Home›Design›Agent memory and state
Design doc · Agent memory and state

Agent memory and state

Where should an AI agent keep its conversations, its progress and what it remembers?

Applications like this: a support agent, a coding agent, an assistant inside a SaaS product, any program that calls a model in a loop and uses tools. This page is written the way I write a database design doc: the workload first, then where each kind of data goes and why, then how it grows, what breaks, and what I rejected. The vector numbers on it were measured, in Notebook 8.

The short answerOne PostgreSQL with pgvector holds the run log, the checkpoints and the long-term memories, with tenant_id in every memory key, and thread ids scoped per tenant for checkpoints. Redis holds the working memory of runs in progress. Turn on iterative scan for filtered memory search, and give memories an expiry by default.
1 · The workload

What the application asks of the database

DimensionThis application
WritesMany small writes per run: each step adds messages, a tool call and a checkpoint.
ReadsEach step reads the recent conversation, the latest checkpoint, and searches long-term memory.
Read to writeClose to one to one for run state. Memories are read more than written.
ConsistencyStrict for checkpoints: resume from exactly the last step. Loose for memory search: a memory saved a second ago can be missed.
LatencyMemory search well under 50 ms, because it runs before every model call, and the model call itself takes seconds.
GrowthFast. Every run leaves a log, and memories grow per user for as long as nobody forgets them.
Connected

Real failures behind this design

These incidents are why the choices below matter. Each one is written up with its numbers and sources.

2 · What goes where

Each kind of data, its store, and why

ApplicationRuns, messages and tool calls (the run log)PostgreSQL, partitioned by monthSOURCE OF TRUTHCheckpoints of a running agentPostgreSQL, keyed by (thread_id, checkpoint_id)SOURCE OF TRUTHLong-term memories with embeddingspgvector in the same PostgreSQL, filtered by tenantSOURCE OF TRUTHWorking memory of an active runRedis or Valkey, with an expiryCAN BE LOSTOld run logsObject storage, exported by monthARCHIVE

Solid arrows: the application writes there. Dashed arrows: a copy fed from the source of truth (change data capture, an outbox, or a cache fill), which can be rebuilt from it.

DataWhere it goesWhy
Runs, messages and tool calls (the run log)PostgreSQL, partitioned by monthEvery step of every run, in order. You need it to debug a bad answer, to bill, and to audit what the agent did. Append-only and large, so it is partitioned from day one.
Checkpoints of a running agentPostgreSQL, keyed by (thread_id, checkpoint_id)After a crash or a deploy, the run resumes from its last step instead of starting again. Small, written every step, read back by primary key.
Long-term memories with embeddingspgvector in the same PostgreSQL, filtered by tenantFacts and summaries the agent should recall later. In the same database, a memory, its tenant and its permissions are one row and one query.
Working memory of an active runRedis or Valkey, with an expiryScratch state, rate limits and locks for runs in progress. Fast, short-lived, and safe to lose because the checkpoint has the durable state.
Old run logsObject storage, exported by monthKept for audit and evaluation, rarely read, far cheaper than database storage.

How each family of store behaves under traffic: Database families. Retrieval over documents rather than memories: Search and AI retrieval.

3 · Data model

The core tables and the queries they serve

CREATE EXTENSION IF NOT EXISTS vector;

CREATE TABLE checkpoints (
  thread_id     text   NOT NULL,
  checkpoint_id bigint NOT NULL,
  state         jsonb  NOT NULL,
  created_at    timestamptz NOT NULL DEFAULT now(),
  PRIMARY KEY (thread_id, checkpoint_id)
);

CREATE TABLE tool_calls (
  run_id     uuid   NOT NULL,
  step       int    NOT NULL,
  tenant_id  bigint NOT NULL,
  tool       text   NOT NULL,
  args       jsonb,
  result     jsonb,
  ms         int,
  created_at timestamptz NOT NULL DEFAULT now()
) PARTITION BY RANGE (created_at);

