esc
  • WorkflowsPages
  • Case studiesPages
  • Machine Learning FoundationsLearn
  • AI EngineeringLearn
  • AI Guardrails & Red TeamingLearn
  • UI/UXLearn
  • Design SystemsLearn
  • Production System DesignLearn
  • AI papersPages
  • Interview KitPages
  • Book a callContact
  • Download ResumeContact
Let’s talk

I’ll build the agent for it.

How Do You Manage Agent State?

Where an AI agent keeps what it needs between steps and runs, how to save and resume it safely, and what goes wrong, for your AI interview.

In short

Agent state is everything the agent needs to carry on: the steps done, the tool results and what has already happened outside the model. Keep it in a database under a run ID, save it after every step, and give every repeatable action, like a payment, a key so a retry is safe.

12 min readIntermediateCommon · estimateFacts checked 26 November 2026

Say it out loud

Read it once, then say it without looking. Start with the short one; use the long one when they ask you to go deeper.

Agent state is everything the agent needs to carry on: the steps done, tool results, and what has already happened in the real world. The model itself keeps none of it between calls, so my code saves it in a database under a run ID after every step. When the run resumes, it loads that saved record and carries on. Any action that could repeat, like a payment, gets a unique key, so a retry is safe if the payment service honours that key.

What is agent state, in plain words?

Agent state is everything an agent needs to carry on: the conversation so far, the steps it has finished, the results of its tool calls, and a record of what already happened outside the model, such as a payment that went out.

The model itself keeps none of that between calls. Some platforms can store a chat for you, but the agent's own steps and payments still need a record your code controls, so a pause, a crash or a new day does not wipe out the job.

Think of a hospital shift handover. The nurse who leaves writes the notes, and the nurse who arrives reads them instead of trusting memory. A real case: a claims agent at an insurer reviews a car claim over several days, and an adjuster has to sign off in the middle. The agent must pick up at the right step, with the right money already paid or not.

Key words

Context window
The text the model can see in one call. It has a fixed size.
Run
One agent job from start to finish. It can pause and restart.
Run ID
A key that ties every saved step to one run, so the agent finds its place again.
Idempotency key
A unique ID for one action, like a payment. A repeat returns the first result.
Compaction
Replacing old chat turns with a summary when the window fills up.

Where does an agent keep its state?

There are three places state can sit, and each one lasts a different time.

Where an agent's state lives

Agent takes a step

reads, calls tools, decides

Kept in three places

Context window

cleared when the run ends

Run state in a database

saved after every step

Long-term store

preferences and facts, all runs

Next run resumes

loads the saved record

  1. 1The model reads its working text from the context window.
  2. 2Each finished step is saved to the database.
  3. 3A later run loads that saved record and carries on.
  4. 4Long-term facts, like a user's preferences, are read on purpose.
The agent reads its working text from the context window, which is lost when the run ends. Each finished step is saved to a database, and the next run loads that record. Long-term facts sit in a store that any run can read.
  • Context window

    Inside one call

    The text the model sees right now. It has a fixed size, and it is gone when the run ends.

  • Run state

    In a database, per run

    Keyed by a run ID and saved after every step. A pause, a crash or a restart loses nothing already saved.

  • Long-term store

    Across all runs

    Facts a later run may need, such as a user's preferences. Saved deliberately, and read when a run needs them.

  • “While each text generation request is independent and stateless”

    OpenAI

So the model does not hold the memory. A chat app adds the earlier messages to each call, and an agent does the same with its saved record. LangGraph, a popular agent framework, splits the two jobs the same way: a checkpointer saves one run's state (it calls that run a thread), and a store keeps facts that cross runs.

LangGraph's in-memory option keeps checkpoints (saved snapshots of state) in RAM (the computer's working memory), so when the process restarts, all checkpoints are lost. Its docs say to use a persistent checkpointer for production.

How do you save and resume a run?

Four habits make a run safe to pause, crash and restart.

  1. 1

    Give every run an ID

    LangGraph calls this a thread ID. Its docs say the ID you choose is effectively your persistent cursor, a bookmark for where the run is. Every saved step hangs off it.

  2. 2

    Save after every step

    A crash then loses only the step in progress. When a run pauses, LangGraph saves its state and waits until you resume it.

  3. 3

    Resume from the record

    The new process loads the saved record and carries on at the next step. It never asks the model what it did last time.

  4. 4

    Make repeats safe

    Retries happen. Idempotent means safe to repeat: AWS describes an idempotent operation as one that can be retried with no extra side effects. Give each payment a unique key, and the service returns the first result on a repeat. LangGraph's rules say the same for side effects before a pause.

Here is the idea in 29 lines of Python. The database is a dict, and the payment service remembers keys. The run crashes right after paying and before it saves. The retry finds the key and does not pay again.

