Reading, updating and listing state

Topic 3 of 4 in Persistence & checkpointing23 min readIntermediateFree course

Overview

In the previous lesson, you learned how SQLite and PostgreSQL checkpointers persist LangGraph state beyond the lifetime of a Python process. Your graph can now remember conversations, recover unfinished workflows, and preserve intermediate execution results.

However, persistence becomes significantly more valuable when your application can interact with saved state without running the graph.

Imagine a customer support agent that incorrectly classifies a payment dispute as a low-priority request. A supervisor needs to inspect the conversation, determine where the classification went wrong, and correct the priority without starting the entire workflow again.

LangGraph provides three principal methods for these operations:

Method Purpose Executes graph nodes? Creates a checkpoint?
get_state() Retrieve a state snapshot No No
get_state_history() Browse saved checkpoints No No
update_state() Modify persisted state No Yes

These methods belong to the compiled graph. They work with in-memory, SQLite, and PostgreSQL checkpointers, allowing application code to remain largely independent of the persistence backend.

This lesson uses deterministic Python nodes rather than an LLM so that checkpoint behavior can be studied independently of model variability, API credentials, and inference costs.

Install the required packages:

Terminal
pip install "langgraph>=1.0,<2" "langchain>=1.0,<2"

Use Python 3.10 or later. The examples follow the LangGraph 1.x APIs. Their expected outputs are derived from documented API behavior; they have not been execution-tested in the authoring environment.

Understanding state snapshots

A checkpoint represents saved graph state at an execution boundary. A thread is a collection of checkpoints associated with a particular conversation or workflow.

Consider an order-processing graph with two sequential nodes: validation and price calculation.

The following diagram illustrates how execution produces successive checkpoints.

Understanding state snapshots diagram: START to Validate order; Validate order to Calculate price; Calculate price to END; START to Input checkpoint; Validate order to Validation checkpoint; Calculate price to Final checkpoint.

Conceptually, LangGraph maintains both application data and execution information. Saving only the order details would not be sufficient for recovery because the runtime also needs to know which operations remain unfinished.

Internally, graph nodes read state channels and return updates. LangGraph applies these updates according to the channel definitions and reducers, determines subsequent execution, and records checkpoint information at super-step boundaries.

A super-step is an execution round in which one or more scheduled nodes can run. Parallel nodes may belong to the same super-step, so the number of checkpoints does not necessarily equal the number of executed nodes.

When you retrieve saved state through the compiled graph, LangGraph exposes this information through a StateSnapshot object.

get_state: retrieving the latest snapshot

The simplest way to inspect a thread is to call:

Python
snapshot = graph.get_state(config)

The configuration identifies the thread:

Python
config = {
    "configurable": {
        "thread_id": "order-101"
    }
}

When no checkpoint identifier is supplied, LangGraph retrieves the latest available checkpoint for that thread and checkpoint namespace.

This operation does not start a new graph run, call an LLM, or execute tools.

Anatomy of StateSnapshot

A snapshot exposes the following important attributes:

Attribute Meaning
values Current application state values
next Tuple containing the names of scheduled next nodes
config Configuration identifying this checkpoint
metadata Information about checkpoint creation and execution
created_at Checkpoint creation timestamp
parent_config Configuration identifying the preceding checkpoint
tasks Task information, including available errors and interrupts
interrupts Interrupt information associated with the snapshot

The values attribute is generally what application developers need most frequently. The other attributes provide operational visibility into the graph’s execution.

For example, a completed sequential workflow normally has snapshot.next == (). A paused workflow might have snapshot.next == ("calculate",).

The configuration returned by a snapshot includes a checkpoint_id and a checkpoint_ns, in addition to the thread_id. An empty checkpoint namespace identifies the root graph.

For the complete field definitions, consult the StateSnapshot API reference.

Example: inspecting an order workflow

This complete example executes a two-node order workflow and then inspects its persisted state.

Python
from typing import TypedDict

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

class OrderState(TypedDict):
    product: str
    quantity: int
    unit_price: int
    total: int
    status: str

def validate(state: OrderState) -> dict:
    if state["quantity"] <= 0:
        raise ValueError("Quantity must be positive")

    return {"status": "validated"}

