ARCHITECTURE · MEMORY · 5 MIN READ

A layered architecture for agent memory

Separate working context, durable state, and long-term recall.

Download example files Code + setup + checks in a ZIP
Jump to a section 12 sections

EXAMPLE USE CASE

Remember a support preference and honor its deletion

A returning user wants English answers, but expired or deleted preferences must not reappear.

Input
Tenant shop-a, user u1, an explicit language preference and its retention deadline.
Expected output
Only that user’s unexpired preference; an empty recall after deletion.
  • Success check: The SQLite lab proves scoped recall, expiry and source-record deletion with assertions.
  • Try a failure: Query shop-b or insert an expired note. Neither may affect shop-a/u1’s current preference.

Example scope: A real local storage-policy lab. Automatic extraction, vector indexing and deletion reconciliation are separate production components.

PostgreSQL exampleMem0 exampleRedis example
SEE HOW THE SYSTEM FITS TOGETHERSELECT A COMPONENT
goalcontextrecallcandidatesvalidatedresumeUser requestVerified identity + goalAgent loopCurrent task controllerContext builderBudget and rank evidenceMemory storesFacts, vectors and graphWrite policyExtract, verify, expireCheckpointsResume this run
  1. Resolve the authenticated tenant, user and current task before reading any state.

  2. Use the bounded context to decide a next step. Save progress separately from proposed long-term memories.

  3. Combine trusted instructions, the active request, scoped recall and the relevant checkpoint within a token budget.

  4. Retain source facts with provenance and expiry; use derived indexes for recall under the same access scope.

  5. Accept only permitted memory types, verify their source and resolve corrections before writing.

  6. Store execution progress by authenticated thread/run. A checkpoint is not a permanent user preference.

Agent loop

Use the bounded context to decide a next step. Save progress separately from proposed long-term memories.

Follow the arrows, then select a component to inspect its responsibility. On mobile, downward arrows connect the next step; bent arrows identify branches and return paths. Select a destination to jump to that component.

Components for this use case

  • PostgreSQL owns facts, versions and deletion records. Mem0 or LangMem can propose/extract recallable preferences. Redis is useful for expiring hot state.
  • Keep checkpoints for execution, preference records for future recall, and vector/graph indexes as derived data with reconciliation.

The request path

  • Authenticate the request and establish tenant, user, and thread identifiers.
  • Load the current thread checkpoint.
  • Retrieve a small set of relevant long-term memories.
  • The context builder selects and ranks these inputs within the model’s context budget.

The write path

  • After the turn, a separate policy identifies candidate facts.
  • Record provenance, subject, timestamps, and expiry.
  • Check for conflicts before replacing older information.
  • Mem0, Letta, Zep, Cognee, or application-owned logic can play different roles in this layer.

Choose a store for each responsibility

  • PostgreSQL: explicit records, ownership, and transactional application state.
  • pgvector or a vector database: semantic retrieval of selected memory records.
  • Redis: time-bounded context and caches, with deliberate persistence settings.
  • A graph store: relationships and time-aware links between entities.

Failure modes to test

  • Test cross-tenant access, stale preferences, conflicting memories, irrelevant recall, and deletion propagation.
  • A persistent store does not make a remembered statement true.
  • Preserve the evidence behind important facts.

Set up the lab

  • Python 3.11 or newer. This local lab exposes the control flow without a model call.
  • Use an empty directory; the example may create a local SQLite file.
Shell
python3 -m venv .venv
source .venv/bin/activate

Implement the example

Save as memory.py

Python · memory.py
import sqlite3
import time

con = sqlite3.connect(":memory:")
con.execute("CREATE TABLE memory (tenant TEXT, user TEXT, key TEXT, value TEXT, expires REAL, PRIMARY KEY (tenant,user,key))")
def remember(tenant, user, key, value, ttl):
    con.execute("INSERT OR REPLACE INTO memory VALUES (?,?,?,?,?)", (tenant,user,key,value,time.time()+ttl))
    con.commit()
def recall(tenant, user):
    return dict(con.execute("SELECT key,value FROM memory WHERE tenant=? AND user=? AND expires>?", (tenant,user,time.time())))

remember("shop-a", "u1", "language", "English", 3600)
remember("shop-a", "u1", "old-note", "expired", -1)
assert recall("shop-a", "u1") == {"language": "English"}
assert recall("shop-b", "u1") == {}
con.execute("DELETE FROM memory WHERE tenant=? AND user=?", ("shop-a", "u1"))
con.commit()
assert recall("shop-a", "u1") == {}
print("scoped recall, expiry, and deletion passed")

Run and verify

Shell
python memory.py
  • The expired note never appears; another tenant cannot recall the preference.
  • User deletion removes the source record. A vector-backed implementation must also delete embeddings and caches.

Troubleshooting and failure tests

  • Memory extraction is a proposal: validate sensitivity and consent before persisting it.
  • An empty recall is valid; do not manufacture an old preference.

Before production

  • Separate authoritative facts, inferred preferences, conversation checkpoints, and retrieval indexes.
  • Add provenance, version checks, retention policies, asynchronous index reconciliation, and deletion receipts.

Keep exploring

Add a dedicated memory layer with Mem0Use PostgreSQL and pgvector for agent memoryA context pipeline for a long-running agent