All articles
11 min read
#LangGraph#LLM#Multi-Agent#Orchestration

State as the API: Three LangGraph Designs

I compare three LangGraph state designs: flat fields, nested models, and explicit reducers, with routing and replay constraints.

On this page

Why this matters

The state schema is the contract between nodes: every shared field declares how writes combine. It is the first thing I check when I review a system for state, recovery, eval, and cost.

I compare three illustrative state designs: flat fields, nested models, and channels with explicit reducers. The examples focus on merge rules, routing signals, and replay boundaries. They are not a reconstruction of a client system or evidence of production performance.

The snippets are partial design sketches, not a complete runnable application. For framework semantics, I refer to the official Graph API, checkpointer, and interrupt documentation. No version-specific execution result is claimed here.

What breaks in production

  • Concurrent same-step writes to a field with no reducer are rejected. LangGraph raises INVALID_CONCURRENT_GRAPH_UPDATE instead of guessing an order.
  • Sequential flags are overwritten when a later node writes the same field and that field uses the default last-write-wins reducer.
  • Side effects replay from a checkpoint. A configured checkpointer persists graph state at super-step boundaries according to its durability and storage configuration. When you resume or replay from a checkpoint, the nodes after it run again, external calls included, so that work has to be idempotent.
  • Checkpoint contents can hold sensitive data. The snapshot is the state: messages, drafts, whatever the nodes wrote. I treat it like a production datastore. mklang ADR 0032, from a different open-source project of mine, describes the same problem: a checkpoint there stores the full working state as plain-text JSON.

1. Flat fields and implicit update rules

I start with a plain TypedDict. Each node reads the fields it needs and returns updates. The schema alone does not declare how concurrent writes should combine.

class AgentState(TypedDict):
    messages: list[str]
    research_results: list[dict]
    draft: str
    critique: str
    iteration_count: int
    should_continue: bool

The conflict to test: suppose two nodes write to messages in the same parallel step, one adding tool results and one adding user messages. Without a reducer, LangGraph rejects concurrent writes to the same key instead of guessing an order. A separate case is sequential updates: if a planner writes should_continue=True and a critic writes False one step later, the later update replaces the earlier value under the default rule.

The issue is the implicit write model. A flat dict makes every shared field a possible race unless its merge behavior is explicit.

Adding a last_writer field or node-level locks would not define the merge rule for a shared field. I prefer field-level merge semantics instead of overwrite-by-default.

2. Nested Pydantic models and update boundaries

The second sketch groups related values into Pydantic models. Validation and update semantics remain separate responsibilities.

class ResearchState(BaseModel):
    query: str
    sources: list[Source]
    confidence: float

class DraftState(BaseModel):
    content: str
    word_count: int
    critique_history: list[Critique]

class AgentState(TypedDict):
    research: ResearchState | None
    draft: DraftState | None
    final_output: str | None

Assigning each node a separate section can avoid overlapping writes; Pydantic validation itself does not define how concurrent updates merge. LangGraph accepts a Pydantic model as graph state. The risk is coupling routing to nested data: an edge might inspect values such as research is not None and draft is not None and draft.critique_history[-1].approved. Those predicates can become business logic hard to test in isolation.

The other problem: None is an ambiguous sentinel. Does research: None mean "not started", "failed", or "intentionally skipped"? I would define an explicit status instead of overloading missing data.

If a node must replace part of the research result while preserving sources, I need an explicit update contract. Adding research_override: ResearchState | None can postpone that decision while expanding the schema.

Nested Pydantic is a good fit for tool I/O contracts. For evolving graph state, I evaluate nested models together with their merge rules rather than treating validation as a merge strategy.

3. Channels with explicit reducers

The third sketch uses documented Annotated fields with reducer functions.

import operator
from typing import Annotated
from langgraph.graph import StateGraph

class AgentState(TypedDict):
    messages: Annotated[list[str], operator.add]      # append-only
    tool_calls: Annotated[list[ToolCall], operator.add]  # append-only
    current_draft: str                                 # last-write-wins (intentional)
    iteration: Annotated[int, lambda a, b: b]          # always take latest
    max_iterations: int                                # configured iteration limit
    approved: bool | None                              # routing signal; writer ownership must be enforced by graph design

