LangGraph: state, nodes, edges and control flow

  • Advanced
  • 40 min
  • Lesson 3 of 7 in LangChain ecosystem
  • Last verified

Open slides(30 slides)

Before you start

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_agent does 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).
Diagram: State is the shared data.

partial update

reads state

partial update

State
messages, attempts

Node: classify

Node: generate

Edge: conditional
reads state, picks next node

Diagram summary: State is the shared data. Nodes read it and return only the keys they changed, and edges read it to decide which node runs next. Nothing passes between nodes except through state.

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.

Python

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

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.

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_messages appends 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:

KeyNode A returnsNode B returnsResult
summaries (append reducer)["a"]["b"]["a", "b"]
attempts (no reducer)11Error: no rule to combine two writes
messages (add_messages)message id 7, editedmessage id 8, newMessage 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 Overwrite wrapper 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.

Diagram: In each super-step every active node runs on the same input state, their updates are merged together at the boundary through the reducers,...

Super-step 1: nodes A and B run in parallel on the same state

Updates merged through reducers

Super-step 2: next active nodes run

Merge, then repeat until no node is active

Diagram summary: In each super-step every active node runs on the same input state, their updates are merged together at the boundary through the reducers, and the nodes they activate form the next super-step.
Diagram: A concrete graph with a parallel middle.

START

split

worker A

worker B

join

END

Diagram summary: A concrete graph with a parallel middle. After split, workers A and B run in the same super-step on the same state, so neither sees the other’s update. Their updates merge through the reducers, and join runs in the next super-step. The rounds are: split, then A with B, then join.

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_limit key of the run config, not inside configurable. 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

ToolWhat it doesUse it for
Fixed edgeAlways go to the next nodeSteps that never vary
Conditional edgeA function inspects state and returns the next node(s)Routing, retry loops, “tools or finish”
CommandA node returns a state update and the next node togetherA node that decides and writes in one move; handoffs between agents
SendA routing function returns a list of Send(node, input) items, each with its own inputFan-out where the number of items is known only at run time (map-reduce)
defer=True on a nodeThe node waits until no pending work remains in the graphA join after uneven parallel branches
RetryPolicy on a nodeRetry on chosen exceptionsFlaky external calls
CachePolicy on a nodeCache results for a time-to-live; caching is switched on at compile timeExpensive, 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.

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

Node returns Command(goto='review')
and also has a static edge to 'publish'

review runs

publish ALSO runs

Fix: if you meant 'go here instead',
remove the static edge

Diagram summary: A node that returns a Command with goto and also has a static edge triggers both targets. If you meant “go to review instead of publish”, remove the static edge, since the docs advise against mixing the two.

Python

# 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).

Diagram: A routing function returns one Send per item, so the number of workers is decided when the graph runs, not when you wrote it.

split: 3 documents at run time

fan_out returns 3 Send items

summarize_doc (doc 1)

summarize_doc (doc 2)

summarize_doc (doc 3)

summaries reducer appends all three

Join: next node runs after all workers

Diagram summary: A routing function returns one Send per item, so the number of workers is decided when the graph runs, not when you wrote it. Each worker has its own input, and their results are combined through the append reducer before the next node runs.

Patterns worth naming

Interviewers like names. Each is a shape you can draw.

PatternShapeNote
Prompt chainingA, then B, then CCheapest and most predictable
RoutingClassify, then one of NEvaluate the classifier
ParallelisationFan out, then joinMind rate limits
Orchestrator and workersA planner emits tasks, workers run via Send, a synthesiser combinesVariable subtasks
Evaluator and optimiserGenerate, critique, loopNeeds a real signal and a cap
Agent loopModel and tools in a cycleOpen-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.

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, resume tomorrow, survive a restartA graph with a checkpointer
A standard tool-using agent, fastcreate_agent
Parallel fan-out with a fixed set of branchesA pipe chain with a dict, or a graph
Parallel 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

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. Command updates and routes. Send fans 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.

Resources & Further Reading

Checked sources to go deeper. The essential ones come first in each group.

Official documentation

Further reading

Hands-on

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.

0 of 15 answered

Keyboard: arrow keys move between options. Space or Enter selects the focused option.

ObjectiveModel a workflow as shared state, nodes and edges, and say what compiling a graph does and what a node should return.

  1. Question 1 of 15A node in a graph has finished its work. What should it return?

    Choose one answer.

  2. Question 2 of 15What does compiling a graph do?

    Choose one answer.

  3. Question 3 of 15A retry loop keeps an "attempts" counter in state and a routing function ends the run when it reaches three. Where is the loop's bound enforced?

    Choose one answer.

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

  1. Question 4 of 15A state key is declared without a reducer, and a node returns {"status": "done"}. What happens to the old value?

    Choose one answer.

  2. Question 5 of 15Two branches run in the same round and both append a summary to a "summaries" list. Only one summary survives in the output. What is the most likely cause?

    Choose one answer.

  3. Question 6 of 15A message list uses the add-messages reducer. A node returns a message with the same id as one already in the list. What happens?

    Choose one answer.

  4. Question 7 of 15A node returns {"items": []} for a key with an append reducer, hoping to empty the list. What is the result?

    Choose one answer.

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

  1. Question 8 of 15Nodes A and B are both active in one super-step. A writes "x" and B reads "x" in the same round. What does B see?

    Choose one answer.

  2. Question 9 of 15A graph has a cycle and you did not set a recursion limit. Why is relying on the default a poor choice?

    Choose one answer.

  3. Question 10 of 15A node sends a confirmation email and then fails later in the same step. The graph retries the step. What is the risk, and the usual fix?

    Choose one answer.

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

  1. Question 11 of 15A support triage node should classify a ticket, record the category in state and send the flow to the right handler. Which tool fits best?

    Choose one answer.

  2. Question 12 of 15A node returns Command(goto="refund") and the graph also has a static edge from that node to "audit". Which nodes run next?

    Choose one answer.

  3. Question 13 of 15A research step must summarise a list of pages whose count is only known at run time, then combine the summaries. Which design fits?

    Choose one answer.

ObjectiveDecide between plain code, a pipe chain, create_agent and a LangGraph graph, and between the graph API and the functional API.

  1. Question 14 of 15A team has a linear three-step flow with no loops, no saved state and no approvals. What is the most defensible implementation?

    Choose one answer.

  2. Question 15 of 15A team already has long procedural Python and wants checkpointing and human approval added with minimal rewriting. Which API fits best?

    Choose one answer.