def calculate(state: OrderState) -> dict:
    return {
        "total": state["quantity"] * state["unit_price"],
        "status": "calculated",
    }

builder = StateGraph(OrderState)
builder.add_node("validate", validate)
builder.add_node("calculate", calculate)

builder.add_edge(START, "validate")
builder.add_edge("validate", "calculate")
builder.add_edge("calculate", END)

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

config = {"configurable": {"thread_id": "order-101"}}

graph.invoke(
    {
        "product": "Keyboard",
        "quantity": 2,
        "unit_price": 1500,
        "total": 0,
        "status": "new",
    },
    config,
    durability="sync",
)

snapshot = graph.get_state(config)

print("State:", snapshot.values)
print("Next nodes:", snapshot.next)
print("Step:", snapshot.metadata["step"])
print("Source:", snapshot.metadata["source"])
print("Checkpoint ID:",
      snapshot.config["configurable"]["checkpoint_id"])
print("Created at:", snapshot.created_at)

Expected output, excluding generated identifiers and timestamps:

Text
State: {'product': 'Keyboard', 'quantity': 2,
        'unit_price': 1500, 'total': 3000,
        'status': 'calculated'}
Next nodes: ()
Step: 2
Source: loop

The important distinction is that graph.invoke() executes the workflow, whereas graph.get_state() reads its saved representation.

An application could use this method to populate an order details page without performing validation or calculation again.

Retrieving a specific checkpoint

You are not restricted to the latest state. You can retrieve a historical snapshot by supplying its identifier.

Python
historical_config = {
    "configurable": {
        "thread_id": "order-101",
        "checkpoint_id": saved_checkpoint_id,
    }
}

Here, saved_checkpoint_id represents a previously recorded identifier. In practice, retaining the entire snapshot.config is preferable because it preserves checkpoint namespace information.

Note: Treat snapshots as read-only representations. Modifying snapshot.values in Python is not a supported way to persist changes. Use update_state() for that purpose.

get_state_history: exploring every saved step

Retrieving the latest state tells you where a workflow currently stands. State history tells you how it arrived there.

The method:

Python
graph.get_state_history(config)

returns an iterator of StateSnapshot objects, with the newest checkpoints appearing first.

This ordering is important. The first snapshot is ordinarily the latest available checkpoint, not the beginning of the workflow.

Example: tracing a workflow’s execution

The following independent example creates a document-processing workflow and displays its checkpoint history.

Python
from typing import Annotated, TypedDict
from operator import add

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

class DocumentState(TypedDict):
    status: str
    events: Annotated[list[str], add]

def extract(state: DocumentState) -> dict:
    return {
        "status": "extracted",
        "events": ["Text extracted"],
    }

def classify(state: DocumentState) -> dict:
    return {
        "status": "classified",
        "events": ["Document classified"],
    }

builder = StateGraph(DocumentState)
builder.add_node("extract", extract)
builder.add_node("classify", classify)
builder.add_edge(START, "extract")
builder.add_edge("extract", "classify")
builder.add_edge("classify", END)

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

config = {"configurable": {"thread_id": "document-1"}}

graph.invoke(
    {"status": "new", "events": []},
    config,
    durability="sync",
)

history = list(graph.get_state_history(config))

for snapshot in history:
    metadata = snapshot.metadata or {}

    print(
        "Step:", metadata.get("step"),
        "| Status:", snapshot.values.get("status"),
        "| Next:", snapshot.next,
        "| Events:", snapshot.values.get("events", []),
    )

before_classification = next(
    snapshot for snapshot in history
    if snapshot.next == ("classify",)
)

historical = graph.get_state(before_classification.config)

print("Before classification:", historical.values)

Expected output:

Text
Step: 2 | Status: classified | Next: () | Events: ['Text extracted', 'Document classified']
Step: 1 | Status: extracted | Next: ('classify',) | Events: ['Text extracted']
Step: 0 | Status: new | Next: ('extract',) | Events: []
Step: -1 | Status: None | Next: ('__start__',) | Events: []
Before classification: {'status': 'extracted', 'events': ['Text extracted']}

