Understanding graph state

Topic 1 of 4 in State management27 min readBeginnerFree course

Overview

In the previous lesson, Visualizing graphs with Mermaid, you learned how to represent nodes, edges, branches, and execution paths visually. A graph diagram tells you where execution goes, but it does not necessarily explain what information travels through the workflow.

That information is managed through graph state.

Imagine building an AI-powered customer support assistant that performs the following operations:

  1. Receives a customer question.
  2. Determines the category of the question.
  3. Retrieves relevant information from a knowledge base.
  4. Generates a response using a language model.
  5. Determines whether human assistance is required.

Each operation needs information produced by earlier operations. The response generator needs the original question and retrieved documents. The escalation decision may depend on the question category and the generated response.

Without a shared mechanism for managing this information, you would need to manually pass arguments between functions, maintain intermediate variables, and coordinate execution yourself.

LangGraph solves this problem through a structured state management system.

Graph state is the current collection of application data available to a graph during its execution.

You can think of it as a working document maintained by the LangGraph runtime. Nodes read relevant information, perform their operations, and submit updates. LangGraph incorporates those updates and makes the resulting state available to subsequent operations.

The following diagram illustrates a support workflow in which information accumulates across several nodes.

Overview diagram: START to Classify Request; Classify Request to Retrieve Documents; Retrieve Documents to Generate Response; Generate Response to END; Classify Request to Shared State; Retrieve Documents to Shared State; Generate Response to Shared State; Shared State to Retrieve Documents; Shared State to Generate Response.

The solid arrows represent execution flow. The dotted arrows illustrate state access and updates rather than executable graph edges.

State management is fundamental to conversational agents, retrieval-augmented generation, multi-agent systems, human approval workflows, and durable applications.

An important distinction is that state is not limited to conversation history. It can contain numbers, strings, documents, classifications, tool results, decisions, counters, and other structured information.

A LangGraph application has three fundamental components:

Component Responsibility Example
State Represents application data Customer question and category
Node Performs an operation Classifies the question
Edge Determines execution flow Moves execution to document retrieval

A graph combines these components into a coordinated workflow.

Setting up the environment

Use Python 3.11 or later and install a current LangGraph 1.x release. The examples use LangGraph 1.1 or later for the version 2 streaming interface.

Terminal
python -m pip install -U "langgraph>=1.1,<2" typing-extensions

All examples deliberately use deterministic Python functions rather than external language models. This allows you to study state behavior without API credentials, network requests, model costs, or unpredictable model responses.

The APIs follow the current LangGraph Graph API documentation. Outputs are expected results based on the documented execution behavior; the examples have not been executed in the lesson-authoring environment.

The state schema

Before creating a graph, you must determine what information the application needs to maintain.

A state schema describes the structure of that information. It establishes the fields available to the graph and their expected types. It can also define how updates to individual fields are combined.

LangGraph supports several Python approaches to defining state:

  • TypedDict
  • Pydantic models
  • Dataclasses

For this lesson, we will primarily use TypedDict because it is straightforward and closely resembles the Python dictionaries and JSON objects you already know.

Defining state using TypedDict

A TypedDict describes the expected structure of a dictionary using Python type annotations.

For example, a customer support workflow might need the following fields:

Field Type Purpose
question str Original customer question
category str Classification result
priority str Request urgency
response str Generated answer

The schema describes the possible structure of state, not the actual values for a particular execution.

When a customer submits a question, the application supplies concrete values. Other fields may become available only after their corresponding nodes execute.

Your first stateful graph

The following complete example defines a state schema, registers two nodes, and demonstrates how information produced by one node becomes available to another.

Python
from typing_extensions import TypedDict, NotRequired
from langgraph.graph import StateGraph, START, END

class SupportState(TypedDict):
    question: str
    category: NotRequired[str]
    response: NotRequired[str]

def classify_question(state: SupportState) -> dict:
    question = state["question"].lower()

    if "password" in question:
        return {"category": "account"}
    return {"category": "general"}

def generate_response(state: SupportState) -> dict:
    if state["category"] == "account":
        response = "Use the password reset option on the login page."
    else:
        response = "Please provide more details about your question."

    return {"response": response}

