Time travel, replay and forking

Topic 4 of 4 in Persistence & checkpointing23 min readIntermediateFree course

Overview

Imagine that you have built an AI customer-support agent with LangGraph. The agent retrieves customer information, classifies a complaint, investigates the problem, and generates a response.

A customer receives an incorrect response because the agent misclassified their complaint.

How would you investigate the problem?

Without persistence, you might rerun the entire workflow, inspect application logs, or manually reconstruct the inputs. Unfortunately, the external data may have changed, and the language model may produce a different classification.

With LangGraph checkpointing, you can inspect the exact historical state, return to an earlier execution boundary, correct the classification, and execute the remaining workflow again.

This capability is called time travel.

In the previous lesson, you learned how to retrieve, inspect, and update persisted graph state. This lesson builds directly on those operations by treating checkpoints as execution boundaries that you can revisit.

Time travel supports three important operations:

  • Inspection: Read historical state without executing the graph.
  • Replay: Execute the remaining workflow from a historical checkpoint.
  • Forking: Modify historical state and execute an alternative workflow from that point.

These capabilities are valuable for debugging agents, experimenting with decisions, regenerating chatbot responses, recovering workflows, and building conversational products.

Understanding the execution timeline

A traditional application usually exposes its current state. LangGraph can preserve multiple historical states belonging to the same thread.

Consider a workflow that retrieves product information, calculates a price, and generates a quotation.

The following diagram shows the relationship between workflow execution and persisted checkpoints.

Overview diagram: START to Retrieve product; Retrieve product to Checkpoint one; Checkpoint one to Calculate price; Calculate price to Checkpoint two; Checkpoint two to Generate quotation; Generate quotation to Checkpoint three; Checkpoint three to END.

If you return to checkpoint two, the product retrieval and price calculation results are already available. You can execute quotation generation without repeating those earlier operations.

The diagram represents checkpoints conceptually; they are persisted execution boundaries rather than additional graph nodes.

How time travel works internally

LangGraph executes graphs in discrete units called super-steps. Sequential nodes generally execute in separate super-steps, while parallel nodes can execute within the same super-step.

At these boundaries, a checkpointer can persist information required to reconstruct graph state and determine which tasks should execute next.

A checkpoint therefore represents more than a dictionary containing application data. It also carries execution information.

Three identifiers help locate a checkpoint:

  • thread_id: Identifies the conversation or workflow thread.
  • checkpoint_id: Identifies a particular saved checkpoint.
  • checkpoint_ns: Identifies the checkpoint namespace, including nested graph contexts.

When you provide only a thread ID, LangGraph normally selects its latest checkpoint. When you provide a checkpoint ID as well, you explicitly identify a historical state.

Time travel operates at saved execution boundaries, not arbitrary Python statements inside a node.

Note: Historical state does not mean historical reality. Restoring a checkpoint cannot automatically restore external databases, reverse payments, retrieve deleted files, or recover the previous behavior of a model provider.

Finding the checkpoint you want

Before replaying or forking an execution, you must identify the correct starting point.

The primary API is graph.get_state_history(config), which provides an iterator over historical state snapshots, beginning with the newest checkpoints.

Each StateSnapshot exposes useful information:

Attribute Purpose
values Application state at the checkpoint
next Nodes scheduled to execute next
config Configuration identifying the checkpoint
metadata Execution metadata, including step and source
created_at Checkpoint creation timestamp
parent_config Configuration identifying the parent checkpoint
tasks Task information, including errors and interrupts

The most important distinction is between values and next. The former tells you what has been saved; the latter tells you what remains scheduled.

See the official checkpointer documentation for the complete snapshot interface.

Preparing the environment

Install the packages used throughout this lesson.

Terminal
pip install "langgraph>=1,<2" "langchain>=1,<2"
pip install langgraph-checkpoint-sqlite
pip install langchain-openai

The first three Python examples use deterministic nodes and require no model API credentials. The SQLite chatbot example uses an OpenAI model and requires a valid OPENAI_API_KEY.

