Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 2 of 6 · Worked example · 20 min · revision 3

State, Nodes and Reducers

Design robust state schemas, implement pure and effectful node functions, and resolve concurrent state mutations using typed reducers.

Contentsand lesson path

What you will learn

  • Define a typed shared state and nodes that read and update it, with reducers for fields that several nodes write.

Prerequisites: Agent Loops & ReAct

01. The Challenge of Concurrent and Cyclic Updates

Once an agent loops to correct itself, or runs several tool calls in parallel, you must decide what happens when two steps write the same piece of state. Suppose two parallel nodes both write a list of findings in the same step: which value wins? Or a loop overwrites a result on its second pass that it should have kept. Either way the state no longer matches what the steps did.

Distributed systems handle the same problem with explicit merge rules for concurrent updates. Agent graphs borrow the idea: they separate the definition of the state, the nodes that compute updates, and the rules, called reducers, that decide how updates are combined.

02. Architecting State Schemas, Nodes, and Reducers

In graph orchestration frameworks such as LangGraph, state is not a loose collection of global variables. It has three parts:

1. The state schema and its channels. The state schema is a typed class or dictionary in which each key is a separate state channel. Each channel can be annotated with a reducer function, which defines what happens when a node returns a new value for that channel:

  • Overwrite (the default). With no reducer, a value a node returns for the key replaces the old value. This suits counters, status strings or the latest user query. Two nodes that write such a key in the same super-step cause an error, as the callout below explains.
  • Append (operator.add). When nodes return list items, such as messages, citations or retrieved documents, the reducer adds the new items to the end of the existing list instead of replacing it. Nodes in later turns or in parallel branches can then add their findings to the same list.
  • Custom reducer. Any function that takes the current value and the update and returns the new value. Use one to merge two dictionaries without dropping keys, to drop duplicates or to keep a running total. merge_metrics in the code below is one.

2. Nodes as transforms. A graph node is a Python or TypeScript function. It takes the current state as its first argument and returns a dictionary with only the keys it changes. (LangGraph can also pass a second argument, such as config or runtime, to a node that asks for one.) Nodes should not mutate the incoming state object directly.

By emitting delta dictionaries rather than full state copies, nodes remain modular, easily testable in isolation, and decoupled from channels they do not need to read or modify. When writing unit tests for a node, you only need to pass a mock state containing the subset of channels the node actually reads, asserting that the emitted dictionary contains only the expected delta keys.

Python · state_schema.py · a typed state with standard and custom reducers
from typing import TypedDict, Annotated, List, Dict, Any
import operator

def merge_metrics(current: Dict[str, Any], new: Dict[str, Any]) -> Dict[str, Any]:
    """Custom reducer that merges metric maps without dropping keys."""
    merged = dict(current)
    merged.update(new)
    return merged

class ResearchGraphState(TypedDict):
    session_id: str                          # Default overwrite
    step_number: int                         # Default overwrite
    chat_history: Annotated[List[dict], operator.add] # Append reducer
    discovered_facts: Annotated[Dict[str, Any], merge_metrics]

def retrieval_node(state: ResearchGraphState) -> dict:
    """Node emits partial updates; framework invokes reducers."""
    new_fact = {"q3_revenue": "$4.2M", "growth_rate": "18.4%"}
    new_message = {"role": "system", "content": "Retrieved financial facts."}
    return {
        "step_number": state["step_number"] + 1,
        "chat_history": [new_message],
        "discovered_facts": new_fact,
    }

3. Applying updates, and what persistence keeps. When the graph runtime invokes retrieval_node, it receives the emitted delta dictionary. For step_number, it replaces the integer. For chat_history, it passes the current list and the single new message to operator.add, producing a combined list. For discovered_facts, it passes the maps to merge_metrics.

Python · run_state.py · run the node once in a one-node graph
# pip install "langgraph==1.2.22"; keep state_schema.py in the same folder
from langgraph.graph import StateGraph, START, END
from state_schema import ResearchGraphState, retrieval_node

builder = StateGraph(ResearchGraphState)
builder.add_node("retrieve", retrieval_node)
builder.add_edge(START, "retrieve")
builder.add_edge("retrieve", END)
graph = builder.compile()

before = {
    "session_id": "s-1",
    "step_number": 0,
    "chat_history": [{"role": "user", "content": "Q3 numbers?"}],
    "discovered_facts": {"q2_revenue": "$3.6M"},
}
after = graph.invoke(before)
print("step_number:", after["step_number"])
print("chat_history:", [m["role"] for m in after["chat_history"]])
print("discovered_facts:", sorted(after["discovered_facts"]))
Expected output (python run_state.py)
step_number: 1
chat_history: ['user', 'system']
discovered_facts: ['growth_rate', 'q2_revenue', 'q3_revenue']

The output shows each rule at work. step_number was overwritten with 1. The user message is still in chat_history, because operator.add appended the node's system message. q2_revenue survived because merge_metrics merged the two maps; without that reducer, the node's two keys would have replaced the whole map.

This architecture also makes persistence straightforward. In LangGraph, each super-step (one tick in which all scheduled nodes run) is saved by default as a checkpoint containing the full channel values, not a log of deltas to replay. (LangGraph 1.2 adds an opt-in DeltaChannel, still in beta, that stores only the increments of one append-heavy channel.) If a node fails partway through a super-step, the writes from nodes that already succeeded in that step are kept as pending writes, so they are not re-run when the thread resumes. Restoring a thread loads its latest checkpoint. Replaying from an older checkpoint is different: it re-executes the nodes after that checkpoint, including model calls and tool side effects, so the results can differ. What reducers do guarantee is narrower: a pure reducer given the same current value and the same update returns the same result.

03. Verify Your Understanding

Practice check · 3 questions

State, Nodes, and Reducers Knowledge Check

Three questions on a failed super-step, what a checkpoint stores and how replay differs from restoring.

Q1. In one super-step, node A succeeds and node B fails. When the thread resumes, what happens to node A?
Q2. With the default channels, what does a LangGraph checkpoint store for a super-step?
Q3. What is the difference between restoring a thread and replaying from an older checkpoint?
Practice only: not graded, not saved, not evidence.

04. Apply it

In the skill's practice project you rebuild your framework-free agent as a graph with a router node, a tool node, a reflection node and a final-answer node. Write its state schema now, before the nodes:

  1. List every key the four nodes read or write, such as the messages, the latest tool result, a retry counter and the final answer.
  2. For each key, decide whether a new value replaces the old one or adds to it, and give every adding key a reducer such as operator.add.
  3. Write each node as a function that returns only the keys it changes. Test it by passing a plain dictionary and checking the keys it returns.

Before you move on, check that:

  • no node changes the incoming state in place;
  • every key that two parallel nodes may write has a reducer;
  • values that come from the model are validated, for example with a Pydantic model, before a node returns them, because a TypedDict is not checked at run time;
  • the message list is trimmed or summarised by a custom reducer or a separate step if it can grow long;
  • the state stays flat, with several top-level keys rather than one deeply nested object, so parallel branches merge cleanly;
  • reducers are pure and fast, with no network or database calls.

05. Review Prompt

Without looking back, explain:

  1. What a node returns, and what the runtime does with it for an overwrite channel, an operator.add channel and a custom reducer.
  2. Why returning only the changed keys is safer than changing the state in place.
  3. What happens when two parallel branches write the same channel, with a reducer and without one.
  4. Why a TypedDict schema alone does not stop a node from writing a value of the wrong type.
  5. What a checkpoint stores, and what happens to the nodes after it when you replay.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check