builder = StateGraph(SupportState)

builder.add_node("classify", classify_question)
builder.add_node("respond", generate_response)

builder.add_edge(START, "classify")
builder.add_edge("classify", "respond")
builder.add_edge("respond", END)

graph = builder.compile()

result = graph.invoke({
    "question": "How do I reset my password?"
})

print(result)

Expected output:

Text
{
    'question': 'How do I reset my password?',
    'category': 'account',
    'response': 'Use the password reset option on the login page.'
}

Notice that the original question is still present even though neither node explicitly returned it.

LangGraph maintains existing state fields while applying the updates returned by each node.

Understanding StateGraph

The StateGraph class is a graph builder that uses a state schema to establish the application’s shared data structure.

In the previous example:

Python
builder = StateGraph(SupportState)

This tells LangGraph to construct the workflow around the fields declared in SupportState.

Internally, LangGraph represents these fields through channels. A channel maintains a value and determines how incoming updates affect that value.

Conceptually, our graph has three application state channels:

  • A question channel.
  • A category channel.
  • A response channel.

These are logical mechanisms managed by the runtime, not separate databases or network connections.

Calling compile() prepares the executable graph. Calling invoke() supplies input and executes the workflow.

The schema remains the same across executions, while the actual state values can differ.

Required and optional state fields

Not every state field needs to exist when execution begins.

Our example declares question as a required key and uses NotRequired for fields that are populated later.

This accurately expresses the application’s lifecycle:

  • The caller supplies the question.
  • The classification node produces the category.
  • The response node produces the response.

NotRequired[str] means the key may be absent. By comparison, str | None means the value may be a string or None; it does not by itself make the key optional.

This distinction matters when reading fields that have not yet been initialized.

Use state.get("category") if absence is expected and meaningful. Use state["category"] when the workflow guarantees that the classification node has already produced it.

Note: TypedDict provides structural type information but does not automatically validate dictionary values at runtime. Validate untrusted inputs explicitly. The next lesson examines runtime validation using Pydantic and alternative schema definitions.

How updates work

A common beginner mistake is assuming that nodes must return the entire state object.

In LangGraph, a node typically returns a partial update containing only the fields it intends to change.

Suppose the current state is:

JSON
{
    "question": "How do I reset my password?",
    "category": "unknown"
}

If a node returns:

Python
{"category": "account"}

The resulting state becomes:

JSON
{
    "question": "How do I reset my password?",
    "category": "account"
}

The question remains unchanged. Only the category is replaced.

This is conceptually similar to updating selected columns in a SQL record or submitting a partial update through a REST API. However, LangGraph applies its own channel-specific update rules.

Default replacement behavior

Unless a field defines a custom reducer or another channel behavior, an update replaces its previous value.

Consider a field named status. If one node returns "processing" and a later node returns "completed", the final value is "completed".

The following runnable example demonstrates replacement, preservation, and independent graph invocations.

Python
from typing_extensions import TypedDict
from langgraph.graph import StateGraph, START, END

class ProcessingState(TypedDict):
    request_id: str
    status: str
    attempts: int

def start_processing(state: ProcessingState) -> dict:
    return {
        "status": "processing",
        "attempts": state["attempts"] + 1,
    }

def finish_processing(state: ProcessingState) -> dict:
    return {"status": "completed"}

builder = StateGraph(ProcessingState)

builder.add_node("process", start_processing)
builder.add_node("finish", finish_processing)

builder.add_edge(START, "process")
builder.add_edge("process", "finish")
builder.add_edge("finish", END)

graph = builder.compile()

result = graph.invoke({
    "request_id": "REQ-101",
    "status": "pending",
    "attempts": 0,
})

print(result)

assert result["request_id"] == "REQ-101"
assert result["status"] == "completed"
assert result["attempts"] == 1

Expected output:

Text
{'request_id': 'REQ-101', 'status': 'completed', 'attempts': 1}

The state evolves as follows:

Execution stage request_id status attempts
Initial input REQ-101 pending 0
After process REQ-101 processing 1
After finish REQ-101 completed 1