The APIs have been checked against official LangGraph documentation. The examples include expected outputs and verification assertions, but have not been executed in this authoring environment because the required packages are unavailable here.

Example: Inspecting a historical workflow

This example builds a pricing workflow and locates the checkpoint immediately before tax calculation.

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

class OrderState(TypedDict):
    quantity: int
    unit_price: int
    subtotal: int
    tax: float
    total: float

def calculate_subtotal(state: OrderState):
    return {
        "subtotal": state["quantity"] * state["unit_price"]
    }

def calculate_tax(state: OrderState):
    return {"tax": state["subtotal"] * 0.10}

def calculate_total(state: OrderState):
    return {"total": state["subtotal"] + state["tax"]}

builder = StateGraph(OrderState)

builder.add_node("subtotal", calculate_subtotal)
builder.add_node("tax", calculate_tax)
builder.add_node("total", calculate_total)

builder.add_edge(START, "subtotal")
builder.add_edge("subtotal", "tax")
builder.add_edge("tax", "total")
builder.add_edge("total", END)

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

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

result = graph.invoke(
    {"quantity": 3, "unit_price": 1000},
    config
)

print("Final total:", result["total"])

history = list(graph.get_state_history(config))

for snapshot in history:
    print(
        "Step:", snapshot.metadata.get("step"),
        "Next:", snapshot.next,
        "Values:", snapshot.values
    )

target = next(
    snapshot for snapshot in history
    if snapshot.next == ("tax",)
)

print("\nSelected checkpoint:", target.values)

print(
    "Checkpoint ID:",
    target.config["configurable"]["checkpoint_id"]
)

assert target.values["subtotal"] == 3000

Expected output, simplified:

Text
Final total: 3300.0

Step: 3 Next: ()
Step: 2 Next: ('total',)
Step: 1 Next: ('tax',)
Step: 0 Next: ('subtotal',)
Step: -1 Next: ('__start__',)

Selected checkpoint:
{'quantity': 3, 'unit_price': 1000, 'subtotal': 3000}

The selected checkpoint contains the calculated subtotal, but tax calculation has not yet executed at that boundary.

Its configuration can now be used to inspect or replay that specific execution point.

Selecting checkpoints reliably

Avoid hardcoding positions such as history[2]. Adding a graph node, introducing a loop, or creating another branch can change the history ordering.

Instead, select checkpoints using meaningful criteria:

  • The next scheduled node.
  • A particular state value.
  • A user message ID.
  • A checkpoint ID saved by your application.
  • A combination of execution metadata and business identifiers.

In looping graphs, the same node may appear as the next scheduled node at multiple checkpoints. Combine node-based filtering with business-specific state conditions to distinguish iterations.

For long-running applications, also avoid loading unbounded history into memory. Use the history API’s limit and pagination capabilities to retrieve manageable batches.

Replay

Replay allows you to execute the remainder of a workflow from an earlier checkpoint.

The essential syntax is:

Python
result = graph.invoke(None, historical_snapshot.config)

The first argument is None because you are continuing saved execution rather than submitting a new application input.

LangGraph reconstructs the selected checkpoint and schedules its remaining work. Earlier results are reused, while downstream nodes can execute again.

Replay is not equivalent to watching a recording. It is a new execution beginning from preserved state.

Example: Replaying an expensive workflow

This example uses execution counters to demonstrate exactly which nodes run again.

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

class State(TypedDict):
    product: str
    price: int
    quotation: str

calls = {"retrieve": 0, "quote": 0}

def retrieve_product(state: State):
    calls["retrieve"] += 1
    print("Retrieving product information")
    return {"price": 25000}

def generate_quote(state: State):
    calls["quote"] += 1

    return {
        "quotation": (
            f"{state['product']} costs {state['price']}."
        )
    }

graph = (
    StateGraph(State)
    .add_node("retrieve", retrieve_product)
    .add_node("quote", generate_quote)
    .add_edge(START, "retrieve")
    .add_edge("retrieve", "quote")
    .add_edge("quote", END)
    .compile(checkpointer=InMemorySaver())
)

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

