Agent State Management
One truth, flowing through stages
Multi-stage agents need state that is typed, versioned, inspectable and resumable — a single source of truth flowing through every stage. State schema design is architecture: where it lives decides what breaks.
What you will learn
- Design typed state contracts across stages
- Version state safely
- Handle concurrent and resumed sessions
What is this?
State management centralizes agent data: the typed state object that every stage reads and extends, stored durably per session, versioned, checkpointed. Stages must not invent their own state; the contract is the single source of truth. Divergence across stages is the #1 source of multi-agent bugs.
Why do you need it?
- Typed state catches contract violations at compile/test time.
- Versioned state survives code evolution over running sessions.
- Checkpoints make long tasks crash-safe and resumable.
- A single truth makes debugging and audit tractable.
Mental model
A patient's shared medical chart
Centralized state
Every specialist (stage) reads and writes the ONE chart — meds, tests, notes. A doctor who keeps their own private chart creates contradictions and endangers the patient. Typed fields, versions, append-only notes; every doctor reads the same truth.
How it works
- Define the state schema (typed, with required fields per stage).
- Store durably per session; checkpoint after stages.
- Version the schema; migrate old sessions.
- Pass state by reference into stages; log mutations.
- Support resume: reload last checkpoint and continue.
State lifecycle.
In production
- Long-running migration agents persist tenant state per batch.
- Multi-stage support flows keep one case state across escalations.
- Undo-friendly systems snapshot state before each write.
Best practices
- One state schema per session, typed and documented.
- Stages extend, don't fork — enforce via interface.
- Checkpoint after consequential stages.
- Version state now; migrating later is painful.
Common mistakes
- Each stage caching its own copy drifts.
- Untyped state (JSON.parse anywhere) — typos become runtime bombs.
- No version tag, so deployments break old sessions.
Common issues
Stage writes state in a different shapeUntyped contract
Enforce types/interfaces at stage boundaries.
Race on concurrent stages writesShared mutable state
Isolate per-branch sub-state; merge deterministically.
Debugging tips
- Cross-stage inconsistencies → audit state mutations per stage; find the fork.
- Resume produces wrong context → checkpoint doesn't capture everything the loop needs.
- Old sessions break post-deploy → schema migration missing.
Interview checkpoint
Hands-on lab
- Declare states and allowed transitions
- Advance state through a step function
- Reject transitions outside the graph
State Machine for an Agent
25 min · intermediate
Quick quiz
Stages should treat state as…
Schema versioning protects running sessions during deploys.