Notice that attempts is not automatically incremented by LangGraph. The node explicitly calculates its next value.

The same principle applies to lists and dictionaries. Returning a new list ordinarily replaces the existing list. Returning a dictionary as the value of a state field does not automatically perform a recursive merge.

Returning updates instead of mutating state

Avoid treating the state received by a node as an ordinary mutable object that you can modify freely.

Consider these two implementations:

Python
def update_status_bad(state):
    state["status"] = "completed"
    return state

def update_status_good(state):
    return {"status": "completed"}

The second implementation expresses exactly what the node intends to change.

Direct mutation can introduce unintended side effects, particularly when nested mutable objects, parallel execution, checkpointing, or reducers are involved.

Returning the entire state may also produce unnecessary writes and interfere with fields managed by accumulation rules.

If you need to update a nested dictionary, construct a new dictionary rather than changing the existing object in place.

Python
def update_customer(state):
    customer = {
        **state["customer"],
        "verified": True,
    }

    return {"customer": customer}

These two snippets illustrate node implementation patterns; they are not independent graph applications.

A node that performs no state-changing operation can return an empty dictionary:

Python
return {}

Omitting a field from an update is different from explicitly assigning None, an empty string, or an empty list. Omitted fields remain unchanged under ordinary channel behavior.

State propagation

State propagation describes how updates become available to other nodes as the graph executes.

In a conventional Python application, you might write:

Python
classification = classify(question)
documents = retrieve(classification)
response = generate(question, documents)

You are responsible for passing each intermediate value to the next function.

LangGraph allows nodes to communicate through declared state channels instead. Nodes do not need to call each other directly.

Edges determine when nodes execute. State channels determine which application values are available to those nodes.

Sequential propagation

For a sequential graph, the process is straightforward:

  1. A node receives the currently available state.
  2. It executes its operation.
  3. It returns an update.
  4. LangGraph applies the update.
  5. The next node receives the resulting state according to its input schema.

This means that a downstream node can access a value produced several steps earlier, even if the immediately preceding node did not return that value.

Supersteps and parallel propagation

Internally, LangGraph uses a Pregel-inspired execution model organized into units called supersteps.

A superstep has three conceptual phases:

  1. Planning determines which nodes are ready to execute.
  2. Execution runs the selected nodes.
  3. Updating incorporates the writes produced during that step.

When multiple nodes execute in the same superstep, they read the state available at the beginning of that step. They do not ordinarily observe one another’s pending state updates.

The following diagram illustrates parallel operations followed by a synchronization point.

State propagation diagram: START to Normalize Question; Normalize Question to Search Documents; Normalize Question to Check Customer; Search Documents to Apply Updates; Check Customer to Apply Updates; Apply Updates to Generate Response; Generate Response to END.

Here, Apply Updates represents the runtime’s synchronization and update boundary, not an additional application node.

The runtime incorporates both completed branches’ updates before the dependent response-generation step runs.

For further technical details, see the LangGraph runtime documentation.

Building a graph with parallel state updates

The following example demonstrates two parallel nodes writing to different state fields, followed by a node that consumes both results.

Python
from typing_extensions import TypedDict, NotRequired
from langgraph.graph import StateGraph, START, END

class ResearchState(TypedDict):
    question: str
    documents: NotRequired[list[str]]
    customer_tier: NotRequired[str]
    response: NotRequired[str]

def search_documents(state: ResearchState) -> dict:
    return {
        "documents": [
            "Refund requests are accepted within 30 days."
        ]
    }

def check_customer(state: ResearchState) -> dict:
    return {"customer_tier": "premium"}

def generate_response(state: ResearchState) -> dict:
    response = (
        f"Customer tier: {state['customer_tier']}. "
        f"{state['documents'][0]}"
    )

    return {"response": response}

builder = StateGraph(ResearchState)

builder.add_node("search", search_documents)
builder.add_node("customer", check_customer)
builder.add_node("respond", generate_response)

builder.add_edge(START, "search")
builder.add_edge(START, "customer")

builder.add_edge(["search", "customer"], "respond")

builder.add_edge("respond", END)

