FullStack AI Hub
Studio
lesson depth
Mastery
not started · 0%

State and Memory

How applications persist working state history summaries facts and user-controlled records.

Freshness: current•15 min read•LLM Application Engineering

Key Learning Outcomes

  • ✓Distinguish state from context
  • ✓Choose memory lifetimes
  • ✓Prevent stale memory
Full Technical Reference Document

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.

Interaction event
Filter & validate candidate memory
Scope tenant, consent & TTL
Persist separate from core SQL state
Hybrid query + freshness check
Render concisely ahead of current turn
Conceptual teaching model synthesized from:Effective Context Engineering for AI AgentsPostgreSQL 16 Architecture, MVCC & Query Optimization Manual

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 CategoryPhysical Backing StoreAuthority & Write GateRetention & Conflict Policy
Core Business StateNormalized PostgreSQL tables (accounts, orders)Strictly deterministic transactions; zero free-form model writesACID foreign-key invariants; immutable audit log
Working Task ScratchpadEphemeral Redis / graph channel per threadRuntime orchestrator + active step reducersDiscarded or summarized deterministically upon completion
Episodic Run TracesAppend-only event stream / analytics warehouseAutomated instrumentation telemetry (redacted PII)Time-bounded compliance retention (30–90 days)
Curated Semantic MemoryVersioned 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 PostgreSQL
CREATE 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 duplicates
fact_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_memory
ON 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.

Reflect before revealing the guide

Why must production agent memory be designed as a governed lifecycle policy rather than simply saving raw conversation logs in a database table?

Prerequisites & Related Concepts (3)

Private notes

0 words
Included In Free Course
Free · Verifiable Credential

FS-102LLM Systems Foundations

Build a connected mental model from tokens through retrieval evaluation security and operations.

24 concepts~18h self-paced
Start Free Course
Weekly Engineering Dispatch

Get the weekly systems teardown

One technical note per week covering inference bottlenecks, retrieval harnesses, and commit-pinned teardowns.

Next