Katkat

Agent Memory and State

By the Katkat team · Updated · 10 min read

Quick overview

Learn how agents keep state: scratchpads, long-term memory, state machines and checkpoints for resuming long tasks, with the trade-offs interviewers probe.

Lesson 30 of 88 · AI Engineering Interview Course

After this lesson you should be able to explain what "memory" and "state" mean for an LLM agent, and why the model's context window is only one of several places to keep them. You should be able to compare scratchpads, long-term memory stores and explicit state machines, and describe how to checkpoint a long-running agent so it can resume after a crash without repeating work or side effects.

State is everything needed to continue

An LLM is stateless between calls. Every step of an agent loop sends the model a fresh prompt, and anything the model should "remember" must be in that prompt or fetched into it. So agent state is whatever you need, outside the model, to rebuild the next prompt and keep going:

  • The goal and any constraints from the user.
  • The plan, and which parts are done.
  • Tool calls made so far and their results.
  • Intermediate notes and conclusions.
  • Facts learned about the user or the world that should outlive this run.
  • Bookkeeping: step count, retry counts, budgets, run ID.

A useful interview framing is that there are layers with different lifetimes. The context window is working memory and lasts one call. A scratchpad lasts one task. Long-term memory lasts across tasks. Durable run state lasts until the task is finished, even if the process dies. For the base mechanics of the loop, see Tool Calling and the Agent Loop.

LayerLifetimeWhere it livesTypical contentsMain failure mode
Context windowOne model callThe promptEverything the model sees right nowOverflow, distraction, cost
ScratchpadOne taskPrompt, plus a copy in the run storePlan, notes, intermediate resultsDrift, stale or wrong notes
Long-term memoryAcross tasks and sessionsDatabase or vector storePreferences, facts, past outcomesWrong retrieval, stale or poisoned entries
Durable run stateUntil the task endsDatabase or logStep, state name, tool results, budgetsLost on crash if not checkpointed

Scratchpads: working memory you control

A scratchpad is a region of text the agent reads and writes while working. It can take several forms:

  • Free-form reasoning. The model's own intermediate reasoning, as in the ReAct style of interleaving thoughts and actions (see Agent Patterns).
  • A notes file or note tool. The agent calls something like write_note(key, text) and later reads it back. Notes persist even when old messages are dropped.
  • A structured plan. A checklist with statuses such as pending, in progress, done, which the agent updates after each step.

The scratchpad matters because raw history grows quickly. Tool outputs are large, and most of their content stops being useful after one or two steps. A scratchpad lets you compress: keep a short, curated summary of what has been learned, and drop or truncate the raw outputs.

Design choices to be ready to discuss:

  • Who writes it. The model can write its own notes, which is flexible but can drift or record mistakes as facts. The orchestrator can write structured fields from tool results, which is reliable but less expressive. Many systems do both.
  • Format. A structured scratchpad (JSON or a checklist) is easier to validate and resume from than prose.
  • Size cap. An unbounded scratchpad becomes the same problem as unbounded history. Cap it and require the agent to rewrite rather than append.

Worked example: context growth and compaction

Suppose an agent has a 2,000-token system prompt and tool definitions. Each step adds about 1,500 tokens of tool output plus 300 tokens of model reasoning and the call itself, so 1,800 tokens per step. The model has a 32,000-token context window. These are illustrative numbers.

Without compaction. Prompt size before step k+1, after k completed steps, is 2,000 + 1,800k.

  • Fits while 2,000 + 1,800k ≤ 32,000, so k ≤ 16.67. After 16 steps the prompt is 30,800 tokens, and after 17 it is 32,600, which overflows.
  • A 20-step task would reach 38,000 tokens, so it cannot finish.
  • Input tokens billed over a 20-step run (prompts at k = 0 to 19): 20 × 2,000 + 1,800 × (0 + 1 + … + 19) = 40,000 + 1,800 × 190 = 382,000.

With a scratchpad. Keep the system prompt (2,000), a 500-token scratchpad, and only the last 3 raw steps (3 × 1,800 = 5,400). That is at most 7,900 tokens per call, regardless of task length.

  • Upper bound over 20 steps: 20 × 7,900 = 158,000 input tokens, roughly 41% of 382,000. It is a bound because early steps have fewer than 3 raw steps.
  • The cost is information loss: anything not captured in the scratchpad is gone from the prompt.

Compaction also rewrites the prompt prefix, which can defeat provider-side caching of a stable prefix, so the real saving depends on your provider's caching behaviour. See Prefix Caching and Context Windows.

Long-term memory: remembering across tasks

Long-term memory stores information that should survive beyond one run. It is usually split into kinds:

  • Semantic memory: durable facts and preferences ("user prefers metric units", "the staging database is read-only").
  • Episodic memory: records of past runs and what happened ("last time this migration failed because of a missing index").
  • Procedural memory: learned instructions or tips, sometimes stored as edited prompt text or reusable skills.

The mechanism has three parts.

  1. Write. Decide what is worth storing. Writing everything creates noise. Common approaches are letting the model call a remember tool, or running a separate extraction step at the end of a task that proposes memories. Store each item with metadata: user or tenant ID, timestamp, source, and a confidence or importance field.
  2. Retrieve. At the start of a task, or when the agent asks, fetch relevant entries. This is usually embedding similarity over a vector index (see Embeddings and Vector Search), often combined with filters on user, recency or type. Retrieved memories are inserted into the prompt, so they compete for context space.
  3. Maintain. Deduplicate, resolve contradictions (a new preference replaces the old one), expire stale entries, and let users inspect and delete memories.

The MemGPT paper is a well-known example of treating the context window like fast memory and external storage like slower memory, with the model managing movement between them. For chat-specific techniques see Conversation Memory for Chat Applications.