graph = builder.compile()

result = graph.invoke({
    "question": "Can I request a refund?"
})

print(result["response"])

Expected output:

Text
Customer tier: premium. Refund requests are accepted within 30 days.

Both parallel nodes receive the original question. Each writes to a different channel, allowing their updates to coexist without a conflict.

The list-based edge explicitly waits for both branches before activating the response node.

What happens if both parallel nodes update the same ordinary state field?

LangGraph cannot safely determine which value should replace the other. It raises an InvalidUpdateError, associated with INVALID_CONCURRENT_GRAPH_UPDATE.

To support multiple writes to the same field, you can define a reducer that specifies how values should be combined. Reducers and Annotated types are covered in depth later in this chapter.

Inspecting state propagation with streaming

When debugging a workflow, inspecting only its final result may not reveal where an incorrect value originated.

LangGraph provides streaming interfaces that let you observe state during execution.

The following complete example demonstrates the difference between individual node updates and accumulated state snapshots.

Python
from typing_extensions import TypedDict
from langgraph.graph import StateGraph, START, END

class CounterState(TypedDict):
    count: int

def increment(state: CounterState) -> dict:
    return {"count": state["count"] + 1}

def double(state: CounterState) -> dict:
    return {"count": state["count"] * 2}

builder = StateGraph(CounterState)

builder.add_node("increment", increment)
builder.add_node("double", double)

builder.add_edge(START, "increment")
builder.add_edge("increment", "double")
builder.add_edge("double", END)

graph = builder.compile()

for chunk in graph.stream(
    {"count": 5},
    stream_mode=["updates", "values"],
    version="v2",
):
    print(chunk["type"], chunk["data"])

Expected output:

Text
values {'count': 5}
updates {'increment': {'count': 6}}
values {'count': 6}
updates {'double': {'count': 12}}
values {'count': 12}

The updates mode exposes writes associated with individual nodes. The values mode exposes accumulated state snapshots.

Using both modes helps you distinguish what a node returned from what the runtime actually maintains.

See the LangGraph streaming documentation for additional streaming capabilities.

Designing good state

State design is an architectural responsibility, not simply a Python typing exercise.

A poorly designed schema can make an agent difficult to debug, expensive to checkpoint, unnecessarily coupled, and vulnerable to accidental data exposure.

Store information that survives node boundaries

Include a value in state when another node needs it, when it influences future decisions, or when it must be recoverable during execution.

Temporary variables used exclusively inside one function generally do not belong in shared state.

For example, a retrieval node might generate a temporary search query. If nothing else needs that query, keep it local. If another node must review or retry the exact query, storing it in state may be appropriate.

Separate state from runtime context

Not all information required by nodes is evolving workflow state.

LangGraph 1.x supports runtime context through context_schema and Runtime. Context is appropriate for invocation-specific configuration and dependencies that nodes need to access without updating them as ordinary state.

Information Appropriate location
Current customer question Graph state
Retrieved documents Graph state or external storage reference
Current workflow status Graph state
Authenticated tenant identity Runtime context
Database client Runtime context or dependency layer
Temporary calculation Local variable
Persistent user preferences Long-term store or database
API credentials Secure configuration or secret manager

Avoid placing live database connections, HTTP clients, API keys, or unnecessary sensitive records inside checkpointable state.

Similarly, do not use config["configurable"] as a general-purpose container for application user data. Use the runtime context API for that purpose.

Input and output schemas

Internal workflow data is not necessarily appropriate for external callers.

For example, a customer-facing support API might accept a question and return an answer. Internally, the graph also maintains classifications, retrieved documents, and routing information.

LangGraph supports separate input and output schemas through StateGraph.

The following example creates an explicit public interface while preserving additional internal state.

Python
from typing_extensions import TypedDict, NotRequired
from langgraph.graph import StateGraph, START, END

class InputState(TypedDict):
    question: str

class OutputState(TypedDict):
    answer: str

class InternalState(InputState):
    category: NotRequired[str]
    answer: NotRequired[str]

def classify(state: InputState) -> dict:
    category = (
        "billing"
        if "refund" in state["question"].lower()
        else "general"
    )

    return {"category": category}

