Agent memory and state

Part of the free LogicWiz Data Engineering course, Module 16: Databases for AI agents. The SQL and Python run in the app, on real Postgres and real Python in the browser.

It is 9:00 on Monday. Hana Kim types: "Has my tote refund come through yet?" On Friday she returned that tote through the assistant, in a long, friendly chat. Today it replies: "Which order do you mean?" There is worse in the queue. On Wednesday a worker crashed half-way through a refund for Freya, the run was retried, and she was refunded twice. Nora: "It forgets what it should keep, and repeats what it should not."

You'll learn to

  • Load the last few messages of a thread for the model
  • Rank long-term memories by relevance, recency and importance
  • Save a checkpoint after every step and resume from it
  • Make a retried step safe with an idempotency key

Learn

By Monday the assistant had forgotten

Friday's chat happened. The model that had it remembers none of it. A model keeps nothing between calls: whatever it should know on Monday, your code has to load from a table and put in front of it.

An agent keeps three kinds of data, each in its own table.

  • Messages: the conversation itself, in order. One conversation is called a thread, with an id such as t-201.
  • Memories: facts worth keeping across threads, such as "prefers email".
  • Checkpoints: a note of where a run stands after each step, so it can pause, crash and carry on.

Hana's Monday question opened a new thread, t-202. Friday's messages were not loaded, and nothing else was either.

Three tables, three jobs

Three tables side by side: messages holds one row per message of a thread, memories holds one fact per row about a customer, and checkpoints holds one row per thread and step with the state of a run.

Read each box as one table with a few of its rows. Messages are kept for days to weeks, memories until they go stale or the customer asks you to forget, and checkpoints only while a run may still need them.

This chat: the last few messages

Start inside one thread. On every turn the model has to read the conversation so far, because it remembers none of it.

But it cannot read forever. The amount of text a model can take in at once is called its context window, and every token in it costs money. So each turn loads only the last few messages: sort newest first, keep 3, then sort them back into reading order.

The last few messages of a thread

SELECT seq, role, content
FROM (
  SELECT seq, role, content
  FROM messages
  WHERE thread_id = 't-201'
  ORDER BY seq DESC
  LIMIT 3
) AS last_three
ORDER BY seq;

Three rows: the end of Hana's Friday chat, in reading order. The inner query takes the newest 3 and the outer one turns them round. The key (thread_id, seq) makes this an index lookup.

A long chat costs more every turn

What about turn 40 of a long chat? If you send the whole thread every time, each turn carries all the turns before it.

Say one turn, a question and its answer, adds 300 tokens (a made-up size):

  • Turn 2 carries 300 tokens of history.
  • Turn 10 carries 300 × 9 = 2,700.

Add up all 40 turns and the history alone comes to 300 × (0 + 1 + ... + 39) = 234,000 tokens.

The fix is a window plus a summary. Keep the last 3 turns word for word: 900 tokens. Replace everything older with a running summary of about 400 tokens, which a model rewrites every few turns. No turn then carries more than 1,300 tokens. That makes 48,600 over the same 40 turns, 79% less.

You pay for it in two ways. The summary is written by a model call too. And a fact dropped from the summary is gone. So anything that matters later, an order number or a promise made, also goes into memories or the run's state.

History tokens sent with one turn

Bars comparing history tokens per turn: the full history grows from 2,700 tokens at turn 10 to 11,700 at turn 40, while a window of 3 turns plus a summary stays at 1,300.

Compare the two red bars with the two green ones. The full history keeps growing. The window plus summary stays the same from turn 5 on.

Across chats: what to keep about Hana

Monday's thread is new, so its message list is empty. What should carry over from Friday is not the whole chat. It is a few facts: she returned the tote, she wants email, she likes long straps.

Each fact is one row in memories: a short sentence, its embedding, an importance from 1 to 10 set when it is written, and the time it was last used.

For a new question the agent recalls the few that matter now. Three signals decide:

  • Relevance: cosine similarity between the question and the memory.
  • Recency: 0.9 ^ days since it was last used. That is 1 today, 0.73 after 3 days, almost 0 after three months.
  • Importance: the stored number, divided by 10.

Add the three and keep the top 3.

Recall Hana's memories for "has my tote refund come through?"