Notice the initial internal checkpoint and the checkpoint containing the graph’s input. LangGraph saves execution boundaries beyond those corresponding directly to business nodes.

This explains why a simple two-node graph can produce four checkpoints.

Understanding checkpoint metadata

Two particularly useful metadata fields are step and source.

The step number identifies an execution round. The source describes how the checkpoint was produced. Common values include:

  • input — associated with incoming graph input.
  • loop — associated with normal runtime progression.
  • update — associated with an external state modification.

Avoid relying on undocumented metadata fields or assuming step numbers uniquely identify checkpoints across branches. Use checkpoint identifiers when exact identity matters.

Filtering and paginating history

Long-running conversations may accumulate thousands of checkpoints. Loading their entire history into memory can become expensive, particularly when each snapshot contains a substantial message list.

Using the graph and configuration from the preceding example, you can request a limited number of results:

Python
recent = list(graph.get_state_history(config, limit=2))

older = list(
    graph.get_state_history(
        config,
        before=recent[-1].config,
        limit=2,
    )
)

print("Recent steps:", [s.metadata["step"] for s in recent])
print("Older steps:", [s.metadata["step"] for s in older])

Expected output:

Text
Recent steps: [2, 1]
Older steps: [0, -1]

The before parameter acts as a checkpoint-based pagination boundary.

You can also filter by checkpoint metadata:

Python
manual_updates = list(
    graph.get_state_history(
        config,
        filter={"source": "update"},
        limit=20,
    )
)

This returns matching manual updates, if any exist. These options are documented in the get_state_history API reference.

History is not necessarily a single linear timeline

Initially, checkpoints form a straightforward progression. However, modifying an older checkpoint can introduce another branch.

History listing returns saved checkpoints for the selected thread and namespace; it is not necessarily restricted to the ancestry of one checkpoint. To reconstruct a particular branch, follow each snapshot’s parent_config.

Also remember that checkpoint history is not a comprehensive trace of every internal operation. Individual tool calls or parallel task writes do not necessarily have separate full state snapshots.

update_state: changing state from outside the graph

Nodes normally modify state by returning dictionaries. However, application code sometimes needs to correct or enrich persisted state independently of node execution.

The method signature is:

Python
updated_config = graph.update_state(
    config,
    values,
    as_node=None,
)

The values argument contains the state fields you want to modify. It is usually a partial state dictionary rather than a replacement for the entire graph state.

The returned object is a configuration identifying the newly created checkpoint, not the updated state itself.

Retrieve the updated snapshot by calling graph.get_state(updated_config).

Reducers still apply

External updates follow the same state-writing semantics as node updates.

Consider the following state definition:

Python
class State(TypedDict):
    status: str
    notes: Annotated[list[str], add]

The status field uses ordinary replacement semantics. The notes field uses an additive reducer.

Suppose the existing values are:

Python
{
    "status": "pending",
    "notes": ["Request received"]
}

An update containing:

Python
{
    "status": "approved",
    "notes": ["Approved by supervisor"]
}

produces:

Python
{
    "status": "approved",
    "notes": [
        "Request received",
        "Approved by supervisor"
    ]
}

Passing the complete existing notes list alongside the new note would append the old notes again. Supply only the intended additions.

When replacement of a reducer-managed value is genuinely required, LangGraph 1.x provides Overwrite from langgraph.types. Use it deliberately because it bypasses the channel’s reducer.

as_node: attributing an external update

The as_node argument is one of the most important details of external state management.

Consider this workflow:

START → prepare → calculate → END

An update attributed to prepare is processed as though prepare produced the supplied values. LangGraph applies that node’s writers and determines subsequent execution accordingly.

Crucially, it does not execute the Python function implementing prepare.

If as_node is omitted, LangGraph attempts to infer the appropriate node from checkpoint execution information. This works when the preceding writer is unambiguous. Parallel execution can make that inference impossible, producing an InvalidUpdateError.

Example: correcting data and scheduling recalculation

This example modifies an order quantity after calculation has completed. It attributes the correction to the preparation node so that calculation becomes the next scheduled operation.

Python
from typing import TypedDict

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

