Slides · LangChain ecosystem
LangGraph: state, nodes, edges and control flow
1 / 30
LangGraph: state, nodes, edges and control flow
Open the agent loop: describe a program as shared state, steps and arrows, and learn the rules that decide whether such a graph is correct.
By the end you can model a workflow as a graph, pick reducers, reason about super-steps and the recursion limit, route with edges, Command and Send, and decide when a graph is the wrong tool.
Concept
Two steps, one notebook
- The team draws a workflow as boxes and arrows, with one shared notebook in the middle that every step can write to.
- Two steps run at the same moment and both write the delivery status: one writes “shipped”, the other “held”.
- The notebook did nothing wrong. It only did what it was told, and nobody told it how to combine two notes.
- Straight-line code never has this bug. Graphs bring a new class of bugs: two writers in one round, a loop with no end, a step that runs twice.
Concept
Mental model: notebook, boxes, arrows
- State is the shared notebook: one record every step can read. Each step writes only the fields it changed.
- Nodes are the boxes: a step does a job and returns a note of what changed.
- Edges are the arrows: sometimes always the same next step, sometimes depending on what the notebook now says.
- Steps that run at the same time write at the same time, so the notebook needs a rule for combining notes. That rule is a reducer.
Concept
The three primitives
- The graph-API page defines state as the shared snapshot of the application, whose schema plus reducers define how updates apply. The schema can be a
TypedDict, a dataclass or a Pydantic model. - Nodes are functions that receive the state, do work and return an update.
- Edges decide which node runs next from the current state, and can be fixed or conditional.
- You build the graph, then compile it. The page says compiling performs basic structural checks and is where checkpointers and breakpoints are specified, and that you must compile before use.
- The overview calls LangGraph a low-level orchestration framework: it does not choose your prompts or architecture.
Sources[1] Graph API overview (LangGraph documentation)[2] LangGraph overview (LangGraph documentation)
Code
Generate, check, retry at most three times
Excerpt; the tested file adds imports and a scripted model.
Python
class State(TypedDict):
draft: str
attempts: int # no reducer: last write wins
def generate(state):
n = state.get("attempts", 0) + 1
return {"draft": call_model(), "attempts": n} # partial update
def route(state):
return END if is_valid(state["draft"]) or state["attempts"] >= 3 else "generate"
builder = StateGraph(State)
builder.add_node("generate", generate)
builder.add_edge(START, "generate")
builder.add_conditional_edges("generate", route)
graph = builder.compile()Test (scripted generate, langgraph 1.2.17, 2026-10-24) | Result |
|---|---|
| valid on attempt 3 | stops with attempts 3 after 3 calls |
| never valid | stops with attempts 3 after 3 calls |
The counter lives in state; the routing function reads it and ends the loop. A pipe chain cannot express this as a cycle in the chain.
Diagram
The same graph, drawn
Concept
Return only what changed
- Each node hands back a partial update: only the keys it changed, never a copy of the whole state.
- Returning the whole state invites one node to overwrite another’s work, especially when nodes run in parallel.
- Nodes should also be small enough to test as plain functions: a state in, an update out.
- Nothing passes between nodes except through state, so anything one step needs from another must be a state key.
Check yourself
Check: trace the loop
Same graph, but the routing function ends when the draft is valid or attempts reaches 4, and the model produces a valid draft on its second try. Starting from attempts 0, how many times does generate run, and what is the final attempts? Where would the loop stop if no draft were ever valid?
Answer
generate runs twice and the final attempts is 2 (run and checked). If no draft were ever valid it would stop after 4 runs with attempts 4, because the routing function reads the counter from state.
Concept
Reducers: how updates merge
- Each state key has a merge rule. The default reducer, per the graph-API page, replaces the old value with the new one.
- An append reducer (for example
operator.addon a list) combines updates instead of replacing them. add_messagesappends new messages and updates an existing message that has the same id.- A custom function can implement a maximum, a set union or a dict merge.
Overwritebypasses a reducer for one key. The page says merging reducers do not clear a field when given an empty value, and shows wrapping the empty value inOverwriteto clear it.
Sources[1] Graph API overview (LangGraph documentation)[3] Use the graph API (LangGraph documentation)
Worked example
Worked example: two parallel nodes, three keys
Nodes A and B run in the same round. Tested on langgraph 1.2.17.
| Key | A returns | B returns | Result |
|---|---|---|---|
summaries (append reducer) | ["a"] | ["b"] | ["a", "b"] |
attempts (no reducer) | 1 | 1 | InvalidUpdateError: “Can receive only one value per step” |
messages (add_messages) | edit of id m1 | new id m2 | m1 replaced in place, m2 appended |
- The error page for this case says to define the key with a reducer so the graph knows how to combine parallel values.
- The error is the better outcome. Silently keeping one of two writes would lose data without a sign.
Sources[4] INVALID_CONCURRENT_GRAPH_UPDATE (LangGraph troubleshooting)[3] Use the graph API (LangGraph documentation)
Worked example
Worked example: clearing an appended list
Key items has an append reducer and starts as ["x", "y"].
| Node returns | Resulting items |
|---|---|
{"items": []} | ["x", "y"] (nothing appended, nothing removed) |
{"items": Overwrite([])} | [] |
- Tested on langgraph 1.2.17. The empty list is a valid update; it just adds nothing.
- Use
Overwritewhen a node must reset a field. The use-graph-api page says that if several parallel nodes overwrite the same key in one super-step, anInvalidUpdateErroris raised.
Check yourself
Check: write a reducer
Three parallel workers each return a score for the key best (0.4, 0.9 and 0.6). You want the graph to keep the highest. Which reducer do you declare, what is the final value, and why does the default fail?
Answer
Declare a function such as def keep_max(a, b): return max(a, b) and annotate the key with it. The final value is 0.9 (run and checked). With the default replace rule three writes in one round have no combine rule and raise an error. One practical detail from the test: the built-in max has no inspectable signature, so the framework rejected Annotated[float, max]; a named function worked.
Concept
State is saved, so keep it small
- With a checkpointer, state is written as the run proceeds, so it should be small and serialisable: ids and references, not whole documents.
- Raw tool output that the model does not need to read does not belong in
messages. - Old saved shapes persist, so changing the 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 the previous lesson introduced.
Diagram
Execution runs in super-steps
Sources[1] Graph API overview (LangGraph documentation)[3] Use the graph API (LangGraph documentation)
Worked example
Worked example: what siblings can see
A writes x = "new". B, in the same round, records the x it reads. join runs after both.
| Node | What it saw or wrote |
|---|---|
| Initial state | x = "old" |
B (same round as A) | read x = "old" |
join (next round) | read x = "new" |
- Tested on langgraph 1.2.17. Siblings read the same input; updates merge at the boundary.
- The use-graph-api page adds that the order of updates from parallel nodes is not guaranteed, so use a separate field with an ordering value if order matters.
Worked example
The recursion limit, measured
The page says that from version 1.0.6 the default is 1000 steps, that the limit is set through a standalone recursion_limit config key and not inside configurable, and that exceeding it raises GraphRecursionError.
| Test on langgraph 1.2.17 (2026-10-24) | Result |
|---|---|
Loop that never ends, config={"recursion_limit": 5} | GraphRecursionError after 5 node runs |
| Same loop, no limit set | GraphRecursionError mentioning a limit of 10007, not 1000 |
recursion_limit placed inside configurable | ignored; the error quoted the default again |
- The default differs between the docs page and the installed version, and the installed code reads an environment variable for it. So set the limit yourself, for each graph, to a number you chose.
- An unbounded cycle is an unbounded bill. A
RemainingStepsfield lets a node end gracefully before the limit.
Sources[1] Graph API overview (LangGraph documentation)[3] Use the graph API (LangGraph documentation)
Check yourself
Check: is a limit of 3 enough?
The diamond graph (split, then A and B together, then join) does work in 3 super-steps. Will recursion_limit=3 let it finish?
Answer
Not in the version tested. With limits 1, 2 and 3 the run raised GraphRecursionError; with 4 and 5 it completed with the log split, A, B, join (langgraph 1.2.17). With limit 3 all four nodes had already run before the error, so side effects happened and only the result was lost. The exact step accounting is an implementation detail, so choose limits with generous margin above your longest legitimate path, not at the count you computed by hand.
Worked example
A step can run twice
A node sends an email, then fails. The node has RetryPolicy for ConnectionError, so it runs again.
| Setup | Emails sent | Result |
|---|---|---|
| Send, then fail once, then succeed | 2 | duplicate |
Send guarded by a key such as run1-send, same failure | 1 | the repeat is ignored |
- Tested with a stand-in send function on langgraph 1.2.17. The runtime saves state, not your outside effects, so it cannot know the email left.
- The use-graph-api page says retries re-run only the failing branch, not the whole graph.
- With a checkpointer, a resume can also re-run a node. Make every side effect safe to repeat, usually with an idempotency key, as in the harness module.
Compare
Routing tools
| Tool | What it does | Use it for |
|---|---|---|
| Fixed edge | always go to the next node | steps that never vary |
| Conditional edge | a function reads state and returns the next node(s) | routing, retry loops |
Command | a node returns an update and the next node together | decide and write in one move; handoffs |
Send | a routing function returns Send(node, input) items | fan-out with a count known at run time |
defer=True | the node waits until no work is pending | a join after uneven branches |
RetryPolicy | retry on chosen exceptions | flaky external calls |
- The page says
Commandonly adds dynamic edges, and that static edges still execute.
Sources[1] Graph API overview (LangGraph documentation)[3] Use the graph API (LangGraph documentation)
Diagram
The goto trap
Code
Map-reduce with Send
Excerpt; the tested file adds imports and a scripted model.
Python
class S(TypedDict):
docs: list[str]
summaries: Annotated[list[str], operator.add] # the reduce
def fan_out(state):
return [Send("summarize_doc", {"doc": d}) for d in state["docs"]] # the map
builder.add_conditional_edges("split", fan_out, ["summarize_doc"])
builder.add_edge("summarize_doc", "combine")Test (worker upper-cases a doc, combine appends a count) | summaries |
|---|---|
docs ["a", "b", "c"] | ["A", "B", "C", "COUNT=3"] |
docs ["x"] | ["X", "COUNT=1"] |
docs [] | [] (combine never ran) |
- The worker count was decided when the graph ran. Each worker has its own input and results gather through the reducer.
Check yourself
Check: what breaks with zero items?
In the map-reduce graph above, a user submits no documents. What does the run return, and what do you add so the caller does not receive a silent empty result?
Answer
The run returns the initial summaries unchanged (an empty list). No Send item was produced, so no worker started and the downstream combine node never ran (tested). Add an explicit branch before the fan-out: if docs is empty, route to a node that writes a clear message or ends with an error, instead of relying on the join to run.
Compare
Patterns worth naming
The LangGraph workflows page lists six patterns. Each is a shape you can draw.
| Pattern | Shape | Note |
|---|---|---|
| Prompt chaining | A, then B, then C | cheapest and most predictable |
| Parallelisation | fan out, then join | mind rate limits |
| Routing | classify, then one of N | evaluate the classifier |
| Orchestrator-worker | a planner emits tasks, workers run via Send | variable subtasks |
| Evaluator-optimiser | generate, critique, loop | needs a real signal and a cap |
| Agent | model and tools in a cycle | open-ended; budget it |
- The page says workflows have predetermined code paths while agents define their own process and tool use, with more autonomy. Course advice, echoing Anthropic’s guidance of finding the simplest solution possible and only increasing complexity when needed: use the least autonomy that solves the task.
Sources[5] Workflows and agents (LangGraph documentation)[6] Building effective agents
Compare
Graph API or functional API
The choosing-APIs page describes two styles over one runtime, which can be used together in one application.
| Choose | When |
|---|---|
| Graph API | you want to visualise a complex workflow, explicit shared state, several conditional branches, parallel paths that merge, or a team that benefits from a visual model |
| Functional API | you are adding LangGraph to existing procedural code with minimal changes, standard if and loop control flow, a quick prototype, a linear workflow or state local to functions |
- The page says to move to the graph API when a workflow becomes complex, and back when a graph is more structure than a simple linear process needs.
Source[7] Choosing between Graph and Functional APIs (LangGraph documentation)
Compare
When a graph is not the answer
| 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 and resume tomorrow | a graph with a checkpointer |
| A standard tool-using agent, fast | create_agent |
| Fan-out with a fixed set of branches | a pipe chain with a dict, or a graph |
| 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 |
- These rows are judgment about trade-offs, not statements by the framework’s authors.
Check yourself
Check: choose the style
A new feature has five steps, three decision points, two parallel review branches that must merge, and a team that wants to review the flow on a whiteboard before building. Which style and why? What would change your answer?
Answer
The graph API: the choosing-APIs page lists a visual model, explicit shared state, several conditional branches and parallel paths that merge as reasons. It would change if the flow turned out linear with simple branching and state local to functions, or if the goal were only a quick prototype, where the functional API needs less setup.
Process
Test and debug a graph
- Test nodes as plain functions: a state in, an update out.
- Test routing functions on a table of states: this one loops, this one ends.
- Run the compiled graph with a scripted stand-in model, so every run is deterministic.
- Draw the graph and check the shape you built is the shape you meant.
- Stream updates to see what each node changed, and trace runs.
- Evaluate the trajectory (which nodes ran, in what order), not just the final answer.
Summary
Recap
- A graph is state, nodes and edges; compile before use; each node hands back only the keys it changed.
- Default merge replaces. Parallel writes to one key need a reducer, or the run raises an error. Clear an appended list with
Overwrite. - Execution runs in super-steps; siblings do not see each other’s updates; set the recursion limit yourself and leave margin; make side effects safe to run twice.
- A conditional edge routes,
Commandupdates and routes,Sendfans out with a runtime count, and a static edge still runs beside agoto. - Handle the empty fan-out explicitly.
- Plain code or a pipe for linear flows; a graph for loops, state and pauses.
References
References & Sources (1 of 2)
Graph API overview (LangGraph documentation) (opens in a new tab)
LangChain2026Documentation
https://docs.langchain.com/oss/python/langgraph/graph-api
Used for State, nodes and edges, compile, default replace reducer, add_messages, Overwrite, super-steps, the recursion limit, and that Command leaves static edges running.
LangGraph overview (LangGraph documentation) (opens in a new tab)
LangChain2026Documentation
https://docs.langchain.com/oss/python/langgraph/overview
Used for LangGraph as a low-level orchestration framework that does not prescribe prompts or architecture.
Use the graph API (LangGraph documentation) (opens in a new tab)
LangChain2026Documentation
https://docs.langchain.com/oss/python/langgraph/use-graph-api
Used for Reducer definitions, parallel branches and update order, Send map-reduce, Command, remaining steps, retry policy and defer.
INVALID_CONCURRENT_GRAPH_UPDATE (LangGraph troubleshooting) (opens in a new tab)
LangChain2026Documentation
https://docs.langchain.com/oss/python/langgraph/errors/INVALID_CONCURRENT_GRAPH_UPDATE
Used for The error raised when several nodes write one key in a step and the fix of adding a reducer.
Workflows and agents (LangGraph documentation) (opens in a new tab)
LangChain2026Documentation
https://docs.langchain.com/oss/python/langgraph/workflows-agents
Used for The six workflow and agent patterns and the difference between predetermined workflows and agents.
References
References & Sources (2 of 2)
Building effective agents (opens in a new tab)
Erik S., Barry Zhang2024Article
https://www.anthropic.com/engineering/building-effective-agents
Used for The principle of using the least autonomy that solves the task.
Choosing between Graph and Functional APIs (LangGraph documentation) (opens in a new tab)
LangChain2026Documentation
https://docs.langchain.com/oss/python/langgraph/choosing-apis
Used for When to choose the graph API or the functional API, and that both can be used together.
Keys: ← → move, Home End first and last, F full screen.