CREATE TABLE memories (
  id           bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  tenant_id    bigint NOT NULL,
  subject_id   bigint NOT NULL,          -- the user the memory is about
  body         text   NOT NULL,
  embedding    vector(1024) NOT NULL,
  model        text   NOT NULL,          -- which embedding model made it
  created_at   timestamptz NOT NULL DEFAULT now(),
  last_used_at timestamptz,
  expires_at   timestamptz
);
CREATE INDEX ON memories USING hnsw (embedding vector_cosine_ops);
CREATE INDEX ON memories (tenant_id, subject_id);

-- resume a run
SELECT state FROM checkpoints
WHERE thread_id = $1 ORDER BY checkpoint_id DESC LIMIT 1;

-- recall: this tenant's nearest memories
SET hnsw.iterative_scan = relaxed_order;
SELECT id, body FROM memories
WHERE tenant_id = $1 AND (expires_at IS NULL OR expires_at > now())
ORDER BY embedding <=> $2
LIMIT 8;
4 · How it grows

Start simple, change one thing at a time

  1. One PostgreSQL for everythingRun log, checkpoints and memories in one database with pgvector. No sync problem.
  2. Many runs at onceWorking memory moves to Redis and a pooler goes in front of PostgreSQL, so parallel runs do not exhaust connections.
  3. The memory index outgrows memoryPartition memories by tenant, or move the vectors to a dedicated store fed from PostgreSQL, which stays the source of truth.

Scale it: watch this design grow

Pick a stage, then throw something at it. The numbers are a model to show the shape of each change, not a measurement; the measured numbers are in the lab notebooks.

5 · What breaks first

The failures to plan for

What happensWhat you seeWhat I do
Filtered memory search returns too few rowsThe agent "forgets" things it was told yesterdayTurn on hnsw.iterative_scan (pgvector 0.8 and later), or for small tenants search exactly within the tenant. In Notebook 8 the plain filtered search returned 1.3 rows out of 10. Iterative scan is bounded by hnsw.max_scan_tuples (20,000 by default), so on a very selective filter raise it or fall back to exact search.
Parallel runs open hundreds of connectionsConnection errors and memory pressure on the database when traffic peaksA pooler (PgBouncer) in front, and a cap on concurrent runs per tenant.
The run log dominates storage and backupsBackups and restores get slow, and the bill grows every monthMonthly partitions, export old months to object storage, drop the partition.
Memories are never forgottenOld, wrong facts outrank new ones; the store grows foreverAn expiry by default and a last-used time on every memory, recency in the ranking, and merging duplicates when a memory is saved.
Embeddings from two models in one indexSearch quality drops quietlyStore the model name on every row and re-embed in one pass when you change models.
A memory saved or found under the wrong tenantOne customer's data in another customer's answertenant_id in every key and every query, and row-level security as a backstop.
6 · Alternatives

What I considered and did not pick

Cost. In Notebook 8 a 384-dimension memory took 3,689 bytes with its HNSW index, 2.4 times the raw floats. At 1,024 dimensions, plan for about 10 KB per memory plus its text, and keep the index in memory.

How this page was writtenFrom the engines' documentation, pgvector's documentation, and common practice in agent frameworks. Measured on real servers: storage, recall and filtered search in Notebook 8. Before you build: check the anti-patterns, size it with the capacity calculator, and write your own version from the design doc template. Want a second opinion? The agents review.
7 · Where to run it

On-prem, managed, EC2 or Kubernetes

StageWhere it runs
Where I would startManaged PostgreSQL with pgvector, plus managed Redis or Valkey
When it growsThe same, with a pooler in front. A dedicated vector service only once the memory index outgrows one machine's memory

For a team without a dedicated database team. Who does which job in each option, and the full-cost comparison: Where to run the database.

8 · Estimate it

The numbers, worked live

The back-of-the-envelope numbers I would want before choosing anything. Move the assumptions to match your application. The link keeps your numbers, so a colleague sees the same ones.

Part 3 of 4 · Design · 24 pagesAll pages

Which database does my application need? What kind of application data goes in which database, and why, as design docs, plus the anti-patterns and the decisions behind them.