The explicit rule: I give messages and tool_calls an explicit reducer with operator.add, so node outputs append to the existing list instead of replacing it. If two nodes add a message in the same step, LangGraph combines both updates according to the reducer. I do not assume a graph-traversal order for those parallel updates.

current_draft is still last-write-wins because only the writer node touches it, and I want the latest value. The point is not to ban overwrites. The point is to make each field's write behavior intentional.

I treat each field as a channel with an explicit update contract. Annotated[list, operator.add] declares concatenation; it does not deduplicate repeated messages or make an external operation idempotent. I still need to test ordering assumptions and replay behavior.

The review question is concrete: does this reducer preserve the required invariants for every permitted writer?

4. Conditional edges are not routing logic

Once update rules are explicit, I keep business decisions separate from routing functions.

A conditional edge in LangGraph takes state and returns the name of the next node. I keep that responsibility narrow: given this state snapshot, which node runs next?

# Wrong: business logic inside the router
def should_continue(state: AgentState) -> str:
    if state["iteration"] > 5:
        return "end"
    last_message = state["messages"][-1] if state["messages"] else ""
    if "approved" in last_message.lower() or "looks good" in last_message.lower():
        return "end"
    return "generate"

# Right: routing reads an explicit signal written by a node
def should_continue(state: AgentState) -> str:
    if state.get("approved") or state["iteration"] >= state["max_iterations"]:
        return "end"
    return "generate"

The failure mode: edge functions that parse strings, look up a database, or contain multi-step logic are hard to test and hard to replay if the decision never landed in state.

The rule I follow: if a routing condition needs more than reading a field and comparing a value, I put that condition in a node. The node writes an explicit routing signal, and the edge reads it. State is the source of truth, not the edge function. I route on a field written after a node interprets a message, not on the message text itself.

5. Interrupts and the dual-write problem

Human-in-the-loop workflows need an explicit boundary between intent, approval, execution, and checkpoints.

The unsafe pattern is performing an external side effect before a resumable checkpoint, or in a node that may be replayed. This is separate from interrupt_before: an interrupt_before on send_draft_node pauses before that node runs, so it does not itself send the email. For human-in-the-loop, current LangGraph docs recommend interrupt() inside a node; on resume the node restarts from the beginning, so any code before interrupt() runs again.

The dual-write problem: send an email, resume from a checkpoint that precedes the send node, retry — the email may go out twice unless the operation is idempotent.

# Unsafe: this node performs a side effect and may be replayed
# from a checkpoint that precedes send_draft_node.
def send_draft_node(state: AgentState) -> dict:
    email_client.send(state["draft"], to=state["recipient"])
    return {"email_status": "sent"}

# Safer: separate intent from execution.
def prepare_send_node(state: AgentState) -> dict:
    # send_request_id is supplied at ingress and saved in graph state.
    # Reuse it on retries; create a new ID only for a new intended send.
    return {"pending_action": {
        "type": "email", "to": state["recipient"], "body": state["draft"],
        "idempotency_key": state["send_request_id"], "status": "pending",
    }}

def execute_send_node(state: AgentState) -> dict:
    action = state.get("pending_action")
    if not action or not state.get("human_approved"):
        return {}

    try:
        # The external boundary requires an idempotency key or a reconciliation mechanism.
        receipt = email_client.send(
            action["body"],
            to=action["to"],
            idempotency_key=action["idempotency_key"],
        )
    except Exception as exc:
        # Retain the intent with a retryable status until an outcome is recorded.
        return {
            "pending_action": {**action, "status": "retryable", "last_error": str(exc)},
            "human_approved": None,
        }

    # Return the confirmed outcome and cleared intent together for the next checkpoint.
    return {
        "pending_action": None,
        "human_approved": None,
        "email_outcome": {"status": "sent", "receipt": receipt},
    }

# Configure the graph to interrupt before execute_send_node.
# The graph pauses after prepare_send_node has written pending_action
# and before the executor performs the external call.