original = graph.invoke({"product": "Laptop"}, config)

print("Original:", original["quotation"])
print("Calls:", calls)

target = next(
    snapshot for snapshot in graph.get_state_history(config)
    if snapshot.next == ("quote",)
)

replayed = graph.invoke(None, target.config)

print("Replayed:", replayed["quotation"])
print("Calls:", calls)

assert calls == {"retrieve": 1, "quote": 2}

Expected output:

Text
Retrieving product information
Original: Laptop costs 25000.
Calls: {'retrieve': 1, 'quote': 1}
Replayed: Laptop costs 25000.
Calls: {'retrieve': 1, 'quote': 2}

Notice that product retrieval executes only once, while quotation generation executes twice.

The execution counters live outside graph state. They deliberately demonstrate actual node execution rather than checkpointed application values.

Replay versus other execution operations

These APIs serve different purposes.

Operation API Behavior
Inspect historical state get_state(snapshot.config) Reads state without execution
Continue a conversation invoke(new_input, config) Processes new input using existing thread state
Resume unfinished execution invoke(None, config) Continues pending work from the latest checkpoint
Replay historical execution invoke(None, snapshot.config) Executes remaining work from a selected checkpoint
Resume an interrupt invoke(Command(resume=value), config) Supplies a response to a paused workflow
Fork historical execution update_state() followed by invoke() Creates and executes an alternative branch

Replaying a completed checkpoint whose next tuple is empty does not restart the graph. Choose an earlier checkpoint if you want a particular node to execute again.

Is replay deterministic?

Not necessarily.

A replayed language model might generate different text. A database query could return updated records. An API might return a different response.

You should distinguish between reproducing historical state and reproducing historical execution results.

For stronger reproducibility, persist important retrieved data, tool outputs, model identifiers, prompt versions, and business-rule versions. When necessary, replace external dependencies with recorded fixtures.

Explicit node caching can also affect whether a downstream node performs fresh computation. Disable or appropriately version caches when investigating execution behavior.

Fork

Replay answers the question: what happens if we execute this workflow again from here?

Forking answers a more powerful question: what happens if we change something at this historical point and execute an alternative path?

A fork allows you to preserve the original execution while exploring modified state.

The basic sequence is:

Python
fork_config = graph.update_state(
    historical_snapshot.config,
    {"field": "alternative value"},
    as_node="previous_node"
)

result = graph.invoke(None, fork_config)

Calling update_state() creates a new checkpoint. It does not rewrite the selected historical checkpoint.

Always use the configuration returned by update_state() when executing the fork.

The following diagram illustrates two alternative execution paths sharing an earlier checkpoint.

Fork diagram: START to Classify request; Classify request to Shared checkpoint; Shared checkpoint to Standard response (original); Shared checkpoint to Fork checkpoint (modify state); Fork checkpoint to Priority response; Standard response to END; Priority response to END.

Example: Exploring alternative support decisions

Suppose a customer-support workflow incorrectly assigns standard priority to an urgent complaint.

This example forks the workflow and compares alternative routing decisions.

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

class TicketState(TypedDict):
    complaint: str
    priority: str
    response: str

def classify(state: TicketState):
    return {"priority": "standard"}

def route(state: TicketState):
    return state["priority"]

def standard_response(state: TicketState):
    return {"response": "Response within 48 hours."}

def urgent_response(state: TicketState):
    return {"response": "Escalated for immediate review."}

builder = StateGraph(TicketState)

builder.add_node("classify", classify)
builder.add_node("standard", standard_response)
builder.add_node("urgent", urgent_response)

builder.add_edge(START, "classify")

builder.add_conditional_edges(
    "classify",
    route,
    {
        "standard": "standard",
        "urgent": "urgent"
    }
)

builder.add_edge("standard", END)
builder.add_edge("urgent", END)

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

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

original = graph.invoke(
    {"complaint": "My account has been compromised."},
    config
)

original_checkpoint = graph.get_state(config)

target = next(
    snapshot for snapshot in graph.get_state_history(config)
    if snapshot.next == ("standard",)
)