class QuoteState(TypedDict):
    quantity: int
    unit_price: int
    total: int

def prepare(state: QuoteState) -> dict:
    print("Preparing quote")

    if state["quantity"] <= 0:
        raise ValueError("Invalid quantity")

    return {"quantity": state["quantity"]}

def calculate(state: QuoteState) -> dict:
    print("Calculating total")
    return {
        "total": state["quantity"] * state["unit_price"]
    }

builder = StateGraph(QuoteState)
builder.add_node("prepare", prepare)
builder.add_node("calculate", calculate)

builder.add_edge(START, "prepare")
builder.add_edge("prepare", "calculate")
builder.add_edge("calculate", END)

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

config = {"configurable": {"thread_id": "quote-1"}}

graph.invoke(
    {"quantity": 2, "unit_price": 500, "total": 0},
    config,
    durability="sync",
)

original = graph.get_state(config)

new_quantity = 4

if new_quantity <= 0:
    raise ValueError("Invalid quantity")

updated_config = graph.update_state(
    config,
    {"quantity": new_quantity},
    as_node="prepare",
)

updated = graph.get_state(updated_config)

print("Updated state:", updated.values)
print("Next:", updated.next)

result = graph.invoke(
    None,
    updated_config,
    durability="sync",
)

print("Recalculated state:", result)
print("Original state:",
      graph.get_state(original.config).values)

Expected output:

Text
Preparing quote
Calculating total
Updated state: {'quantity': 4, 'unit_price': 500, 'total': 1000}
Next: ('calculate',)
Calculating total
Recalculated state: {'quantity': 4, 'unit_price': 500, 'total': 2000}
Original state: {'quantity': 2, 'unit_price': 500, 'total': 1000}

Several important things happen here.

First, the external update changes the quantity without executing either node. Second, the stored total temporarily remains inconsistent with the new quantity. Third, attribution to prepare schedules its successor. Finally, invoking with None continues the scheduled work rather than submitting fresh graph input.

This pattern is useful for recomputing derived fields after correcting their underlying inputs.

Tip: Never assume that as_node executes the specified node’s validation, authorization, or business logic. Validate external updates independently before writing them.

Updates create new checkpoints

LangGraph does not overwrite the original historical checkpoint when update_state() is called.

Instead, the runtime applies the supplied modifications and records a new checkpoint containing the resulting state and execution information.

The following diagram illustrates an external correction followed by continued execution.

Updates create new checkpoints diagram: Original checkpoint to External update; External update to Apply reducers; Apply reducers to New checkpoint; New checkpoint to Resume execution; Resume execution to Final checkpoint.

Using the preceding quote example, the original snapshot still contains a quantity of two, even after the latest state contains a quantity of four.

You can compare checkpoint identifiers to verify this behavior:

Python
old_id = original.config["configurable"]["checkpoint_id"]
new_id = updated.config["configurable"]["checkpoint_id"]

assert old_id != new_id

assert (
    updated.parent_config["configurable"]["checkpoint_id"]
    == old_id
)

The new checkpoint references the original checkpoint as its parent.

This provides historical versioning and makes administrative changes traceable. However, checkpoint history alone is not a complete compliance audit system. It does not automatically establish who authorized a modification or whether that modification was legitimate.

An application requiring formal auditability should separately record the authenticated actor, modification reason, previous checkpoint identifier, new checkpoint identifier, and timestamp.

Practical uses in agentic applications

Restoring previous chatbot conversations

The chapter’s hands-on project involves building a chatbot that restores previous conversations. State inspection provides the foundation for implementing its conversation-management interface.

A chat application can retrieve persisted messages before the user submits another request. This avoids unnecessary model calls simply to display conversation history.

With MessagesState, the messages field uses the add_messages reducer. New messages are appended, messages with matching IDs are replaced, and RemoveMessage can remove messages from the current state.

Example: restoring and editing a SQLite conversation

Install the SQLite checkpointer:

Terminal
pip install langgraph-checkpoint-sqlite

This standalone example simulates closing and reopening a chatbot application. A deterministic response node is used instead of an LLM.

Python
from pathlib import Path
from tempfile import TemporaryDirectory