Risks to name in an interview: retrieving the wrong memory and confidently applying it, leaking memories across users if scoping is wrong, and memory poisoning, where injected content from a web page or document gets saved and then influences future runs. Treat memory writes from untrusted content as a security boundary.

State machines: making control flow explicit

A pure "let the model decide everything" loop is flexible but hard to test and resume. A state machine makes the control flow explicit. You define named states, allowed transitions, and what data each state reads and writes. The model still does the work inside states, and may choose among permitted transitions, but the orchestrator owns the structure.

Example for a refund agent:

  • gather_info → check_policy → propose_action → await_approval → execute_refund → notify_user → done
  • Failure edges: check_policy → escalate_to_human; execute_refund → retry (bounded) → escalate_to_human.

Benefits:

  • Testability. Each state can be tested alone with fixed inputs.
  • Safety. Dangerous tools are only reachable from specific states, and approval states block until a human responds.
  • Resumability. The current state name plus its data is the checkpoint.
  • Bounded behaviour. Transitions and retry counters make infinite loops easier to prevent.

The trade-off is rigidity. A workflow that is too strict cannot handle unexpected requests. A common compromise is a graph of states with a flexible agent loop inside some of them.

Checkpointing and resuming long tasks

Long tasks fail: processes crash, deploys restart workers, rate limits hit, humans take hours to approve. Resumability means persisting enough to continue from the last good point instead of starting over.

What to checkpoint after each step (or at least each side-effecting step):

  • Run ID, current state name and step number.
  • The scratchpad and plan.
  • The model's output and the tool calls it requested.
  • Tool results, stored as recorded values.
  • Retry counts, remaining budget (tokens, money, time).
  • Idempotency keys for side-effecting calls.

Two principles make resume correct:

  1. Replay recorded results; do not regenerate them. A model call is non-deterministic, so re-running it may choose a different action than the one that already happened. On resume, load the log of what actually occurred and rebuild the prompt from it.
  2. Make side effects idempotent. Suppose the agent sent an email and crashed before saving the result. Resuming would send it twice. Record the intent with a deterministic key (for example run ID plus step number) before executing, pass that key to the tool or API if it supports idempotency, and check on resume whether the action already completed.

Example: a 20-step task crashes after step 14, with about 6 seconds per step. Without checkpoints, a restart repeats 14 steps (about 84 seconds, plus their model and tool costs) and may repeat side effects. With a checkpoint after every step, it reloads the saved state and runs step 15 onward, losing at most the one in-flight step (about 6 seconds). For human approval waits, the process can exit entirely and be restarted by an event when the approval arrives. See Making Agents Reliable for retries and timeouts.

If the model, prompt or tool schemas change between crash and resume, old checkpoints may no longer be compatible. Version your state format and your prompts, and decide whether in-flight runs finish on the old version.

Trade-offs to be ready to discuss

  • More context vs less. Keeping raw history preserves detail but costs money and can distract the model. Aggressive summarisation is cheap but can lose a crucial detail.
  • Model-managed vs orchestrator-managed state. Letting the model manage memory is flexible but inconsistent. Code-managed state is predictable but must anticipate what matters.
  • Checkpoint frequency. Every step gives the best recovery but adds write latency and storage. Checkpointing only before side effects or after expensive steps is a common compromise.
  • Memory precision vs recall. Retrieving more memories raises the chance of finding the right one and the chance of injecting a misleading one.
  • Privacy. Persistent memory stores personal data, so you need scoping, retention limits and deletion.

How does this come up in interviews?

1. "Your agent works on 5-step tasks but fails on 30-step tasks. Why, and what do you change?" Likely causes are context overflow or the model losing track as history grows. Introduce a scratchpad or structured plan, truncate or summarise old tool outputs while keeping the last few steps raw, and cap tool output sizes. Then evaluate on long tasks to confirm that compaction does not drop key facts.

2. "How would you give an assistant long-term memory of each user?" Describe write, retrieve and maintain: extract candidate memories with metadata, store them scoped per user in a vector store, retrieve by similarity plus filters at task start, and dedupe and expire entries. Mention user control (view and delete), and the risk of storing untrusted content as memory.

3. "An agent runs for an hour and the worker crashes midway. How do you resume?" Persist state after each step: current state, scratchpad, model outputs, tool results and idempotency keys. On restart, rebuild from the recorded log rather than re-calling the model for completed steps, and check whether any in-flight side effect already happened before retrying it.

4. "When would you use a state machine instead of a free-form agent loop?" When the process has known stages, risky actions or approval gates, such as payments or deployments. Explicit states give testability, restricted tool access and easy checkpointing. If requests are open-ended, use a flexible loop inside bounded states.

5. "What is the difference between a scratchpad and long-term memory?" A scratchpad is task-scoped working notes, discarded or archived when the task ends. Long-term memory persists across tasks, requires retrieval, and needs governance such as scoping, expiry and deletion. A task may end by distilling scratchpad contents into a few long-term memories.

Common mistakes

  • Treating the context window as the only memory and appending every tool output forever.
  • Summarising history without keeping a structured record of decisions, so the agent repeats failed actions.
  • Resuming by re-running the model on the original request and hoping it makes the same choices.
  • Retrying side-effecting tool calls with no idempotency key, causing duplicate emails, charges or tickets.
  • Saving everything to long-term memory, then retrieving noisy or contradictory entries.
  • Storing content from untrusted sources as memory without checks, enabling persistent prompt injection.
  • Sharing a memory store across users without strict scoping.
  • Changing prompts or state schemas without versioning, which breaks in-flight runs.
  • Making a state machine so rigid that it cannot recover from an unexpected user request, or so loose that it adds no safety.