Skip to content

Courses / Agentic AI / Module 3

Module 3: LangGraph state machines: state, nodes, edges, checkpoints, interrupts

12 h · theory 4 · hands-on 5 · project 2 · revision 1

You will be able to

  • Model an agent as a graph with typed state
  • Add conditional edges and loops with limits
  • Persist checkpoints and resume runs
  • Pause for input with interrupts

Capstone increment: The assistant rebuilt as a LangGraph graph with Postgres checkpoints.

Job-description skills: Agent frameworks, LangGraph · Lab tools: langgraph, psycopg

1. Why model an agent as a graph

A hand-written loop hides its control flow in if statements. A graph makes it explicit: nodes do work, edges decide what runs next, and a typed state object carries everything between them. You can draw it, test each node alone, add a step without rewriting the loop, and pause or resume it at any node.

LangGraph is the most widely used library for this in Python and TypeScript. The ideas (state, reducers, conditional edges, checkpoints, interrupts) transfer to any framework.

STARTstate = {messages}agentcall the modelroutetool call? done?toolsrun, append resultapproveinterrupt()ENDfinal answerCheckpointerPostgres, per thread_idResumesame thread_idTime travelreplay from any stepNodes read and update one typed stateAfter every steploop (with a limit)save
The graph makes control flow explicit and testable; the checkpointer makes long runs survivable and pausable.

2. State, nodes and reducers

Define the state as a TypedDict or Pydantic model: messages, the incident, findings, a step counter. A node is a function that reads the state and returns a partial update. A reducer says how an update merges: messages are appended (add_messages), most other fields are replaced.

Keep state small and serialisable. Store big tool outputs elsewhere and keep a reference; everything in state is saved at every checkpoint.

Deep dive

Deep dive: reducers and super-steps

LangGraph runs a graph in super-steps, a model borrowed from Google’s Pregel. In each super-step, every node whose inputs are ready runs, in parallel if there are several; each returns a partial update (a dict of the keys it wants to change); then the updates are merged into the state and a checkpoint is saved. The next super-step starts from that saved state.

How updates merge is set per key by its reducer. A key without one is overwritten by the last write, and if two nodes write it in the same super-step LangGraph raises InvalidUpdateError because it has no rule to choose. Annotated[list, operator.add] appends; add_messages appends messages and replaces one that has the same ID, which is how tool results and edits land in the right place.

Worked example: the incident graph in the tool, with findings: Annotated[list[str], operator.add]

super-step 0  plan           → {}                                        findings = []
super-step 1  fetch_logs     → {"findings": ["logs: 502s from payments-api"]}
              fetch_metrics  → {"findings": ["metrics: p99 4.1 s"]}       merged: 2 items
super-step 2  summarize      reads both findings                         checkpoint 2 saved
with findings: list[str] (no reducer), super-step 1 raises InvalidUpdateError
State, reducers and super-stepsplan → fetch_logs and fetch_metrics → summarize. Both fetch nodes return an update to the same key, findings. Step through and read the state after each super-step.
findings is declared as
  1. Super-step 0: ran plan · plan decides to check logs and metrics
    checkpoint 0 saved · findings = []
Guided experiments
  1. No reducer, parallel. Step until it stops. Why does LangGraph refuse two values for one key in the same super-step instead of picking one?
  2. Untick parallel (the fetches run one after the other). It runs without an error, but read the final findings. Which bug is worse: the loud error or the silent overwrite?
  3. Switch to operator.add and run both ways. The state is the same either way. Where else do you need a reducer: messages (add_messages), counters, a set of visited URLs?
  4. Each step saves a checkpoint. If the process dies during summarize, which super-step does it resume from with the same thread_id, and which nodes run again?
Common misconception: Nodes don’t change the state they are given; they return an update. Code that appends to state["findings"] in place and returns nothing can pass a quick test and still lose data in parallel or resumed runs.

3. Conditional edges and loops with limits

A conditional edge is a function of the state that returns the next node’s name: “tools” if the model asked for a tool, “approve” if the action changes a system, END if it answered. Loops are just edges back to an earlier node.

Every loop needs an exit. LangGraph enforces a recursion limit per run and raises when it is hit; add your own step counter and budget in state so the graph can end gracefully with a partial answer instead of an exception.

Common misconception: “A graph makes the agent deterministic.” The edges are deterministic; the nodes that call models aren’t. The graph makes the non-determinism visible and contained.

4. Checkpoints, resume and time travel

Compile the graph with a checkpointer (in memory for tests, SQLite or Postgres for real use) and run it with a thread_id. After every step the state is saved. If the process dies, invoke the graph again with the same thread_id and it continues from the last checkpoint.

Because every step is saved, you can list the state history, inspect any past step, and re-run from it with a change, which is invaluable for debugging a bad run. This is what LangGraph calls time travel.

In production: Use the Postgres checkpointer in production and back it up like any other database. Checkpoints are the record of what your agent did.

5. Interrupts for human input

Inside a node, interrupt() pauses the graph and returns a payload to the caller, such as the change awaiting approval. The state is checkpointed, so the pause can last seconds or days. Resuming with the human’s answer (Command(resume=…)) continues from that exact point.

This is the building block for approvals in Module 9 and for asking the user a clarifying question mid-task.

Hands-on: coding window

The coding window and the full VS Code lab are available after you sign in.

Sign in to code

Labs

Lab 3.1: Rebuild the loop as a graph

Rebuild the Module 1 agent in LangGraph: agent node, tools node, a conditional edge, a step counter in state and a graceful end at the limit.

Expected: Same answers as the hand-written loop on the five baseline incidents, with a graph diagram exported to docs/.

Lab 3.2: Postgres checkpoints

Add the Postgres checkpointer, start a run, kill the process mid-run, and resume with the same thread_id. Then list the state history and re-run from step 2 with a changed input.

Expected: A short screen recording or log showing the resume and the replay.

Lab 3.3: Interrupt for approval (capstone increment)

Add an approve node that calls interrupt() with the proposed change, and FastAPI endpoints to fetch pending approvals and resume a thread with approve or reject.

Expected: A change waits for POST /approvals/{thread_id}; reject sends the reason back to the agent.

Go deeper

Videos

Further reading

  • Docs Graph API overview · LangGraph docs. State, reducers, nodes, edges and super-steps, from the source.
  • Docs Persistence · LangGraph docs. Checkpointers, threads, replay and updating state: everything behind resume and time travel.
  • Course Introduction to LangGraph · LangChain Academy. The free official course, with notebooks for each concept in this module.

GitHub repositories

Checkpoint quiz

1. What does a reducer decide?
2. A process dies mid-run. How do you continue?
3. What does interrupt() do?
4. Why keep state small?
5. Every loop in a graph needs…
6. Two parallel nodes both return an update to state key findings, declared as list[str] with no reducer. What happens?

Interview questions

  1. Why model an agent as a state graph instead of a while loop?
  2. Explain checkpoints and how you’d resume a run after a crash.
  3. How would you implement human approval in the middle of an agent run?
  4. What goes in agent state, and what shouldn’t?
  5. How do you debug a bad run using a graph’s state history?

Ask the professor

Sign in to ask questions about this module.

Discussion

Community discussion appears here once giscus is configured (see README).