from langchain.messages import HumanMessage, AIMessage, RemoveMessage
from langgraph.graph import StateGraph, MessagesState, START, END
from langgraph.checkpoint.sqlite import SqliteSaver

def reply(state: MessagesState) -> dict:
    latest = state["messages"][-1]

    return {
        "messages": [
            AIMessage(content=f"Received: {latest.content}")
        ]
    }

def build_graph(checkpointer):
    builder = StateGraph(MessagesState)
    builder.add_node("reply", reply)
    builder.add_edge(START, "reply")
    builder.add_edge("reply", END)
    return builder.compile(checkpointer=checkpointer)

config = {
    "configurable": {"thread_id": "conversation-101"}
}

with TemporaryDirectory() as directory:
    db_path = str(Path(directory) / "chat.db")

    # First application session.
    with SqliteSaver.from_conn_string(db_path) as saver:
        graph = build_graph(saver)

        graph.invoke(
            {
                "messages": [
                    HumanMessage(content="My name is Ravi")
                ]
            },
            config,
            durability="sync",
        )

    # Reopen the application using the same database.
    with SqliteSaver.from_conn_string(db_path) as saver:
        graph = build_graph(saver)

        original = graph.get_state(config)

        print("Restored conversation:")

        for message in original.values["messages"]:
            print(message.type, message.content)

        assistant_message = original.values["messages"][-1]

        corrected_config = graph.update_state(
            config,
            {
                "messages": [
                    AIMessage(
                        id=assistant_message.id,
                        content="Hello Ravi! How can I help?",
                    )
                ]
            },
            as_node="reply",
        )

        corrected = graph.get_state(corrected_config)

        print("Corrected response:",
              corrected.values["messages"][-1].content)

        graph.update_state(
            config,
            {
                "messages": [
                    RemoveMessage(id=assistant_message.id)
                ]
            },
            as_node="reply",
        )

        latest = graph.get_state(config)

        print("Remaining messages:",
              len(latest.values["messages"]))

        print("Historical response:",
              graph.get_state(original.config)
              .values["messages"][-1].content)

        thread_ids = {
            item.config["configurable"]["thread_id"]
            for item in saver.list(None)
        }

        print("Saved threads:", sorted(thread_ids))

Expected output:

Text
Restored conversation:
human My name is Ravi
ai Received: My name is Ravi
Corrected response: Hello Ravi! How can I help?
Remaining messages: 1
Historical response: Received: My name is Ravi
Saved threads: ['conversation-101']

Replacing a message requires its existing ID. Without that ID, the reducer normally treats the replacement as a new message.

Removing a message changes the current conversation state but does not erase the message from older checkpoints. Real tool-calling conversations also require message-sequence consistency: removing a tool call without its associated tool results can leave invalid model input.

The temporary SQLite database is automatically cleaned up when the demonstration finishes. A real chatbot would use a stable database location.

Listing available conversations

The preceding example also demonstrates an important distinction: get_state_history() lists checkpoints belonging to one thread, not all conversations.

For locally compiled graphs, checkpointer.list(None) can enumerate stored checkpoints across threads. Because it returns checkpoint records rather than distinct conversations, deduplication is required.

For production systems, maintain an application-level conversation registry containing thread identifiers, owners, titles, and last-access timestamps. Scanning every checkpoint to construct a conversation sidebar is inefficient.

When using LangSmith Agent Server, use its thread-management APIs instead of directly accessing the server’s checkpoint tables.

Other practical applications

State inspection and external updates support several production workflows:

Application Typical operation
Debugging agents Inspect checkpoints preceding an incorrect decision
Human review Correct generated classifications or proposed actions
Customer support Escalate a ticket without repeating completed work
Workflow monitoring Inspect pending tasks and execution errors
Testing Prepare controlled state for downstream execution
Chat interfaces Restore or correct persisted conversation messages

For dynamic human-in-the-loop interruptions created with interrupt(), use the appropriate Command(resume=...) mechanism to supply the interrupt response. An ordinary state update is not a substitute for answering an interrupt.

Common mistakes and production best practices

Confusing thread identity with checkpoint identity