fork_config = graph.update_state(
    target.config,
    {"priority": "urgent"},
    as_node="classify"
)

fork_snapshot = graph.get_state(fork_config)

print("Fork next:", fork_snapshot.next)

alternative = graph.invoke(None, fork_config)

restored = graph.get_state(original_checkpoint.config)

print("Original:", restored.values["response"])
print("Alternative:", alternative["response"])

assert fork_snapshot.next == ("urgent",)
assert restored.values["priority"] == "standard"
assert alternative["priority"] == "urgent"

Expected output:

Text
Fork next: ('urgent',)
Original: Response within 48 hours.
Alternative: Escalated for immediate review.

The original classification remains accessible through its checkpoint configuration. The fork applies a different classification and follows the corresponding conditional edge.

Understanding as_node

The as_node argument specifies which node should be treated as the producer of a state update.

In the previous example:

Python
as_node="classify"

This tells LangGraph to treat the corrected priority as though the classification node produced it. The classification function itself is not called again by update_state().

Its outgoing routing logic determines the next execution path.

LangGraph can often infer the appropriate node automatically. Explicit attribution is particularly useful when parallel execution makes the previous writer ambiguous or when intentionally bypassing a node.

Incorrect attribution may skip required validation or schedule unexpected work. Inspect graph.get_state(fork_config).next before executing sensitive branches.

Forking and reducers

State updates pass through the reducers defined by your graph.

For ordinary scalar fields, updates generally replace existing values. An additive list reducer, however, combines existing and incoming values.

MessagesState uses the add_messages reducer, which supports replacing messages by ID.

To edit an existing user message, provide the revised message with the original message’s ID. Providing a different ID normally appends another message instead.

This distinction is essential when implementing chatbot editing.

Select a checkpoint before the assistant responded to the original message; otherwise, the revised conversation may retain an assistant response that no longer matches its question.

Branch identity and lineage

A fork normally remains within the original thread. It does not automatically receive a separate thread ID.

After several forks, chronological checkpoint history can contain states belonging to multiple execution paths.

Use parent_config to reconstruct the ancestry of a selected branch rather than assuming adjacent history entries belong to the same path.

For independent conversations with their own latest state, create separate threads and explicitly initialize them with the appropriate historical application data.

Debugging with time travel

Agent failures are often difficult to reproduce because agents combine model decisions, external tools, routing logic, and mutable data.

Time travel turns an investigation into a sequence of controlled experiments.

A practical debugging workflow is:

  1. Identify the affected thread and final checkpoint.
  2. Inspect historical snapshots to locate the first incorrect state.
  3. Examine the values immediately before the responsible node.
  4. Replay from that checkpoint to test reproducibility.
  5. Fork the checkpoint with corrected inputs or assumptions.
  6. Compare the original and alternative outcomes.
  7. Convert the discovered failure into a regression test.

For example, if a retrieval agent produces an unsupported answer, inspect the retrieved documents before answer generation. Replay the generation node to determine whether the failure persists. Fork the retrieval state with verified documents to isolate the quality of retrieval from the quality of generation.

LangSmith tracing complements this approach by providing visibility into individual node executions and model or tool calls.

Interrupts during replay

When time travel reaches a node containing interrupt(), the interrupt can be triggered again.

A previously supplied approval should not be assumed to authorize an alternative execution branch.

Resume the newly paused execution using Command(resume=...) and the configuration identifying that interrupted execution.

Operations appearing before an interrupt inside the same node can run again when the node restarts.

External side effects

Replaying a node that sends an email, creates a ticket, or initiates a payment can repeat the external operation.

Checkpointing does not provide a distributed transaction spanning LangGraph and external services.

Protect production systems by using stable business-operation idempotency keys, sandbox dependencies, explicit approval gates, and database uniqueness constraints.

Tip: Separate read-only analysis from irreversible actions. Place external writes in dedicated nodes and implement a read-only debugging mode so historical execution cannot accidentally repeat production operations.

Choosing checkpoint durability