WITH scored AS (
  SELECT memory_id,
         content,
         cosine_sim(embedding, '{0.1,0.8,0.5,0.2}') AS similarity,
         DATE '2025-06-16' - last_used_at::date AS days_ago,
         importance
  FROM memories
  WHERE customer_id = 13
)
SELECT memory_id,
       content,
       ROUND(similarity::numeric, 3) AS similarity,
       ROUND(0.9 ^ days_ago, 3) AS recency,
       importance,
       ROUND((similarity + 0.9 ^ days_ago + importance / 10.0)::numeric, 3) AS score
FROM scored
ORDER BY score DESC, memory_id;

WHERE customer_id = 13 comes first: memories are personal, so the filter is not optional. DATE '2025-06-16' stands for "today". In production it is current_date, fixed here so the result never changes. Add LIMIT 3 to keep the top 3 for the prompt.

Why the email memory beats the payment memory

Four bars, one per memory, each split into similarity, recency and importance: the tote return scores 2.467, the email preference 1.861, the long straps 1.809, and the bank transfer memory 1.271 because its recency has almost gone.

Each bar is one memory, and its length is its score. Compare the teal parts of memory 5 and memory 1: the payment memory is more relevant. But it is 23 days old, so its violet part has almost gone, and the email preference takes the place in the top 3. That is what the reply needs. The weights are a choice. A well-known research agent (Generative Agents, 2023) scored memories this way, and teams tune the weights on real conversations or require a minimum similarity first.

Look at which part of that query does the heavy work: WHERE customer_id = 13. A B-tree index on customer_id finds Hana's 40 memories, and Postgres scores those 40 exactly. A vector index over everyone's memories would be Lesson 16.4's trap: 40 candidates, nearly all of them other customers'.

The total still adds up. Two million customers × 40 memories is 80 million rows. So teams embed memories with a small model, cap the memories per customer, and run a nightly consolidation job. It merges near-duplicates and drops memories that are both old and unimportant.

Where a run stands

Memory is what the agent knows. State is where a piece of work has got to.

A run can take many steps. Workers restart, new versions are deployed, and some steps wait hours for a person, such as a colleague approving Freya's refund. You cannot keep that run in a program's memory.

So after every step the agent saves a checkpoint: one row keyed by thread and step, holding everything needed to carry on, as JSON in a JSONB column. To resume, load the newest checkpoint of the thread and continue from its next step.

Where is every thread right now?

SELECT DISTINCT ON (thread_id)
       thread_id,
       step,
       node,
       state ->> 'next' AS next_step,
       state ->> 'waiting_for' AS waiting_for
FROM checkpoints
ORDER BY thread_id, step DESC;