The pattern I use is: write the intent to state, interrupt before the executor, let a human approve the intent, then execute. I assign a request ID at ingress and persist it in state, reusing it across retries and replay. Changing the recipient or body creates a new intent with a new ID and requires approval again. On failure, I retain the intent for retry; on confirmed success, I return the outcome and cleared intent together for the next checkpoint. The external service must enforce the idempotency key or provide a reconciliation mechanism.

Checkpoints capture state, not external side effects. Approval controls whether an action is allowed; it does not prevent a retry from duplicating an approved action. I require idempotency or reconciliation at the external boundary.

6. What I checkpoint and what I don't

With a configured LangGraph checkpointer and the default durability mode, state is persisted at super-step boundaries: a snapshot after each tick of the graph. I treat that as the safe starting point. The exact storage backend and retention policy still depend on the persistence configuration, so I verify them for the version I support.

In a graph that calls an LLM at every node, that means a durable write at each configured boundary. I would measure checkpoint latency and storage writes under the intended workload before changing persistence settings. I distinguish persisted intent and results from cheap transformations that can be recomputed; no overhead measurement is reported here.

A configured checkpointer persists the graph state at super-step boundaries according to its durability and storage configuration. I do not claim I can turn checkpointing off per node. I classify nodes so I know which replays are expensive or unsafe:

  • Side effect (API call, database write, email): Persist durable intent before the call and record the outcome after. If I cannot pin the checkpoint boundary, I make the operation idempotent and put an approval gate before the first execution.
  • LLM call: Keep the inputs available before the call when the persistence model allows it. The call is expensive and non-deterministic; on failure I want the same inputs, not a re-derived prompt.
  • Pure transform (parse, format, filter): I do not add extra persistence for this work. I usually recompute cheap deterministic transforms, provided they have no external side effects and their inputs are persisted.
  • Routing: I do not add extra persistence for the routing decision. It should be reproducible from state that is already persisted.

When I audit a LangGraph system, I list all nodes and classify each one against that table. If I cannot classify a node, I fix that first.

The contract I would review

I start with explicit writers and merge rules. LangGraph provides primitives for durable state and replay. I now design state as channels with explicit merge semantics. Edges, interrupts, and checkpoint coverage then follow from that contract and stay simple.

If you are building or auditing a LangGraph system and encounter these issues, see how I work.

FAQ

How should I model shared LangGraph state between agents?

I model shared state as channels with explicit merge semantics. I use reducers where fields must combine writes, and I keep overwrite only where a specific writer owns the field.

Why can a flat TypedDict state fail under parallel node execution?

A flat dict does not define how shared fields merge. If two nodes write the same key in the same step and that key has no reducer, LangGraph rejects the update. Across sequential steps, a later overwrite still wins if that field uses the default reducer.

When are nested Pydantic models too rigid for LangGraph state?

I use them for tool I/O, not as the main shape of evolving graph state. Conditional edges start inspecting nested data, None becomes an ambiguous sentinel, and partial overrides grow extra fields.

What belongs in a LangGraph conditional edge function?

Given this state snapshot, which node runs next? If the condition needs parsing, lookups, or multi-step logic, I put that logic in a node and let the edge read the signal it writes.

How do I avoid duplicate side effects with LangGraph interrupts?

I separate intent from execution, interrupt before the executor, and make the external operation idempotent or record its outcome. Checkpoints capture state, not side effects.

Share this article

Related articles

  • How I Evaluate CrewAI and LangGraph for Recovery

    I compare roles, routing, structured state, memory, and recovery through explicit design criteria and official documentation.

    Jan 15, 20255 min read
    #CrewAI#Multi-Agent#LangGraph#Production
  • Around Three Agents, I Start Considering Message-Passing

    I compare shared fields and append-only messages, with explicit ownership, inbox tracking and supervisor routing.

    Dec 10, 202414 min read
    #LangChain#Agents#Multi-Agent#Architecture
  • How I Diagnose RAG Retrieval: Chunking, Ranking, and Embeddings

    I diagnose RAG retrieval with a fixed query set, inspect document boundaries, and test ranking and embedding changes against quality, latency, and cost.

    Dec 20, 202412 min read
    #RAG#Retrieval#LLM#Production