Time travel depends on checkpoints actually being available.

  • durability="sync" persists each checkpoint before execution proceeds.
  • durability="async" overlaps checkpoint persistence with subsequent work.
  • durability="exit" saves state when execution exits rather than preserving every intermediate boundary.

Use synchronous durability when reliable intermediate recovery points are particularly important.

For parallel graphs, successful task writes can support recovery from a partially failed super-step. This recovery mechanism differs from intentionally replaying an earlier completed execution.

Product features built on it

Time travel is not exclusively a developer debugging feature. It can become a fundamental capability exposed to application users.

Conversational products commonly implement:

Product feature Implementation approach
Restore conversation Read a saved thread’s state
View conversation history Retrieve historical snapshots
Regenerate response Replay from before assistant generation
Edit previous message Fork a checkpoint and replace a message by ID
Duplicate conversation Initialize a new thread with selected historical messages
Explore alternative decisions Fork state and execute alternative routing
Resume interrupted workflow Continue the appropriate paused execution

These features share the same persistence infrastructure but require different execution semantics.

Building a chatbot that restores previous conversations

For the chapter project, use SQLite to preserve messages beyond the lifetime of a Python process.

The following complete application supports reopening an existing conversation, listing saved assistant-response checkpoints, regenerating a response, and continuing the conversation.

Save it as chatbot.py.

Python
from uuid import uuid4

from langchain.chat_models import init_chat_model
from langchain.messages import HumanMessage, AIMessage
from langgraph.graph import (
    StateGraph,
    MessagesState,
    START,
    END
)
from langgraph.checkpoint.sqlite import SqliteSaver

model = init_chat_model("openai:gpt-5.4-mini")

def chatbot(state: MessagesState):
    response = model.invoke(state["messages"])
    return {"messages": [response]}

builder = StateGraph(MessagesState)
builder.add_node("chatbot", chatbot)
builder.add_edge(START, "chatbot")
builder.add_edge("chatbot", END)

def display(messages):
    for message in messages:
        print(f"{message.type}: {message.content}")

with SqliteSaver.from_conn_string("conversations.db") as saver:
    graph = builder.compile(checkpointer=saver)

    thread_id = input("Conversation ID: ").strip()

    if not thread_id:
        thread_id = str(uuid4())

    config = {
        "configurable": {"thread_id": thread_id}
    }

    print("Conversation ID:", thread_id)

    restored = graph.get_state(config)

    print("\nRestored conversation:")
    display(restored.values.get("messages", []))

    print("\nCommands: /history, /regenerate, /exit")

    while True:
        text = input("\nYou: ").strip()

        if text == "/exit":
            break

        if text == "/history":
            for snapshot in graph.get_state_history(config):
                messages = snapshot.values.get("messages", [])

                if not snapshot.next and messages:
                    if isinstance(messages[-1], AIMessage):
                        checkpoint_id = snapshot.config[
                            "configurable"
                        ]["checkpoint_id"]

                        print(
                            checkpoint_id,
                            str(messages[-1].content)[:80]
                        )
            continue

        if text == "/regenerate":
            latest = graph.get_state(config)
            messages = latest.values.get("messages", [])

            if not messages or not isinstance(
                messages[-1], AIMessage
            ):
                print("No completed response to regenerate.")
                continue

            # Walk the active branch's ancestry.
            target = latest

            while target.parent_config:
                target = graph.get_state(target.parent_config)

                if target.next == ("chatbot",):
                    break

            if target.next != ("chatbot",):
                print("No generation checkpoint found.")
                continue

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

            print("Assistant:", result["messages"][-1].content)
            continue

        if not text:
            continue

        result = graph.invoke(
            {"messages": [HumanMessage(content=text)]},
            config,
            durability="sync"
        )

        print("Assistant:", result["messages"][-1].content)

Set your OpenAI API key in your environment and start the application.

Terminal
python chatbot.py

Example interaction:

Text
Conversation ID: python-learning

Restored conversation:

You: My name is Maya.
Assistant: Nice to meet you, Maya!

You: /exit

Restart the application and enter the same conversation ID.

Text
Conversation ID: python-learning

