Mental model
Application state is authoritative durable business truth governed by deterministic schemas (PostgreSQL accounts, orders, permissions), whereas agent memory is an explicit lifecycle policy deciding which signals get extracted from past interactions, how they are validated, scoped to tenant/user ACLs, decayed over time (TTL), and injected concisely into active prompts. Confusing raw chat transcripts with curated memory creates drift, compliance leaks, and stale overrides.
Learning outcomes
- Separate authoritative relational state cleanly from working scratchpads, episodic execution logs, curated semantic facts, and pinned procedural rules.
- Validate, deduplicate, and resolve conflicts whenever model-inferred memory writes update user preferences or domain assumptions.
- Enforce user consent, right-to-be-forgotten cascading deletes, tenant scoping, and staleness decay cleanly on long-term memories.
Theory
Loading complete historical conversations endlessly into every subsequent turn fails on cost, privacy, and distraction ("needle in a noisy haystack" confusion). Conversely, letting an unconstrained background LLM silently write arbitrary inferred claims into global vector storage without versioning or conflict resolution turns one mistaken assumption ("Prefers Python 2", "Works in EU region") into permanent poisoned truth overriding fresh user queries months later! Production teams distinguish four cleanly scoped lifetimes:
| Memory Category | Physical Backing Store | Authority & Write Gate | Retention & Conflict Policy |
|---|---|---|---|
| Core Business State | Normalized PostgreSQL tables (accounts, orders) | Strictly deterministic transactions; zero free-form model writes | ACID foreign-key invariants; immutable audit log |
| Working Task Scratchpad | Ephemeral Redis / graph channel per thread | Runtime orchestrator + active step reducers | Discarded or summarized deterministically upon completion |
| Episodic Run Traces | Append-only event stream / analytics warehouse | Automated instrumentation telemetry (redacted PII) | Time-bounded compliance retention (30–90 days) |
| Curated Semantic Memory | Versioned DB table + scoped vector index (pgvector) | Explicit validated extraction schema (confidence, evidence_msg_id, ttl_at) | Explicit conflict supersede; current explicit query always wins |
Crucially, fresh explicit user input always overrides stale inferred memory ("Generate this briefing in Rust" beats cached semantic preference "Prefers Go"), and sensitive inferences (health, political views, HR incidents) must never persist silently without explicit policy allowlists and user edit/delete UIs.
sql-- Authoritative tenant-scoped semantic memory ledger in PostgreSQLCREATE TABLE IF NOT EXISTS user_semantic_memories (memory_id UUID PRIMARY KEY,tenant_id TEXT NOT NULL,user_id TEXT NOT NULL,fact_key TEXT NOT NULL, -- Normalized slot key prevents conflicting duplicatesfact_value TEXT NOT NULL,source_thread_id TEXT NOT NULL,consent_confirmed BOOLEAN NOT NULL DEFAULT FALSE,verified_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),expires_at TIMESTAMPTZ,superseded_by UUID REFERENCES user_semantic_memories(memory_id));CREATE INDEX idx_active_user_memoryON user_semantic_memories (tenant_id, user_id, fact_key)WHERE superseded_by IS NULL;
Trade-offs
Full immutable message replay preserves lossless nuance on short single-session workflows (< 20 turns) cleanly with zero extraction infrastructure, yet degrades badly across weeks-long relationships on token cost and stale topic clutter. Curated slot-keyed semantic memory with provenance links and expiration policies preserves tiny crisp prompt sizes across months (< 400 tokens of pinned facts), while introducing memory extraction latency, conflict-resolution complexity, and explicit user inspection UI requirements so errors never ossify silently.
Failure modes and misconceptions
- Treating Vector Transcript Dumps as Memory Architecture: Embedding raw conversational chatter yields conflicting contradictory fragments (
"Use React"vs"Switching away from React") retrieved identically at random. - Letting Stale Inferred Memory Override Explicit User Prompt: Prioritizing retrieved
"usually writes Java"over today's explicit question asking for Python. - Unscoped Sensitive PII Persistence: Silently saving financial numbers or medical remarks mentioned casually in support chats directly into persistent unencrypted memory pools without opt-in consent.
- Orphaned Vector Entries After User Deletion: Deleting rows cleanly from the user settings DB without cascading tombstones into vector memory indexes violates privacy compliance (
GDPR/CCPA).
Decision scenario
An AI coding mentor supports multi-month student projects across browser workspaces. Right now inferred preferences persist forever in an unstructured global index cleanly overriding explicit current-lesson stack requests and breaking user privacy deletion controls. Design separated working scratchpads, explicit opt-in Postgres memory slots (consent_confirmed, superseded_by, expires_at), and clean cascade delete hooks.
Why must production agent memory be designed as a governed lifecycle policy rather than simply saving raw conversation logs in a database table?