def respond(state: InternalState) -> dict:
    return {
        "answer": f"Your request belongs to {state['category']} support."
    }

builder = StateGraph(
    InternalState,
    input_schema=InputState,
    output_schema=OutputState,
)

builder.add_node("classify", classify)
builder.add_node("respond", respond)

builder.add_edge(START, "classify")
builder.add_edge("classify", "respond")
builder.add_edge("respond", END)

graph = builder.compile()

result = graph.invoke({
    "question": "Can I get a refund?"
})

print(result)

assert "category" not in result

Expected output:

Text
{'answer': 'Your request belongs to billing support.'}

The category remains available internally but is excluded from the normal invocation result.

This separation makes it easier to evolve internal implementation details without changing the public API contract.

Private state channels

LangGraph also supports additional channels used by selected nodes without including them in the graph’s main state schema.

For example, a retrieval node and a ranking node might share intermediate candidate documents that other nodes do not need.

The following example introduces a private channel through a node-specific input schema.

Python
from typing_extensions import TypedDict, NotRequired
from langgraph.graph import StateGraph, START, END

class PublicState(TypedDict):
    question: str
    answer: NotRequired[str]

class PrivateState(TypedDict):
    candidates: list[str]

def retrieve(state: PublicState) -> dict:
    return {
        "candidates": [
            "Refunds are available within 30 days.",
            "Contact support for assistance.",
        ]
    }

def select_answer(state: PrivateState) -> dict:
    return {"answer": state["candidates"][0]}

def finalize(state: PublicState) -> dict:
    assert "candidates" not in state
    return {}

builder = StateGraph(PublicState)

builder.add_node("retrieve", retrieve)
builder.add_node(
    "select",
    select_answer,
    input_schema=PrivateState,
)
builder.add_node("finalize", finalize)

builder.add_edge(START, "retrieve")
builder.add_edge("retrieve", "select")
builder.add_edge("select", "finalize")
builder.add_edge("finalize", END)

graph = builder.compile()

print(graph.invoke({
    "question": "What is the refund policy?"
}))

Expected output:

Text
{
    'question': 'What is the refund policy?',
    'answer': 'Refunds are available within 30 days.'
}

Registering the node-specific schema establishes the additional channel. The retrieval node writes to it, the selection node reads it, and the finalization node receives the public state projection.

Note: Private channels and output schemas are architectural boundaries, not security guarantees. Internal values may still appear in streams, checkpoints, and traces. Apply authorization, redaction, and explicit output filtering before exposing such information to external users.

The state management documentation describes these schema and visibility mechanisms in greater detail.

State lifetime and persistence

A graph maintaining state throughout one execution does not automatically make it remember previous executions.

Without checkpointing, independent invocations normally begin with their supplied input rather than inheriting the previous invocation’s state.

With a checkpointer, state can be retained and recovered across invocations associated with the same thread.

The following example demonstrates this distinction using an in-memory checkpointer.

Python
from typing_extensions import TypedDict
from langgraph.graph import StateGraph, START, END
from langgraph.checkpoint.memory import InMemorySaver

class SessionState(TypedDict):
    visits: int
    latest_message: str

def record_visit(state: SessionState) -> dict:
    return {"visits": state.get("visits", 0) + 1}

builder = StateGraph(SessionState)

builder.add_node("record", record_visit)
builder.add_edge(START, "record")
builder.add_edge("record", END)

graph = builder.compile(
    checkpointer=InMemorySaver()
)

config = {
    "configurable": {
        "thread_id": "customer-session-101"
    }
}

first = graph.invoke({
    "visits": 0,
    "latest_message": "Hello"
}, config)

second = graph.invoke({
    "latest_message": "I need help"
}, config)

print(first)
print(second)

snapshot = graph.get_state(config)
print(snapshot.values)

Expected output:

Text
{'visits': 1, 'latest_message': 'Hello'}
{'visits': 2, 'latest_message': 'I need help'}
{'visits': 2, 'latest_message': 'I need help'}

The second invocation retains the previous visit count because it uses the same checkpointed thread.