Python
# A claim agent's saved state, simplified. A dict stands in for the database.
import json
DB = {}        # run ID -> saved state, written after every step
CHARGES = []   # payments the payment service actually sent
SEEN = {}      # idempotency key -> the result already returned
def pay(key, amount):
    # The payment service sends money only the first time it sees a key.
    if key not in SEEN:
        CHARGES.append(amount)
        SEEN[key] = {"ref": "PAY-" + str(len(CHARGES)).zfill(4)}
    return SEEN[key]
def run_step(run_id, crash_after_pay=False):
    state = json.loads(DB[run_id])  # reload the saved state, not memory
    if state["step"] == 7:
        result = pay(state["claim"] + "-payment", 1250)
        if crash_after_pay:
            raise RuntimeError("process stopped before the state was saved")
        state["step"] = 8
        state["payment_ref"] = result["ref"]
        DB[run_id] = json.dumps(state)
    return state
DB["run-2231"] = json.dumps({"claim": "CLM-2231", "step": 7})
try:
    run_step("run-2231", crash_after_pay=True)
except RuntimeError as err:
    print("Crashed:", err)
state = run_step("run-2231")
print("Step:", state["step"], "Ref:", state["payment_ref"])
print("Payments sent:", len(CHARGES))

Output

Crashed: process stopped before the state was saved
Step: 8 Ref: PAY-0001
Payments sent: 1

The output shows one payment, even though the step ran twice.

What about long chats and long projects?

A long chat fills the window. Compaction handles that by replacing the older turns with a summary. Anthropic says the summary is written on the server, and it covers only the older turns.

A summary is lossy, which means it drops detail. It can drop a detail that matters, such as a document number, so keep hard facts in saved fields, outside the summary.

Long coding projects show the same need. Anthropic's engineering team found that each new session begins with no memory of what came before, so their agent left clear artifacts for the next session and used git (a tool that saves snapshots of code) to revert bad code changes and recover working states.

  • “each new session begins with no memory of what came before”

    Anthropic

Old checkpoints pile up as well, so LangGraph's docs say to prune them on a schedule or set a retention policy (a rule for how long saved data is kept).

How would you stop a claim agent paying twice after a crash?

Setting: a claims agent at a mid-size insurer has reviewed car claim CLM-2231 up to step 6. An adjuster must approve a 1,250 payment, which takes two days, and the server restarts overnight.

A claim that pauses for two days

Claim agent

pauses after step 6 for a human

Between runs

Saved run state

claim ID, steps done, document IDs

Adjuster approves

two days, no model is running

Resumes at step 7

reads the saved record

Payment step

Key already used?

New key sends; used key gets old result

Send payment once

key: CLM-2231-payment

  1. 1Each finished step is saved to the database.
  2. 2The adjuster's approval wakes the run up.
  3. 3The run loads the saved record and carries on.
  4. 4Before paying, the payment service checks the key.
  5. 5Only a new key sends money, so a retry cannot pay twice.
The run saves after each step and pauses until the adjuster approves. On the payment step, the key is checked first, so a retry after a crash returns the first payment instead of sending another.
  • No key

    The retry pays again

    The payment call has no key, and a retry after the crash sends a second payment.

  • Key and saved step

    The retry pays nothing new

    The key is checked before paying, and the first reference comes back. The run saves step 8 and moves on.

My answer: the state lives in a database keyed by the claim, saved after each step, and the payment carries a key set before the call. I would test it by stopping the process right after a payment and counting the payments sent. The honest limit is that the payment service has to honour the key, so that part sits outside our code.

What does the interviewer want to hear?

A strong answer covers

  • A plain definition: everything the agent needs to carry on.
  • The model itself keeps nothing between calls, so your code saves the state.
  • Three places: the context window, the run state and a long-term store.
  • Save after every step, and resume from the saved record.
  • Idempotency keys, so a retry can't repeat a payment.
  • Honest limits: summaries drop detail, and saved state needs backups.

Common traps

  • Trap"The model remembers what it did last time."

    BetterEach call is independent. Keep the record in a store you control, and the run loads it.

  • Trap"Just keep the whole chat in the prompt."

    BetterThe window has a fixed size. Save state outside, and send only what the next step needs.

  • Trap"A summary keeps everything that matters."

    BetterSummaries drop details, like a document number. Keep hard facts in saved fields.

Can you spot the risky step?

Spot the problem

Which line in the payment step can send money twice?

Quick check

A claim waits two days for an adjuster. Where must the run's progress live?

Can you answer these from memory?

Flash cards · tap a card to flip it

1 / 6

What will they ask next?

  1. Q163Short-term vs long-term agent memory?12 min
  2. Q176How should an agent handle tool errors and retries?14 min
  3. Q181How do you evaluate agents?11 min
  4. Q182How do long-running agents use checkpoints?12 min
  5. Q174What are common agent failure modes?12 min

Learn it in depth

Last updated on 26 November 2026

Building an agent that has to pause, resume or wait for a person?

I design and build AI agents, the interface and the system behind it, including how their state is saved and resumed. Book a short call and tell me what your agent needs to do.