Restored conversation:
human: My name is Maya.
ai: Nice to meet you, Maya!

You: What is my name?
Assistant: Your name is Maya.

Actual model responses will vary.

The /regenerate command walks the latest branch’s ancestry until it finds the checkpoint preceding assistant generation. It then replays generation without adding another human message.

Earlier responses remain available through their historical checkpoints.

The SQLite database preserves the conversation even after the Python application terminates.

Production design considerations

This chatbot is a single-user educational implementation. A production version needs additional application-level controls.

Associate every thread with an authenticated user and validate ownership before exposing any checkpoint. Treat checkpoint identifiers as references, not authorization credentials.

Maintain an application-level conversation catalog containing conversation titles, ownership, selected branch heads, and update timestamps.

Serialize conflicting writes to the same conversation or implement concurrency controls. Otherwise, simultaneous requests can create competing branches.

Use PostgreSQL for multi-user production deployments, define checkpoint-retention policies, and protect sensitive historical data. Editing or removing a message from the latest state does not necessarily remove it from earlier checkpoints.

Version graph schemas, prompts, and business rules so older checkpoints remain compatible with subsequent deployments.

For the official execution semantics and additional subgraph examples, consult LangGraph’s time-travel guide.

Connection to the next lesson

The conversation-restoration project demonstrates thread-scoped persistence: a chatbot remembers information because earlier messages are included in its saved graph state.

However, retaining conversation history does not automatically give an agent knowledge across independent threads.

Suppose the same user starts a new conversation. How should the agent remember their preferences, previous projects, or important facts without copying every historical message?

That introduces the distinction between short-term memory, represented by thread-scoped graph state, and long-term memory, represented by information stored independently of individual conversations.

In the next lesson, Short-term and long-term memory, you will extend the persistence architecture with LangGraph stores and explore how agents can retain and retrieve useful information across conversations.

Exercise

Build a Time-Travel Chatbot

Build a checkpoint-enabled chatbot that remembers conversations across multiple turns and allows users to restore historical conversation states. Implement checkpoint selection, response regeneration through replay, and message editing through forking. Verify that the original conversation remains accessible after creating an alternative branch.

Python
# Install: pip install "langgraph>=1,<2" "langchain>=1,<2"

from uuid import uuid4
from langchain.messages import HumanMessage, AIMessage
from langgraph.graph import StateGraph, MessagesState, START, END
from langgraph.checkpoint.memory import InMemorySaver


def chatbot(state: MessagesState):
    # A deterministic chatbot for testing without API credentials.
    human_messages = [
        m for m in state["messages"]
        if isinstance(m, HumanMessage)
    ]

    return {
        "messages": [
            AIMessage(
                content=f"Reply to: {human_messages[-1].content}"
            )
        ]
    }


builder = StateGraph(MessagesState)
builder.add_node("chatbot", chatbot)
builder.add_edge(START, "chatbot")
builder.add_edge("chatbot", END)

# TODO: Compile with a checkpointer.

config = {
    "configurable": {"thread_id": str(uuid4())}
}

# TODO: Submit two user messages in separate invocations.
# TODO: Save the original completed checkpoint.
# TODO: Retrieve the checkpoint history.
# TODO: Find the checkpoint before the second assistant reply.
# TODO: Replay the chatbot from that checkpoint.
# TODO: Edit the second user message using its existing message ID.
# TODO: Fork the checkpoint and execute the alternative branch.
# TODO: Verify that the original conversation remains accessible.

Summary

  • Time travel restores graph execution from previously persisted checkpoint boundaries.
  • Checkpoint history exposes historical state values, execution metadata, pending nodes, and parent relationships.
  • Replay executes downstream nodes again using the state captured at a selected checkpoint.
  • Forking creates an alternative execution branch by updating historical state without deleting the original checkpoint.
  • The as_node argument determines which node receives credit for a state update and influences subsequent execution.
  • Replaying external operations requires careful management of side effects, idempotency, and nondeterministic results.
  • Persistent checkpointers enable applications to restore conversations across process restarts and support regeneration, editing, and branching.