LangGraph: state, nodes, edges and control flow
- Advanced
- 40 min
- Lesson 3 of 7 in LangChain ecosystem
- Last verified
Select text in the lesson first to keep it with your note. With the keyboard, move focus here and press the button: the note goes with the section you are reading.
In this module
On this page
Before you start
- Completed:Agents, middleware and memory
You will be able to
- Model a workflow as shared state, nodes and edges, and say what compiling a graph does and what a node should return.
- Choose a reducer for a state key, and explain what happens by default, when parallel nodes write the same key, and how to clear an appended list.
- Explain super-step execution, why a recursion limit must be set on purpose, and why a node's side effects must be safe to run twice.
- Choose between a conditional edge, a Command and Send for a routing need, and state what happens when a static edge and a goto leave the same node.
- Decide between plain code, a pipe chain, create_agent and a LangGraph graph, and between the graph API and the functional API.
The team draws the workflow as a map: a box for every step, an arrow for every path between them. In the middle sits one shared notebook that every step can write to.
Two steps run at the same moment and both write the delivery status. One writes “shipped”. The other writes “held”.
Vihaan reads the notebook and says nothing is wrong with it. It only did what it was told. Whose line stays?
Concept
In the story the workflow map is LangGraph. The previous lesson built an agent from a ready-made loop. This lesson opens the loop. LangGraph describes a program as a graph over one shared piece of data: a state, a set of nodes that do the work, and edges that say what runs next. The docs call it a low-level orchestration framework: it does not hide your prompts or choose your architecture. What it adds is a runtime that can run steps in parallel, loop, pause and resume.
This lesson covers the building blocks and the rules that decide whether a graph is correct: how state merges, how execution proceeds in rounds, and how to route. Persistence and approvals come next, in lesson 4.
Why It Matters
A chain of function calls is easy to write and easy to lose. It forgets everything if the process dies, it cannot wait for a person, and a loop or a branch hides inside nested code. A graph turns that structure into something you can name, draw, test and resume. It also brings a new class of bugs that do not exist in straight-line code: two branches writing one field in the same round, a loop with no end, a step that runs twice. Most of this lesson is those bugs.
Mental Model
The map has three parts. The shared notebook is state: one record that every step can read, and each step writes only the fields it was given. The boxes are nodes: a step runs, does a job, and returns a note of what changed. The arrows are edges: they say what runs next, sometimes always the same step, sometimes depending on what the state now says.
Steps that run at the same time write at the same time. The shared notebook needs a rule for combining those notes. That rule is a reducer.
The three primitives
- State is the shared data. The docs list a typed dictionary as the main option, a dataclass for default values, and a Pydantic model for validation (slower; the higher-level
create_agentdoes not accept it). You can also set separate input and output schemas, and use private keys for nodes to talk to each other. - Nodes are functions, sync or async, that take the state (optionally also the run config and runtime) and return an update.
- Edges decide what runs next: a fixed edge, a conditional edge (a function returns the next node name or names), or a dynamic route from a node (below).
You build a graph with a state class, add nodes and edges from a start marker to an end marker, and compile it. Compiling runs structural checks and is where you attach runtime options such as a checkpointer. The graph must be compiled before use.
# Illustrative: after the graph-API page, read 2026-10-21.
from typing import Annotated
from typing_extensions import TypedDict
from langgraph.graph import StateGraph, START, END
from langgraph.graph.message import add_messages
class State(TypedDict):
messages: Annotated[list, add_messages] # reducer: append, or update by message id
attempts: int # no reducer: last write wins
def generate(state: State):
reply = model.invoke(state["messages"])
return {"messages": [reply], "attempts": state.get("attempts", 0) + 1}
def route(state: State):
done = looks_valid(state["messages"][-1]) or state["attempts"] >= 3
return END if done else "generate"
builder = StateGraph(State)
builder.add_node("generate", generate)
builder.add_edge(START, "generate")
builder.add_conditional_edges("generate", route)
graph = builder.compile()
graph.invoke({"messages": [("user", "Draft a refund policy")]})This is the “generate, check, retry at most three times” loop that a pipe chain cannot express. The counter lives in state. The routing function reads it and ends the loop.
Notice what the node returns: a partial update with only the keys it changed, not the whole state. Returning the whole state invites one node to overwrite another’s work.
Reducers: how updates merge
Each state key has a rule for merging a node’s update into the current value.
- Default: replace. The returned value overwrites the old one. Fine for a counter or a flag.
- An append reducer. Annotating a list with an add operation makes updates append.
- The message reducer.
add_messagesappends new messages and, if an incoming message has the id of an existing one, updates that message. That is how you edit or replace a message in history. - Your own function for a maximum, a set union or a dict merge.
Two parallel nodes write the same keys in one round. summaries has an append reducer and attempts has none:
| Key | Node A returns | Node B returns | Result |
|---|---|---|---|
summaries (append reducer) | ["a"] | ["b"] | ["a", "b"] |
attempts (no reducer) | 1 | 1 | Error: no rule to combine two writes |
messages (add_messages) | message id 7, edited | message id 8, new | Message 7 updated in place, message 8 appended |
Reducers matter most when nodes run at the same time. If two parallel nodes write the same key in the same round, the runtime needs a rule to combine them. With a reducer it has one. Without one, the update is invalid and you get an error, which is the better outcome than silently keeping one of the two.
(The story’s notebook had no rule for two writes, so it kept “whichever was written last”. Giving it one is the lesson.)
Two traps:
- An append reducer cannot be cleared by returning an empty list. The empty update is merged in, and nothing changes. The docs describe an
Overwritewrapper that bypasses the reducer for one key; only one node may use it on the same key in a round. - State is saved. With a checkpointer, state is written after steps. Keep it small and serialisable: ids and references, not whole documents. Raw tool output the model does not need to see does not belong in
messages. Old saved shapes persist, so changing a schema later needs thought.
Per-run values that should not be saved, such as the user id or a database handle, belong in runtime context, which lesson 2 introduced, not in state.
Super-steps: how execution proceeds
LangGraph runs in discrete rounds the docs call super-steps.
Consequences you can reason from:
- Siblings do not see each other’s work. Two nodes in one round read the same state; neither sees the other’s update until the round ends.
- Several outgoing edges from one node run their targets in parallel in the next round.
- Execution ends when no node is active and nothing is in transit, or when it hits the recursion limit, the maximum number of super-steps. Exceeding it raises an error. The docs give the default as 1000 from version 1.0.6, and it is set through the top-level
recursion_limitkey of the run config, not insideconfigurable. Do not rely on the default: set it for each graph to a number you chose, because an unbounded cycle is also an unbounded bill. A special remaining-steps field lets a node degrade gracefully before the limit. - Steps can run twice. With a checkpointer, state is saved at step boundaries, and a retry or a resume can re-run a node. So any side effect inside a node (send an email, charge a card) must be safe to repeat, usually through an idempotency key. Lesson 4 returns to this, with the power cut.
Control flow: edges, Command and Send
| Tool | What it does | Use it for |
|---|---|---|
| Fixed edge | Always go to the next node | Steps that never vary |
| Conditional edge | A function inspects state and returns the next node(s) | Routing, retry loops, “tools or finish” |
Command | A node returns a state update and the next node together | A node that decides and writes in one move; handoffs between agents |
Send | A routing function returns a list of Send(node, input) items, each with its own input | Fan-out where the number of items is known only at run time (map-reduce) |
defer=True on a node | The node waits until no pending work remains in the graph | A join after uneven parallel branches |
RetryPolicy on a node | Retry on chosen exceptions | Flaky external calls |
CachePolicy on a node | Cache results for a time-to-live; caching is switched on at compile time | Expensive, deterministic nodes |
A subgraph can send a Command to its parent graph. The docs say that when it updates a key shared with the parent, that parent key must have a reducer.
The goto trap. If a node returns a Command with a goto and also has a static edge, the static edge still runs. Both fire. If you meant “go here instead”, remove the static edge. The docs say to avoid mixing them.
# Illustrative: map-reduce with Send, after the graph-API page.
import operator
from langgraph.types import Send
class S(TypedDict):
docs: list[str]
summaries: Annotated[list[str], operator.add] # the reduce
def fan_out(state: S):
return [Send("summarize_doc", {"doc": d}) for d in state["docs"]] # the map
builder.add_conditional_edges("split", fan_out, ["summarize_doc"])Each Send starts a worker with its own input. Their results come back through the summaries reducer. The number of workers was decided when the graph ran, not when you wrote it. If something must happen after all of them, add a join (an edge from the worker to the next node, or defer).
Patterns worth naming
Interviewers like names. Each is a shape you can draw.
| Pattern | Shape | Note |
|---|---|---|
| Prompt chaining | A, then B, then C | Cheapest and most predictable |
| Routing | Classify, then one of N | Evaluate the classifier |
| Parallelisation | Fan out, then join | Mind rate limits |
| Orchestrator and workers | A planner emits tasks, workers run via Send, a synthesiser combines | Variable subtasks |
| Evaluator and optimiser | Generate, critique, loop | Needs a real signal and a cap |
| Agent loop | Model and tools in a cycle | Open-ended; budget it |
The principle behind the list, from the agentic patterns lesson, is to use the least autonomy that solves the task. A fixed workflow is cheaper, faster and easier to test than an agent.
Two ways to write it, and when to use none
LangGraph has a second style, the functional API, built from an entrypoint and tasks. You write ordinary Python control flow (if, loops, awaits) and still get persistence, streaming and approvals. The docs’ guidance:
- Graph API when you want the shape visible: debugging by diagram, explicit shared state, several decision points, parallel paths that merge, a workflow a team needs to see.
- Functional API when you are adding durability to existing procedural code, the flow is linear with simple branching, or state is local to functions.
Both give the same core capabilities and can be used in one application.
| Need | Choose |
|---|---|
| A linear pipeline, no loops, no state | Plain functions, or a pipe chain |
| Loops, branching on state, retries that remember | A LangGraph graph |
| Pause for approval, resume tomorrow, survive a restart | A graph with a checkpointer |
| A standard tool-using agent, fast | create_agent |
| Parallel fan-out with a fixed set of branches | A pipe chain with a dict, or a graph |
| Parallel fan-out with a count known at run time | A graph with Send |
| Strict SLAs and many non-model steps | Consider an existing workflow engine around the model calls |
Testing and debugging graphs
- Test nodes as plain functions: a state in, an update out.
- Test routing functions on a table of states: this one should loop, this one should end.
- Test the compiled graph with a stub model that returns scripted tool calls, so runs are deterministic.
- Draw the graph to check the shape you built is the shape you meant.
- Stream updates to see what each node changed, and trace runs (lesson 5).
- Evaluate the trajectory, which nodes and tools ran in what order, not just the final answer.
Real-World Application
A research assistant gets a question and an unknown number of sources. A planner node decides which sources to read. For each one a Send starts a summariser with its own input. The summaries come back through an append reducer under the summaries key. A synthesiser runs after all of them and writes an answer. An evaluator checks the answer; if it fails, a counter in state allows two more tries, then the run ends with a “could not verify” message. The recursion limit is set to a number you chose. Every node that calls an outside service is written to be safe to run twice.
Nothing in that design needs a model to decide the shape. The model does the reading and the writing. The graph is the fixed part, which is what makes it testable.
Interview Perspective
Expect: “What does a reducer do?”, “Two parallel branches both append to messages. Results duplicate or race. Diagnose.”, “Implement generate, validate, retry at most three times.”, “Summarise an unknown number of pages in parallel, then synthesise.”, “When do you not use LangGraph?”
For the first, say that a reducer is the merge rule for a state key, that the default is replace, and that parallel writes to a key without a rule are an error. For the third, put the counter in state and bound the loop with a routing function. For the fourth, name Send, the append reducer and the join. For the last, name a case: a linear pipeline, or a single call.
Common mistakes: no reducer on a key that parallel nodes write; large documents in state; side effects that are not safe to repeat; unbounded cycles with an unknown recursion limit; mixing goto with static edges; treating state as a database for memory across conversations (that is the store); returning the whole state from a node.
Provenance: Common industry pattern. These are the questions this topic tends to draw for agent roles; none is verified for a named company.
Practice Questions
- Basic: What does a reducer do, and what happens without one when two nodes write the same key?
- Intermediate: Implement generate, validate, retry at most three times with conditional edges. Where does the counter live?
- Advanced: Summarise an unknown number of web pages in parallel, then synthesise. Give the state, the
Send, the reducer and the join. - Product-Company: Two parallel branches both append to
messages, and the output duplicates or races. Diagnose and fix.
Activity
Draw the graph for a workflow you know: classify a request, branch to one of two handlers, then check the result and retry at most twice. Mark each state key and its reducer. Mark which node could run twice and what makes it safe if it does.
Homework
Write a one-page design for the research assistant in the section above. Include the state with each key’s reducer, each node’s returned update, the routing logic, the recursion limit you would set and why, and a test for the routing function expressed as a table of states and expected next nodes.
Quick Revision
- A graph is state, nodes and edges; compile it before use.
- A node returns a partial update.
- Default merge is replace. Parallel writes to one key need a reducer. An append reducer is cleared with an overwrite, not an empty list.
- Execution runs in super-steps: parallel nodes, merge at the boundary, repeat.
- Set the recursion limit yourself. Make side effects safe to repeat.
- Conditional edge routes.
Commandupdates and routes.Sendfans out with a runtime count. - A static edge still runs alongside a
goto. - Plain code or a pipe for linear flows; a graph for loops, state and pauses.
Check yourself
- Walk-through: Explain super-steps and why reducers exist, then design a map-reduce summariser.
- Variation: Add a person’s approval before the reduce step. What else has to change?
- Common misconception: “LangGraph replaces LangChain.” It is a separate runtime; LangChain agents are built on it, and it works without LangChain.
Related
Resources & Further Reading
Checked sources to go deeper. The essential ones come first in each group.
Official documentation
Persistence (LangGraph documentation) (opens in a new tab)Essential
The next lesson's subject: how checkpoints are saved after each step, which is why nodes can run twice.
Further reading
Idempotent requests (opens in a new tab)
A concrete model for the idempotency keys that make a node safe to run twice.
Timeouts, retries, and backoff with jitter (opens in a new tab)
Explains why retries need backoff and caps, relevant to RetryPolicy on flaky nodes.
Hands-on
langchain-ai/langgraph (GitHub repository) (opens in a new tab)
The repository with source and issues; reading the reducer and recursion-limit code settles questions the pages leave open, such as the default limit.
More for this module: LangChain ecosystem resources
Practice
Test what you just read. Quizzes and cards are grouped by module: LangChain ecosystem.
Check yourself15 questions on what this lesson set out to teach
Checking answers needs JavaScript. You can still read every question and option below.
Keyboard: arrow keys move between options. Space or Enter selects the focused option.