A thread identifies a continuing workflow. A checkpoint identifies one version within that workflow.

Use a thread-only configuration for normal latest-state access. Use a saved snapshot configuration when deliberately targeting a historical version.

Accidentally supplying an old checkpoint identifier to update_state() can create an unintended branch.

Assuming every intermediate state is durable

Checkpoint visibility depends on the durability mode selected during execution.

With durability="sync", checkpoint persistence completes before execution advances to the following step. The "async" mode overlaps checkpoint writing with execution, while "exit" defers persistence until execution exits.

If intermediate recovery points are essential, select the durability mode accordingly.

Updating an actively running thread

An administrator might read a snapshot while another request is updating the same conversation. The administrator’s correction could then be based on stale information.

Serialize conflicting operations per thread, or implement application-level concurrency control. A checkpoint identifier is useful for detecting stale reads, but passing it to update_state() is not an atomic compare-and-swap operation.

Bypassing security and business invariants

Treat state-management endpoints as privileged application operations.

Authenticate users, verify thread ownership, restrict editable fields, validate proposed values, and record administrative modifications. Never allow a client to freely choose arbitrary as_node values or alter authorization decisions.

For asynchronous applications, use await graph.aget_state(), async for with graph.aget_state_history(), and await graph.aupdate_state() alongside an appropriate asynchronous checkpointer.

Finally, retain checkpoints according to business and privacy requirements. Deleting information from current state does not automatically remove historical copies.

Connection to the next lesson

In the previous lesson, SQLite and PostgreSQL gave your graphs durable persistence. In this lesson, you learned how application code can interact with that persistence independently of ordinary graph execution.

You can now locate an exact execution boundary, inspect its state, identify pending nodes, and create a corrected checkpoint.

These capabilities provide the prerequisites for the next lesson, Time travel, replay and forking, where you will deliberately return to historical execution boundaries, re-execute selected portions of a workflow, and explore alternative execution paths without destroying the original history.

For further API details, refer to the official LangGraph checkpointers guide and the update_state API reference.

Exercise

Build a support ticket state manager

Build a persistent customer support workflow that allows an administrator to inspect, list, and modify the state of an existing ticket. Use get_state to retrieve the latest snapshot and get_state_history to display previous checkpoints. Correct the ticket priority and append an administrative note using update_state, then verify that the original checkpoint remains unchanged.

Python
from typing import Annotated, TypedDict
from operator import add

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


class TicketState(TypedDict):
    ticket_id: str
    description: str
    priority: str
    status: str
    notes: Annotated[list[str], add]


def classify_ticket(state: TicketState) -> dict:
    # TODO: Assign a default priority and append a note.
    raise NotImplementedError


def register_ticket(state: TicketState) -> dict:
    # TODO: Set the status to open and append a note.
    raise NotImplementedError


builder = StateGraph(TicketState)
builder.add_node("classify", classify_ticket)
builder.add_node("register", register_ticket)

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

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

config = {"configurable": {"thread_id": "ticket-101"}}

graph.invoke(
    {
        "ticket_id": "101",
        "description": "Payment deducted twice",
        "priority": "unknown",
        "status": "new",
        "notes": [],
    },
    config,
    durability="sync",
)

# TODO: Retrieve and print the latest state.

# TODO: Save the original snapshot configuration.

# TODO: List all checkpoints and their step numbers.

# TODO: Update priority to high and append an administrative note.
# Attribute the update to the register node.

# TODO: Retrieve the updated state.

# TODO: Retrieve the original checkpoint and verify its priority.

# TODO: Verify that the update created a new checkpoint.

Summary

  • get_state returns a StateSnapshot containing persisted state values and execution information for a thread.
  • A thread identifier retrieves the latest checkpoint, while a checkpoint identifier selects a specific historical snapshot.
  • get_state_history returns an iterator of saved snapshots ordered from newest to oldest.
  • update_state applies external modifications using the graph's state channels and reducer semantics.
  • The as_node argument determines which node receives credit for an external update and influences subsequent execution.
  • External state updates create new checkpoints without overwriting the original historical snapshots.
  • Production state management requires authorization, input validation, concurrency control, and appropriate checkpoint retention policies.