InMemorySaver is suitable for learning and testing, but its contents do not survive process restarts. Production persistence and durable recovery will be covered in later chapters.

Common mistakes and production best practices

Common mistake Better approach
Returning the entire state from every node Return only intended updates
Mutating state directly Construct explicit update dictionaries
Reading fields before initialization Establish execution dependencies
Assuming lists automatically accumulate Define appropriate reducers
Writing concurrently to an ordinary channel Use separate fields or a reducer
Storing credentials in state Use secure dependency configuration
Allowing state to grow indefinitely Bound, summarize, or externalize large data
Assuming every invocation remembers previous runs Configure checkpointing deliberately
Treating private channels as security controls Enforce explicit access and exposure policies

Prefer descriptive field names such as retrieved_documents, approval_status, and customer_question rather than ambiguous names such as data, temp, and result.

Maintain structured source information rather than storing preformatted prompts whenever possible. Construct prompts inside model-calling nodes so different nodes can reuse the same underlying data.

Think carefully about ownership. Identify which nodes produce each field, which nodes consume it, and whether multiple nodes can update it concurrently.

Also distinguish business state from runtime execution metadata. Store a business-specific attempt counter when it influences application behavior, but avoid duplicating information already managed by the execution engine.

For production systems, consider schema evolution. Changing a field’s name or type may affect existing checkpoints and resumed workflows. Such changes should be treated as compatibility and migration decisions.

Connection to the next lesson

The chapter’s hands-on project is a stateful conversational application. Its state will eventually need to represent conversation history, user questions, assistant responses, and additional workflow information.

The principles introduced here establish the foundation for that application. However, a plain list of conversation messages would be replaced whenever a node returned a new list unless appropriate update behavior were configured.

Later in this chapter, Reducers and Annotated types will explain how to control accumulation and concurrent writes. MessagesState and add_messages will then introduce conversation-specific state management, including the ability to append and update messages.

Before exploring those mechanisms, the next lesson, State schemas — TypedDict, Pydantic and dataclasses, examines the available schema representations in detail.

You will learn how to choose the appropriate schema for a particular application, define defaults, establish validation boundaries, and balance development simplicity against production requirements.

Exercise

Build a stateful customer support workflow

Build a LangGraph workflow that receives a customer support request, classifies its category, assigns a priority, and generates a response. Each node must return only the state fields it updates. Use a TypedDict state schema and verify that the original request remains available throughout the workflow. Test the graph with billing, technical, and general support requests.

Python
from typing import Literal
from typing_extensions import TypedDict, NotRequired
from langgraph.graph import StateGraph, START, END


class SupportState(TypedDict):
    request: str
    category: NotRequired[Literal["billing", "technical", "general"]]
    priority: NotRequired[Literal["high", "normal"]]
    response: NotRequired[str]


def classify_request(state: SupportState) -> dict:
    # TODO: Classify the request as billing, technical, or general.
    raise NotImplementedError


def assign_priority(state: SupportState) -> dict:
    # TODO: Assign high priority to billing requests
    # and requests containing the word "urgent".
    raise NotImplementedError


def generate_response(state: SupportState) -> dict:
    # TODO: Generate a response using category and priority.
    raise NotImplementedError


builder = StateGraph(SupportState)

# TODO: Register the three nodes.

# TODO: Connect START, the nodes, and END.

graph = builder.compile()

requests = [
    "I was charged twice for my subscription.",
    "The application keeps crashing.",
    "How do I update my profile?",
]

for request in requests:
    result = graph.invoke({"request": request})
    print(result)

Summary

  • Graph state is the shared application data that nodes read and update during graph execution.
  • A state schema defines the available state channels, their expected types, and their update behavior.
  • Nodes should return partial state updates instead of directly mutating their input state.
  • State fields without custom reducers use replacement semantics rather than automatic accumulation.
  • Sequential nodes observe previously committed updates, while parallel nodes operate on the state available at the beginning of their superstep.
  • Input schemas, output schemas, and private state channels help establish clear boundaries between public and internal application data.
  • State propagation within a graph execution is automatic, but retaining state across separate invocations requires explicit state management or checkpointing.