graph = StateGraph(AgentState)
Building Real-World Agentic AI Systems with LangGraph
Designing, building, evaluating, and shipping stateful, durable, multi-agent systems on LangGraph 1.x.
It turns unreliable LLM calls into dependable software. The right amount of structure is a dial to tune deliberately — not maxed out in either direction — and LangGraph's stateful, durable runtime is how you tune it for production: durability, explicit state, controlled flow, and human oversight.
All the code is open: the companion repository on GitHub, one tag per chapter.
The problem
The demo was never the hard part.
A support-agent demo works beautifully in the room. It answers three questions, calls a tool, sounds confident. Two weeks later it is in front of real customers, and the incidents start: it loses the thread of a conversation after a restart, retries a refund it already issued, and when an operator asks what happened, there is no trace to read.
This book is about the part that is hard: turning unreliable LLM calls into dependable software. It is about orchestration — the layer that gives an agent durable state, controlled flow, the ability to pause for a human, recover from a crash, and tell you what it did.
What it is not
Not a prompt-engineering book, not an LLM-internals book, and not a RAG book.
The running project
You build one system across the whole book. Atlas starts as a customer-support assistant, then grows two extensions that justify a multi-agent boundary: an internal-data agent and a research agent. Every backend — knowledge base, ticket API, research corpus — ships as a seeded, mockable service in the companion repo.
The spine of the book
Twenty-seven chapters. Twenty-seven things that break.
Every chapter starts from a concrete failure and ends with the mechanism that removes it, plus the term the book uses for that mechanism from then on. Open a chapter to see all three.
Ch 1 The Agent Reliability Problem the break · the mechanism · the term
What breaks without it
Your agent refunds twice. No prompt fixes that.
The mechanism
The control/autonomy dial sizes structure to the cost of being wrong.
Core concept it names
control/autonomy dial — Degree to which a system imposes explicit structure (state machines, fixed routing, gates, validation) vs delegates decisions to the model. Tune to the task's cost of being wrong; do not max either end.
Ch 2 The LangGraph Ecosystem in 2026 the break · the mechanism · the term
What breaks without it
You hand-roll a StateGraph first. It reimplements create_agent, worse.
The mechanism
The abstraction ladder starts at create_agent, and you earn every drop below it.
Term it names
abstraction ladder — Start at the highest abstraction that is still correct (create_agent) and descend to raw StateGraph only when a concrete requirement forces it. “You earn the drop, you do not start at the bottom.”
Ch 3 Thinking in Graphs the break · the mechanism · the term
What breaks without it
You bolt resumability on later. The shape refuses it.
The mechanism
State-transition discipline: a node reads state, returns a delta, routes, and does nothing else.
Term it names
state-transition discipline — Every node reads the shared state, returns a state delta, and routes — and does nothing that isn't one of those three. The working rule that keeps the graph from lying about its own control flow.
Ch 4 StateGraph, Nodes, and Edges the break · the mechanism · the term
What breaks without it
Dev is fast. Production p99 is eleven seconds.
The mechanism
Give the runtime plain def nodes and its superstep loop does the offloading.
Term it names
No new core concept. This chapter reinforces the state-transition discipline and the abstraction ladder rather than naming a term of its own.
Ch 5 State Design and Reducers the break · the mechanism · the term
What breaks without it
Two parallel branches write one channel. Production throws.
The mechanism
A state contract declares who writes each channel and how concurrent writes merge.
Core concept it names
state contract — The explicit agreement, encoded in the state schema, of who writes each channel and how concurrent writes merge. Every channel has a contract whether you author one or not: no reducer = LastValue = “one writer per superstep, enforced by an error”.
Ch 6 Conditional Edges and Dynamic Control Flow the break · the mechanism · the term
What breaks without it
The model invents a node name. Your graph routes to it.
The mechanism
The routing boundary keeps control flow on edges, where the model proposes and the graph disposes.
Core concept it names
routing boundary — Control flow lives on edges, never buried in node side effects: a node writes state, a separate routing function (on the edge) reads state to choose the next node. The model's output is a validated, bounded input to routing, never the next-node name itself. The model proposes; the graph disposes.
Ch 7 Tools, Models, MCP, and create_agent the break · the mechanism · the term
What breaks without it
A ticket status of "clozed". Your API accepts it.
The mechanism
Sizing the authority surface makes the wrong write unrepresentable instead of merely discouraged.
Term it names
authority surface — The set of real-world actions your tool list grants the model. Every tool widens it; a loose arg schema widens it invisibly. Sizing it (narrowest tools that do the job) is the control/autonomy dial made concrete when the model can act.
Ch 8 The Middleware System the break · the mechanism · the term
What breaks without it
PII redaction lives in every tool. The next one leaks.
The mechanism
The agent-loop seam gives every cross-cutting concern one ordered place to live.
Term it names
agent-loop seam — The set of defined hook points around the create_agent loop — before/after_agent, before/after_model, wrap_model_call, wrap_tool_call — where cross-cutting logic attaches without being tangled into node or tool bodies. A concern touching every turn lives on the seam; a concern specific to one action lives in that action.
Ch 9 Persistence and Checkpointing the break · the mechanism · the term
What breaks without it
The process restarts. Every open conversation is gone.
The mechanism
A checkpointer turns the restart into a resume.
Term it names
resumption boundary — The point a durable run continues from after a crash, deploy, or human pause: the last completed superstep's checkpoint, not the start. Because the checkpoint is between supersteps, where state is consistent, resume is exact, not approximate. Makes “resume after failure” and “resume after approval” the same operation.
Ch 10 Durable Execution, Long-Running Workflows, and State Migration the break · the mechanism · the term
What breaks without it
The crash lands after the charge. Charged twice.
The mechanism
The checkpoint membrane marks where retries stop being free and idempotency starts.
Core concept it names
checkpoint membrane — The boundary in the graph where irreversible side effects begin. Before it (triage, retrieve, answer, pure compute) retries and resumes are free. After it (charge a card, send email, file a ticket) every retry or resume needs idempotency, an outbox record, or compensation — because the work touched the world. Drawing it is the core reliability decision.
Ch 11 Human-in-the-Loop the break · the mechanism · the term
What breaks without it
Approval takes seven hours. The deploy kills the worker.
The mechanism
An approval gate suspends the run into the checkpointer, not into a blocked thread.
Term it names
approval gate — A deliberate suspension placed just before a membrane crossing: the run interrupts, surfaces the proposed action to a human, and resumes only on an explicit, recorded decision (approve/edit/reject). A pause chosen on purpose, not a failure path; durable — the suspended run lives in the checkpointer, not a blocked thread.
Ch 12 Context Engineering the break · the mechanism · the term
What breaks without it
By turn forty, worse answers and a bigger bill.
The mechanism
A context budget allocates the window per turn and enforces it on the hot path.
Core concept it names
context budget — An explicit per-turn allocation of the context window across system, history, retrieved, and scratch — enforced on the hot path, not hoped for. Each section gets a token slice; the four operations (write/select/compress/isolate) keep a turn within it.
Ch 13 Short-Term vs Long-Term Memory the break · the mechanism · the term
What breaks without it
The customer explains their setup again. Third ticket.
The mechanism
The memory horizon decides, fact by fact, what has to outlive the thread.
Core concept it names
memory horizon — The deliberate, per-fact decision of how long information must outlive the thread that produced it: this turn only (transient state, discard), this conversation (the checkpointer, thread_id-scoped), or across all of a customer's conversations (the store, namespace-scoped). Choosing the horizon is choosing the mechanism.
Ch 14 Advanced Memory: Extraction, Compaction, and LangMem the break · the mechanism · the term
What breaks without it
Prefers email, prefers phone. The model picks one.
The mechanism
Extraction and compaction run as background reflection, so remembering never adds latency to answering.
Term it names
background reflection — Forming and consolidating long-term memory off the response path — after the turn, deferred or scheduled — so remembering never adds latency to answering. Extraction and compaction are reflection, not response. If the agent decides what to remember before it replies, reflection is on the hot path and every user pays for it.
Ch 15 When and Why to Go Multi-Agent the break · the mechanism · the term
What breaks without it
You split one agent into three. Slower, no smarter.
The mechanism
The coordination tax is what a split costs before it pays anything back.
Term it names
coordination tax — The cost a multi-agent system pays regardless of whether the split helps: multiplied token spend (each agent re-establishes context; handoffs duplicate it), added latency per hop, a debugging surface that fans across agents and coordinator, and context lost at every handoff. Paid up front and unconditionally; parallelism and isolation is what you might buy back.
Ch 16 The Supervisor Pattern (and Swarm as Contrast) the break · the mechanism · the term
What breaks without it
One handoff forwards the whole transcript. Bill triples.
The mechanism
Owning the handoff payload sends the sub-task, not the transcript.
Term it names
handoff payload — The context a handoff deliberately carries from one agent to the next: the sub-task plus only the state the receiver needs, not the entire conversation. Scoping it is where multi-agent correctness and cost are both decided. A handoff that forwards everything is not “safe” — it is unbudgeted.
Ch 17 Subgraphs, Parallelism, and Map-Reduce the break · the mechanism · the term
What breaks without it
You fan out inside a node. The runtime sees one step.
The mechanism
Send declares the fan-out and a reducer merges the fan-in, both in the runtime's view.
Term it names
the superstep barrier — Every node fanned out in a superstep must complete before the graph advances. Makes fan-in deterministic and checkpointable — and is why one slow branch delays the whole batch and one failing branch endangers it, so per-worker timeouts and in-worker error capture are mandatory at scale.
Ch 18 Deep Agents: The Production Harness the break · the mechanism · the term
What breaks without it
Three sprints hand-wiring a planner. The plan changed.
The mechanism
The planning loop belongs to the harness, so the abstraction ladder decides whether you adopt it.
Term it names
planning loop — The agent-maintained todo list (write_todos) that drives the agent's own sub-task sequencing — work the agent decides, as opposed to the supervisor's externally-fixed routing graph or the map-reduce's externally-fixed source list. Makes the shape of the work emergent instead of declared.
Ch 19 Streaming the break · the mechanism · the term
What breaks without it
The client disconnects. Your run dies mid-refund.
The mechanism
The live channel is a tap on the run, never the run itself.
Term it names
the live channel — The disconnectable, transport-level tap a client uses to watch a run — not the run itself. The run is the checkpointer-backed execution, durable regardless of who is watching; the live channel is best-effort and can drop at any time with no authority over whether the run continues. Naming the distinction is what stops “client disconnected” from being treated as “cancel the run”.
Ch 20 Observability and Debugging with LangSmith the break · the mechanism · the term
What breaks without it
Tracing is on. Nobody can say which agent answered.
The mechanism
Trace fidelity is engineered at instrumentation time, one name and one tag at a time.
Term it names
trace fidelity — The degree to which a trace alone — without rerunning code — reconstructs exactly what happened in a run: which node or agent ran, in what order, with what inputs and outputs, at what cost and latency. Tracing can be fully “on” with near-zero trace fidelity if nothing is named or tagged; fidelity is designed in at instrumentation time, not a byproduct of enabling tracing.
Ch 21 Evaluation and Testing the break · the mechanism · the term
What breaks without it
Every eval passes. Cost is up forty percent.
The mechanism
Path coverage exercises the routes through the graph, not just the wording of answers.
Term it names
path coverage — A dataset's job to exercise the distinct routes through Atlas's topology — branches, handoffs, approve/reject/edit outcomes — not just distinct input questions that happen to land on the same route. A dataset with excellent question variety and poor path coverage gives high confidence in one route and none in the rest.
Ch 22 Deployment and Scaling the break · the mechanism · the term
What breaks without it
Two code versions, one checkpoint store. Refunds vanish.
The mechanism
Naming the schema straddle turns a deploy into drain, migrate, replace, one replica at a time.
Term it names
schema straddle — The window during a rolling deploy when old and new code versions run concurrently against the same shared checkpoint store. A state-schema change is fleet-safe only if it can be read and written by both versions for the full length of that window — the additive-field rule, now a hard fleet requirement instead of a single-process good habit.
Ch 23 Security, Privacy, Cost, and Governance the break · the mechanism · the term
What breaks without it
A forwarded email hides instructions. Narrow tools obey.
The mechanism
Injection surface multiplies authority surface, so shrinking one term changes nothing.
Term it names
injection surface — The set of untrusted content sources (retrieved documents, MCP tool results, third-party API responses) that can reach the model as if they were instructions rather than data. Multiplies with the authority surface to define an agent's real vulnerability — hardening only one factor leaves the product unchanged.
Ch 24 Patterns from Production the break · the mechanism · the term
What breaks without it
Every run is correct. Every run redoes work it already did.
The mechanism
The six-concept catalog says where a pattern belongs, and where it turns into pattern soup.
Term it names
No new term. This chapter catalogs the six core concepts and the sixteen supporting terms already established, by design.
Ch 25 Choosing Your Stack (and When Not to Use LangGraph) the break · the mechanism · the term
What breaks without it
A stateless FAQ bot. And a Postgres bill.
The mechanism
The durability tax is worth paying only when a real checkpoint membrane exists.
Term it names
the durability tax — The fixed operational cost every LangGraph project pays regardless of whether its own reliability requirements need it — a checkpointer and its backing database, reducer discipline on every state channel, the deploy-time machinery that protects a schema straddle. Worth paying when a real checkpoint membrane exists; pure cost on a project with nothing to persist and nothing to resume.
Ch 26 The Frontier and Future-Proofing the break · the mechanism · the term
What breaks without it
The model improved, so someone removed the approval gate.
The mechanism
The judgment/execution split loosens scaffolding for judgment and never for execution guarantees.
Term it names
the judgment/execution split — The resolution of the control/autonomy dial: model capability improvements shift the optimal scaffolding for judgment (what to decide, which route, how to phrase a plan) but leave execution guarantees (durability, idempotency, approval gates on irreversible actions) unchanged, because those guarantees compensate for the world — crashes, unsendable refunds — not for model weakness. The dial was always two axes; only one moves with the model.
Ch 27 Capstone the break · the mechanism · the term
What breaks without it
You know the patterns. The next vertical starts over.
The mechanism
A new vertical gets built from patterns already in hand, including the one that did not fit.
Term it names
No new term. The capstone builds a second vertical from patterns already in hand, including the one that did not fit.
Named-concept discipline
Six ideas carry the whole book.
Six concepts get a full treatment and recur by name across all 27 chapters. Sixteen further supporting terms stay local to the chapter that needs them. Chapter 24 catalogs both, and Appendix D is the glossary.
Ch 1 → resolved Ch 26
control/autonomy dial
How much structure you impose vs how much you delegate to the model — tune deliberately, do not max out either end.
Ch 5
state contract
The explicit agreement about who writes which state channel and how conflicts merge.
Ch 6
routing boundary
Control flow lives on edges, never buried in node side effects.
Ch 10
checkpoint membrane
The boundary where irreversible side effects begin; before it retries are cheap, after it every retry needs idempotency, an outbox record, or compensation.
Ch 12
context budget
An explicit per-turn allocation of the context window across system, history, retrieved, and scratch — enforced, not hoped for.
Ch 13
memory horizon
The explicit decision of how long each piece of information must outlive the current thread.
How the code is kept honest
Pinned, not “latest”.
LangGraph and LangChain reached 1.0 together in October 2025 and are still moving fast. This book does not promise “the latest”; it pins a tested-version matrix, with beta surfaces isolated, labeled, and paired with stable fallbacks. Where a claim depends on a version, the version is stated.
The goal is not to make you fluent in an API surface that will change. It is to give you the judgment to ship agents that survive contact with production — and to keep that judgment when the framework underneath it shifts.
| Component | Version |
|---|---|
| Python | 3.12 (3.11+ supported) |
| LangGraph | 1.2.6 |
| LangChain | 1.3.0 |
| LangSmith | current at time of writing |
deepagents | 0.6.x (beta — isolated, paired with a stable fallback) |
Who this book is for
You have shipped Python. You have not yet shipped an agent you would trust on call at 2am.
You write production Python. You are comfortable with typing, async/await,
and decorators. You have called an LLM API and built something that demos well.
If that is you, this book is for you.
It also serves two secondary readers: architects evaluating whether to bet on LangGraph at all (Chapter 25 is an honest treatment of when not to), and engineers migrating from LangGraph or LangChain 0.x to the 1.x line (Appendix B is your map). You do not need prior LangChain or LangGraph experience.
| Path | Reader | Chapters | Outcome |
|---|---|---|---|
| Atlas fast path | Engineer shipping a first reliable agent | 1–13, 19–23, 27 | Durable support assistant with tools, persistence, HITL, context control, observability, evals, deployment, and security. |
| Architecture path | Tech lead choosing a stack | 1–3, 15–18, 21–26 | Decision record for when LangGraph, a harness, or a simpler workflow is the right fit. |
| Multi-agent path | Practitioner with a single-agent baseline | 5, 12, 15–18, 21, 23 | Justified multi-agent boundary, supervisor/subgraph comparison, and measured cost/latency tradeoff. |
| Migration path | LangGraph/LangChain 0.x user | 2, App. B, App. C, then 4–11 | Clean 1.x mental model, API migration map, and durable-state upgrade strategy. |
A path is a route, not a self-contained subset. Chapters name the code they build on, so a path occasionally sends you back one chapter for a module it assumes.
Contents
Seven parts, twenty-seven chapters, seven appendices.
Part I
Foundations: Why Agents Need a Runtime
- 1 The Agent Reliability Problem
- 2 The LangGraph Ecosystem in 2026
- 3 Thinking in Graphs
Part II
Core LangGraph
- 4 StateGraph, Nodes, and Edges
- 5 State Design and Reducers
- 6 Conditional Edges and Dynamic Control Flow
- 7 Tools, Models, MCP, and create_agent
- 8 The Middleware System
Part III
State, Persistence, and Durability
- 9 Persistence and Checkpointing
- 10 Durable Execution, Long-Running Workflows, and State Migration
- 11 Human-in-the-Loop
Part IV
Context and Memory
- 12 Context Engineering
- 13 Short-Term vs Long-Term Memory
- 14 Advanced Memory: Extraction, Compaction, and LangMem
Part V
Multi-Agent Systems
- 15 When and Why to Go Multi-Agent
- 16 The Supervisor Pattern (and Swarm as Contrast)
- 17 Subgraphs, Parallelism, and Map-Reduce
- 18 Deep Agents: The Production Harness
Part VI
Production Engineering
- 19 Streaming
- 20 Observability and Debugging with LangSmith
- 21 Evaluation and Testing
- 22 Deployment and Scaling
- 23 Security, Privacy, Cost, and Governance
Part VII
Case Studies and the Frontier
- 24 Patterns from Production
- 25 Choosing Your Stack (and When Not to Use LangGraph)
- 26 The Frontier and Future-Proofing
- 27 Capstone
The companion repository
One tag per chapter. Check out any increment and run it.
All code in the book lives in one repository, organized as one tag per chapter increment, so you can check out the exact state of Atlas at the end of any chapter and run it. Each increment ships with its tests. The suite stands at 379 passing tests.
# Reproduce the environment exactly uv sync # or: pip install -r requirements.txt # Check out a specific chapter's end state git checkout ch09-persistence-checkpointing # Run that increment's tests uv run pytest
Every backend Atlas talks to — the knowledge base, the ticket API, the research corpus — ships as a seeded, mockable service in the repo: no vendor account stands behind any of them, and the test suite runs entirely offline.
Everything else — the graph, the reducers, the retry and escalation paths, persistence, human-in-the-loop, and the whole test suite — runs with no account at all.
| What | From | Why |
|---|---|---|
| A model provider key | Ch 2+ | Atlas's triage step is a real model call, so any run of the graph needs one. |
| An embeddings provider | Ch 13, App. G | Semantic recall over the long-term store. The in-memory dev path needs no key. |
| A LangSmith account | Ch 20–22 | Tracing, datasets, and the online evaluators. The free tier is enough. |
The author
Ranjan Kumar
An engineer who builds production AI systems and writes about the parts that the demos leave out. He works on agentic systems, LLM orchestration, and the infrastructure that makes them dependable.
Errata and feedback
This book bets on a fast-moving stack, and parts of it will drift. The living errata
page — ERRATA.md at the root of the companion repository —
tracks confirmed corrections and post-publication changes in the libraries the book
depends on. Check it before assuming a discrepancy is your bug rather than expected
drift.
Found an error? Open an issue or pull request on the companion repository.