Slides · LangChain ecosystem

LangGraph: state, nodes, edges and control flow

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.

Sources1 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 3stops with attempts 3 after 3 calls
never validstops 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.

Source1 Graph API overview (LangGraph documentation)

Diagram

The same graph, drawn

Diagram: A graph with one working node.

no

yes

START

generate

Valid, or 3 attempts?

END

Diagram summary: A graph with one working node. After each pass a routing function checks the result and the attempt count, and either loops back to generate or ends.

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.add on a list) combines updates instead of replacing them.
  • add_messages appends 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.
  • Overwrite bypasses 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 in Overwrite to clear it.

Sources1 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.

KeyA returnsB returnsResult
summaries (append reducer)["a"]["b"]["a", "b"]
attempts (no reducer)11InvalidUpdateError: “Can receive only one value per step”
messages (add_messages)edit of id m1new id m2m1 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.

Sources4 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 returnsResulting 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 Overwrite when 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, an InvalidUpdateError is raised.

Source1 Graph API overview (LangGraph documentation)

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

Diagram: The graph-API page describes a super-step as one iteration over the graph’s nodes, with parallel nodes sharing a step.

START

split

worker A

worker B

join

END

Diagram summary: The graph-API page describes a super-step as one iteration over the graph’s nodes, with parallel nodes sharing a step. Here split runs first, workers A and B run in the same super-step on the same input state, their updates merge through the reducers, and join runs in the next super-step.

Sources1 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.

NodeWhat it saw or wrote
Initial statex = "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.

Source3 Use the graph API (LangGraph documentation)

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 setGraphRecursionError mentioning a limit of 10007, not 1000
recursion_limit placed inside configurableignored; 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 RemainingSteps field lets a node end gracefully before the limit.

Sources1 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.

SetupEmails sentResult
Send, then fail once, then succeed2duplicate
Send guarded by a key such as run1-send, same failure1the 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.

Source3 Use the graph API (LangGraph documentation)

Compare

Routing tools

ToolWhat it doesUse it for
Fixed edgealways go to the next nodesteps that never vary
Conditional edgea function reads state and returns the next node(s)routing, retry loops
Commanda node returns an update and the next node togetherdecide and write in one move; handoffs
Senda routing function returns Send(node, input) itemsfan-out with a count known at run time
defer=Truethe node waits until no work is pendinga join after uneven branches
RetryPolicyretry on chosen exceptionsflaky external calls
  • The page says Command only adds dynamic edges, and that static edges still execute.

Sources1 Graph API overview (LangGraph documentation)3 Use the graph API (LangGraph documentation)

Diagram

The goto trap

Diagram: A node that returns a Command with goto and also has a static edge triggers both targets.

Node returns Command
goto review

review runs

publish also runs
via static edge

Fix: remove the
static edge

Diagram summary: A node that returns a Command with goto and also has a static edge triggers both targets. In the test the log held start, publish and review (in that observed order, which the docs do not promise) with the static edge, and start, review without it.

Source1 Graph API overview (LangGraph documentation)

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.

Source3 Use the graph API (LangGraph documentation)

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.

PatternShapeNote
Prompt chainingA, then B, then Ccheapest and most predictable
Parallelisationfan out, then joinmind rate limits
Routingclassify, then one of Nevaluate the classifier
Orchestrator-workera planner emits tasks, workers run via Sendvariable subtasks
Evaluator-optimisergenerate, critique, loopneeds a real signal and a cap
Agentmodel and tools in a cycleopen-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.

Sources5 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.

ChooseWhen
Graph APIyou 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 APIyou 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.

Source7 Choosing between Graph and Functional APIs (LangGraph documentation)

Compare

When a graph is not the answer

NeedChoose
A linear pipeline, no loops, no stateplain functions or a pipe chain
Loops, branching on state, retries that remembera LangGraph graph
Pause for approval and resume tomorrowa graph with a checkpointer
A standard tool-using agent, fastcreate_agent
Fan-out with a fixed set of branchesa pipe chain with a dict, or a graph
Fan-out with a count known at run timea graph with Send
Strict SLAs and many non-model stepsconsider 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

  1. Test nodes as plain functions: a state in, an update out.
  2. Test routing functions on a table of states: this one loops, this one ends.
  3. Run the compiled graph with a scripted stand-in model, so every run is deterministic.
  4. Draw the graph and check the shape you built is the shape you meant.
  5. Stream updates to see what each node changed, and trace runs.
  6. 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, Command updates and routes, Send fans out with a runtime count, and a static edge still runs beside a goto.
  • 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)

  1. Graph API overview (LangGraph documentation) (opens in a new tab)

    LangChain2026Documentation

    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.

  2. LangGraph overview (LangGraph documentation) (opens in a new tab)

    LangChain2026Documentation

    Used for LangGraph as a low-level orchestration framework that does not prescribe prompts or architecture.

  3. Use the graph API (LangGraph documentation) (opens in a new tab)

    LangChain2026Documentation

    Used for Reducer definitions, parallel branches and update order, Send map-reduce, Command, remaining steps, retry policy and defer.

  4. INVALID_CONCURRENT_GRAPH_UPDATE (LangGraph troubleshooting) (opens in a new tab)

    LangChain2026Documentation

    Used for The error raised when several nodes write one key in a step and the fix of adding a reducer.

  5. Workflows and agents (LangGraph documentation) (opens in a new tab)

    LangChain2026Documentation

    Used for The six workflow and agent patterns and the difference between predetermined workflows and agents.

References

References & Sources (2 of 2)

  1. Building effective agents (opens in a new tab)

    Erik S., Barry Zhang2024Article

    Used for The principle of using the least autonomy that solves the task.

  2. Choosing between Graph and Functional APIs (LangGraph documentation) (opens in a new tab)

    LangChain2026Documentation

    Used for When to choose the graph API or the functional API, and that both can be used together.