Interview's MateAI Engineering
Interview's Mate

AI Engineering

LLMs, RAG, agents & evals

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
AI Engineering topics
Lesson 55/ 160
03. AI Agents

State and Checkpoints

Persisting agent state so long jobs can pause, resume, and recover after failures.

AdvancedCheckpoint · Resume3 quiz questions
Practice Generative AI Q&A
In plain wordsDiagramTheoryStep by stepWhen to use itInterview cluesMistakes to avoidHands-onQuiz (3)Practice

In plain words

The system saves the agent's progress after each step so it can continue from there if something breaks or if it has to wait for a person.

Think of it like…

Saving a video game at each level: if the game crashes you reload the last save, not the start. But if reloading re-awards a one-time bonus, you've created a bug, which is why each action must be safe to repeat.

Where you’ve seen it

A data-migration agent processes 200 customer accounts, each needing several tool calls. State (the list of completed account ids, current account, step counter, messages) is checkpointed to Postgres after every account. A node crashes at account 137; the job restarts, loads the latest checkpoint, and continues at account 137, not 1. Each write tool takes an idempotency key (migrate-{account_id}), so the partially completed account 137 isn't migrated twice. Total re-work after the crash: one account instead of 136.

Words you’ll hear

Checkpoint
A durable snapshot of run state at a step boundary.
Thread / run id
The key that identifies a run's state for resume and inspection.
Idempotency key
A unique token ensuring repeating an operation has the same effect as doing it once.
Durable execution
Running workflows so progress survives process failures (Temporal, LangGraph with a checkpointer).

Visual diagram

Loading interactive diagram

Theory & deep dive

What to save and when

Save enough to reconstruct the run: conversation messages, structured working state (plan, completed ids, counters), pending tool calls, and metadata (thread id, step number, timestamps, state schema version, model and prompt versions). Don't store secrets in state; keep references to credentials and fetch them at run time. Large artefacts (documents, tool outputs) belong in object storage, referenced by key, to keep checkpoints small.

Checkpoint at natural boundaries: after each node or tool batch, before and after risky side effects, and when pausing for a human. Frameworks such as LangGraph do this automatically per step with a checkpointer; with a hand-written loop, write the state before waiting, and after each tool result. The same mechanism supports time travel: load an earlier checkpoint, optionally edit state, and re-run to debug or branch.

A checkpoint record

{"thread_id": "migrate-2026-11", "step": 137, "state_version": 3, "state": {"done": [1, 2, …, 136], "current": 137, "messages": […]}, "updated_at": "2026-11-20T10:42:07Z"}

Key takeaway: Persist messages and structured state at step boundaries, keep artefacts by reference.

Resuming safely: idempotency, versions and cleanup

When a run resumes after a crash, the last step may have partly executed: the tool call went out but the result wasn't saved. Design side effects so repeating them is harmless: pass idempotency keys to payment, email and database-write APIs, make writes upserts, check "already done?" before acting, and record intent before and completion after. Distinguish at-least-once delivery (steps may repeat; make them idempotent) from exactly-once (hard; usually emulated with idempotency).

Handle change over time. When you alter the state schema or the graph, persisted threads may no longer match: include a state version, write migrations or run old threads to completion on old code, and avoid renaming fields casually. Set retention and cleanup (TTL for finished threads, deletion for privacy requests), cap checkpoint size, and secure the store (contains user data). Add recovery behaviour for failures that aren't crashes: retry with backoff for transient errors, mark a step as failed after N attempts and route to a human, and keep dead-letter records for inspection. Test it: kill the process mid-run in tests and assert that resume produces the right final state with no duplicates.

An idempotent write

payments.refund(order_id, amount, idempotency_key=f"refund-{run_id}-{step}") means a retry after a crash returns the original refund instead of creating a second one.

Key takeaway: Idempotent side effects, versioned state, retention rules and crash tests.

How it works, step by step

Step 1 of 4
Design

1. Decide the state and boundaries

List what must be saved to continue, and choose checkpoint points such as after each tool batch.

messages · plan · done_ids · step
Key numbers at this step
Small
state; big data by reference

When to use it & trade-offs

What it is

Agent state is everything needed to continue a run: the messages, plan, intermediate results, step counters and pending actions. A checkpoint is a saved snapshot of that state, written after each step to durable storage (Postgres, Redis, a database table) under a run or thread id. With checkpoints, a long job can pause (waiting for approval or an external event), resume after a crash or deploy from the last saved step instead of starting over, and be inspected, replayed or forked for debugging. Because resumed steps may re-run, side effects must be idempotent.

Why it matters: Agent runs can take minutes or hours, call dozens of tools and cost real money. Without persistence, a timeout at step 18 of 20 wastes everything, a deploy kills in-flight jobs, and human approvals can't span hours. Checkpointing turns fragile in-memory loops into reliable workflows, but it brings new correctness issues: duplicated side effects, schema versioning and stale state.

When to reach for it

  • Long-running agents and batch jobs
  • Workflows waiting on human approval
  • Debugging via replay and time travel

When to avoid or be careful

  • Non-idempotent write tools in resumable runs
  • Storing secrets or huge blobs inside checkpoints
  • Changing state schemas with live persisted threads and no migration

Ways to survive failures

Checkpointing agent state
Best for: Long LLM workflows, human approvals, debugging

Strengths: Resume, replay and inspect; fits agent frameworks.

Watch out: Needs idempotent steps and schema versioning.

Durable workflow engine (Temporal and similar)
Best for: Business-critical, long-running processes

Strengths: Strong retry and durability semantics.

Watch out: Heavier infrastructure and learning curve.

Restart from scratch
Best for: Short, cheap, side-effect-free runs

Strengths: Simplest.

Watch out: Wastes work and money; unsafe with side effects.

Interview signals & numbers to know

When this topic comes up

  • “The job died at step 18 of 20”
  • “Approval takes hours; how does the agent wait?”
  • “We double-charged after a retry”
  • Idempotency keys
  • Time travel debugging

Benchmarks & rules of thumb

137 of 200 -
crash point in the migration example
1 vs 136 -
accounts redone with vs without checkpoints
at-least-once -
typical delivery guarantee to design for

Common mistakes & follow-ups

Common interview mistakes

  • Resuming a run that re-sends an email because the send wasn't idempotent.
  • Putting API keys into persisted state.
  • Deploying a renamed state field and breaking every paused thread.

Likely interviewer follow-ups

  • How would you make an agent resumable after a crash?
  • Why must tools be idempotent in checkpointed workflows?
  • How do you handle state schema changes?
Interview tip: Always pair "checkpoint" with "idempotent". The two words together show you understand why resuming is risky.
Loading hands-on exercise

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply State and Checkpoints with generative AI interview Q&A and hands-on practice.

Open Generative AI Q&A →Tech Learn Q&A
Previous topic
OpenAI Agents SDK
Next topic
Human in the Loop