DISTINCT ON (thread_id) keeps the first row of each thread in the ORDER BY, here the highest step: the latest checkpoint (Module 2's "keep the latest row"). Thread t-201 is finished: its next is null. Thread t-301 is paused before refund, waiting for approval. When the colleague approves, a worker loads this row and runs the refund with state ->> 'amount'.

Freya was refunded twice

Now Wednesday's bug. The approval came, a worker loaded the checkpoint and ran the refund step. The money went out. Then the worker died, before it could save that step.

The retry did what it should. It loaded the latest checkpoint, saw that the refund step was not saved, and ran it again. The payment provider paid again.

A resume always runs the unfinished step again. For a read, that is harmless. For a step that changes the world, you give the call a name the other side can recognise: an idempotency key, built from the thread and the step. The provider sees the same key twice and pays once.

A crash, a retry, one refund

Six frames of a four-step refund run with its checkpoints table and the payment provider: steps 1 and 2 are saved, step 3 pays the refund with a key, the worker dies before saving step 3, the retry resumes at step 3, the provider recognises the key and pays nothing more, and steps 3 and 4 are saved.

  1. Steps 1 and 2 run and are saved. Each finished step writes one row to the checkpoints table. No money has moved.

  2. Step 3 pays the refund. The tool sends 142.44 USD to the payment provider with the key t-301:refund. The provider records the refund and the key.

  3. The worker dies. The refund is paid, but the checkpoint for step 3 was never written. The table still ends at step 2.

  4. The retry resumes. A new worker loads the newest checkpoint, step 2, and starts again at step 3. It has no way to know the refund already happened.

  5. The provider knows the key. The refund call arrives a second time with t-301:refund. The provider answers "already refunded" and pays nothing.

  6. The run finishes. Steps 3 and 4 are saved. Four checkpoints, one refund of 142.44 USD.

Watch the right-hand box. It never holds more than one refund, however many times step 3 runs. Without the key, the second call would pay a second refund.

A crash, a resume, and why tools need idempotency keys

checkpoints = []            # stands in for the checkpoints table
refunds = []                # stands in for the payment provider

def refund(order_id, amount, key):
    """Idempotent: a second call with the same key changes nothing."""
    if any(r["key"] == key for r in refunds):
        return "already refunded"
    refunds.append({"key": key, "order_id": order_id, "amount": amount})
    return "refunded"

STEPS = ["look_up_order", "check_policy", "refund", "reply"]

def run(thread_id, crash_after=None):
    done = [c["step"] for c in checkpoints if c["thread_id"] == thread_id]
    start = max(done) + 1 if done else 1        # resume after the last saved step
    for step in range(start, len(STEPS) + 1):
        node = STEPS[step - 1]
        if node == "refund":
            print("  ", refund(1012, 142.44, key=f"{thread_id}:refund"))
        if node == crash_after:
            print("   worker crashed before saving step", step)
            return
        checkpoints.append({"thread_id": thread_id, "step": step, "node": node})
        print("   saved step", step, node)

print("first try:")
run("t-301", crash_after="refund")
print("resumed:")
run("t-301")
print("refunds:", len(refunds), "total:", sum(r["amount"] for r in refunds))

The same story in code. The refund ran, the worker died before saving step 3, and the resumed run did the refund step again. The key t-301:refund turned the second call into "already refunded". Payment providers such as Stripe accept exactly such a key. Any tool that changes something needs one.

Remember: a resume runs the unfinished step again. A step that changes the world needs an idempotency key.

Inside a real checkpointer

The tables so far are a teaching version. Here is what a real framework stores.

LangGraph runs an agent as a graph of steps it calls nodes. One round of nodes that run together is a super-step, and it saves a checkpoint after each. Its Postgres checkpointer, PostgresSaver, splits a checkpoint across three tables:

  • checkpoints: one row per super-step, with a pointer to the row before it.
  • checkpoint_blobs: the big values, such as the message list, written again only when they change.
  • checkpoint_writes: the outputs of nodes that finished in a super-step that did not. These are called pending writes. On resume, those nodes are not run again.

The catch is the message list. It changes every step, so every step stores a full copy of a growing list.

LangGraph's Postgres checkpointer: the tables

Four boxes for the tables PostgresSaver creates: checkpoints with its key and parent pointer and JSONB checkpoint and metadata, checkpoint_blobs keyed by channel and version, checkpoint_writes holding pending writes per task, and checkpoint_migrations holding the schema version.

Each box is a table, with its primary key under the name. LangGraph calls each piece of state a channel, and the message list is one. The column names are from the library's own migrations. Each table also has an index on thread_id, because almost every read is "this thread".

Walk a thread's history through parent pointers

WITH RECURSIVE history AS (
  SELECT checkpoint_id, parent_checkpoint_id, metadata, checkpoint, 1 AS depth
  FROM lg_checkpoints
  WHERE thread_id = 't-301'
    AND checkpoint_id = (SELECT MAX(checkpoint_id) FROM lg_checkpoints WHERE thread_id = 't-301')
  UNION ALL
  SELECT c.checkpoint_id, c.parent_checkpoint_id, c.metadata, c.checkpoint, h.depth + 1
  FROM lg_checkpoints AS c
  JOIN history AS h ON c.checkpoint_id = h.parent_checkpoint_id
  WHERE c.thread_id = 't-301'
)
SELECT depth,
       checkpoint_id,
       parent_checkpoint_id,
       (metadata ->> 'step')::int AS step,
       checkpoint -> 'channel_versions' ->> 'messages' AS messages_version
FROM history
ORDER BY depth;

Checkpoint c04 was a bad step 2. A developer went back to c03, fixed the state and ran on, which made c05 a second child of c03. Walking parents from the newest checkpoint follows the live branch only, so c04 is not in the result. That is why the history is a chain of parents, not "all rows of the thread ordered by step": two rows share step 2.

What to forget, and when

Agent tables grow fast and hold personal data. Postgres has no built-in expiry, so you build one.

  • Messages: an expires_at, or a cut-off on created_at, and a scheduled job that deletes in batches of a few thousand rows, so no single delete holds locks for long.
  • Monthly partitions for messages and checkpoints: dropping a whole month is instant and leaves nothing for VACUUM (Modules 4 and 6).
  • Checkpoints: a finished thread needs its last checkpoint at most. Delete the older ones, and the blobs that no checkpoint points to.
  • Memories: expire the unused, unimportant ones. Let customers see and delete theirs.
  • "Forget me": delete by customer_id everywhere, vectors included.

A resume replays the step that was running. For a read that is harmless. A write (a refund, an email, a cancellation) happens twice unless the tool is idempotent. Give every call that changes something an idempotency key built from the thread and the step, and save the checkpoint right after it. And treat memories as hints, not facts: "pays by bank transfer" was true in May. Check the database before you act on one.

Numbers to remember

WhatValueGood to know
History with the full thread300 × (t − 1) tokens on turn t: 234,000 over 40 turnsGrows with the square of the turns
Window of 3 turns plus a summary900 + 400 = 1,300 tokens a turn at most: 48,600 over 40 turns79% less. Older turns live on as a summary row in messages
Recency0.9 ^ days0.729 after 3 days, 0.089 after 23
One customer's 40 memories40 × 6,152 bytes = 246 kBScored exactly, after a B-tree lookup on customerid
80 million memories492 GB of vectors at 1,536 float32 numbers, 124 GB at 384Why teams use a small embedding model and store memories as halfvec
LangGraph PostgresSaverCall .setup() once to create its tablesThe thread id is passed in each call's config
Blobs of one 40-step threadClose to 1 MBA history of 6,000 tokens on average is about 24 kB at roughly 4 bytes a token, copied on every step
Deleting vectorsVacuuming an HNSW index can take a whilepgvector's README suggests reindexing first

LangGraph also has checkpointers for SQLite and Redis, and a separate store for long-term memories with vector search. Mem0 and Letta manage long-term memory for you, and several agent SDKs can store conversation sessions too. Underneath sit tables much like these three, with the same questions: what is kept, for how long, and who may read it.

What changed at SwiftKart

Hana asks again. This time the turn loads her three best memories first, so the assistant knows about the tote from order 1053, checks the refund and promises an update by email, not by text.

Freya's second refund is being recovered, and every tool that moves money now carries a key.

Nora reads the refund tool's code and stops at a different line: the agent connects to Postgres as a user that can read and write every table. Lesson 16.6 gives the agent a database role that can only do what it should.

In one line

Keep messages per thread and load the last few, rank long-term memories by similarity, recency and importance, and save a checkpoint per step so a run can resume, with idempotent tools and clear retention.

Interview corner

How would you give an AI assistant memory?

Short-term memory is the message history of the current thread: load the last N messages plus a running summary into each prompt. Long-term memory is a table of facts per user with embeddings, importance and timestamps, recalled by a mix of similarity, recency and importance and always filtered by the user. Both are personal data, so they need retention rules and a way to delete them on request.

What is a checkpoint in an agent framework, and how does an agent resume after a crash?

A checkpoint is the full state of a run saved after each step, keyed by thread and step (LangGraph stores it as JSONB in Postgres with a parent pointer). To resume, a worker loads the thread's latest checkpoint and continues from its next step. The step that was running during the crash runs again, so tools with side effects must be idempotent, for example with an idempotency key.

What retention rules would you set for agent data?

Messages: a fixed window such as 30 days, keeping summaries if needed. Checkpoints: only the latest per finished thread, with full history kept for threads under investigation. Memories: expire unused low-importance ones and let users see and delete theirs. All of it must honour erasure requests across tables and the vector index, run as a scheduled job, ideally on monthly partitions.

Your checkpoint store grew to several terabytes in a month. Why, and what do you change?

In a checkpointer like LangGraph's, a channel value is stored again whenever its version changes, and the message list changes every step, so a 40-step thread with about 24 kB of history on average stores close to 1 MB, and a million threads a month is about a terabyte. I would keep only the latest checkpoint of finished threads and delete blobs no checkpoint references, partition by month so old data is dropped rather than deleted, keep messages as a window plus a summary so the list stays short, and move long-lived facts into a memories table. Then I would chart bytes per thread so the next regression shows up early.