State Persistence

Query checkpoints, replay history, update state, recover from failures, and persist state with PostgreSQL.

🎯 Introduction

If generation succeeds but review fails because of an API error, restarting the whole task can waste the generated content. A checkpointer records workflow execution state so applications can inspect history, resume unfinished tasks, and run again from a selected state. This article covers these capabilities and uses PostgreSQL to verify that state remains available after the program exits.


🧱 Workflow Checkpoints

In the LangChain course, we used a checkpointer to save conversation messages. LangGraph checkpoints can also record custom state such as drafts and review results, along with the next nodes to execute.

Consider two sequential nodes for generation and review:

Enter topic
topic: LangGraph
Checkpoint
Draft complete
draft saved · next: review
Can resume
Review complete
review saved · next: []
Checkpoint
Replay from the completed draft checkpoint to rerun only the review.
A single task can save multiple state snapshots. Internal framework checkpoints are omitted.

LangGraph saves checkpoints at execution step (super-step) boundaries. In sequential execution, one node typically corresponds to one step; in parallel execution, a step may contain multiple nodes. It does not save state after every line of code.

A thread_id identifies a workflow state history. Here it represents an article task, rather than a user identity. One task may have multiple historical snapshots, each with its own checkpoint_id.


🛠 Create a Workflow with Checkpoints

Create article-graph.mjs and wrap the workflow in a factory function so we can change storage later. Start by defining state:

import { StateGraph, StateSchema, START, END } from '@langchain/langgraph';
import { z } from 'zod';

const ArticleState = new StateSchema({
    topic: z.string(),
    draft: z.string().default(''),
    review: z.string().default(''),
});

Add generation and review nodes:

function writeArticle(state) {
    console.log('Running writing node');
    return { draft: `${state.topic} can organize tasks.` };
}

function reviewArticle(state) {
    console.log('Running review node');

    if (!state.draft.includes('For example')) {
        return { review: 'Missing an example' };
    }

    return { review: 'Review passed' };
}

Continue with:

export function createArticleGraph(checkpointer) {
    return new StateGraph(ArticleState)
        .addNode('write', writeArticle)
        .addNode('review', reviewArticle)
        .addEdge(START, 'write')
        .addEdge('write', 'review')
        .addEdge('review', END)
        .compile({ checkpointer });
}

Here, state saving is enabled through compile({ checkpointer }), rather than by passing a storage object separately to invoke().

Create 07.persistence.mjs:

import { MemorySaver } from '@langchain/langgraph';
import { createArticleGraph } from './article-graph.mjs';

const graph = createArticleGraph(new MemorySaver());
const config = {
    configurable: { thread_id: 'article-001' },
};

await graph.invoke({ topic: 'LangGraph' }, config);

const snapshot = await graph.getState(config);
console.log('Current status:', snapshot.values);
console.log('Pending nodes:', snapshot.next);

Run:

node 07.persistence.mjs

Expected output:

Running writing node
Running review node
Current status: { topic: 'LangGraph', draft: 'LangGraph can organize tasks.', review: 'Missing an example' }
Pending nodes: []

getState() reads the task's latest checkpoint without rerunning nodes. The returned StateSnapshot has several useful fields:

FieldPurpose
valuesState data stored in the checkpoint
nextNames of nodes waiting to execute
configConfiguration containing the thread ID and checkpoint ID

An empty next means no nodes remain to execute. It does not mean the article passed review; check the business state in review as well.


🧱 Query History and Replay Execution

If the final review seems wrong, inspect the checkpoint after generation to determine whether the problem arose during writing or review. Append all history and replay code below to 07.persistence.mjs. Each full script run creates a new in-memory checkpointer.

Append to 07.persistence.mjs:

const history = [];

for await (const item of graph.getStateHistory(config)) {
    history.push(item);
}

// Find the checkpoint after generation and before review
const beforeReview = history.find(item => item.next.includes('review'));

if (!beforeReview) {
    throw new Error('No checkpoint found before review');
}

console.log('Draft before review:', beforeReview.values.draft);
console.log('Pending nodes:', beforeReview.next);

Run it again to see these additional lines at the end:

Draft before review: LangGraph can organize tasks.
Pending nodes: [ 'review' ]

getStateHistory() returns asynchronously iterable snapshots, generally from newest to oldest. We locate a checkpoint by its pending nodes instead of relying on a fixed array index.

Replay from a Historical Checkpoint

Append the following:

const replay = await graph.invoke(null, beforeReview.config);
console.log('Replay result:', replay.review);

Run it again to see these additional lines at the end:

Running review node
Replay result: Missing an example

Pass the historical snapshot's config, which already contains a specific checkpoint_id. invoke(null, ...) continues from that checkpoint without submitting new task input. The writing node is not rerun, but the review node is.

Update Historical State and Run Again

To test another draft, create a new checkpoint based on historical state. Continue with:

const forkConfig = await graph.updateState(beforeReview.config, {
    draft: 'For example: orchestrate generation and review with LangGraph.',
});

const fork = await graph.invoke(null, forkConfig);
console.log('Review after update:', fork.review);

Run it again to see these additional lines at the end:

Running review node
Review after update: Review passed

updateState() creates a new state record based on the historical checkpoint and returns its configuration; it does not overwrite the original checkpoint. Here the checkpoint follows write, so the framework can infer that the update comes from write and run review next. If multiple sources are possible, specify asNode explicitly. The original checkpoint remains accessible through its original configuration; use forkConfig for the new one.

Running again from an earlier checkpoint is called time travel. It helps with debugging and trying different inputs, but does not automatically undo external operations that already occurred.


🧱 Resume a Failed Task

Checkpoints also support recovery from failures. Create 07.recovery.mjs:

import { StateGraph, StateSchema, MemorySaver, START, END } from '@langchain/langgraph';
import { z } from 'zod';

const State = new StateSchema({
    draft: z.string().default(''),
    review: z.string().default(''),
});

let unavailable = true;

function write() {
    console.log('Generating draft');
    return { draft: 'LangGraph article draft' };
}

function review() {
    console.log('Requesting review service');

    if (unavailable) {
        throw new Error('Review service unavailable');
    }

    return { review: 'Review complete' };
}

Continue with:

const graph = new StateGraph(State)
    .addNode('write', write)
    .addNode('review', review)
    .addEdge(START, 'write')
    .addEdge('write', 'review')
    .addEdge('review', END)
    .compile({ checkpointer: new MemorySaver() });

const config = {
    configurable: { thread_id: 'article-recovery' },
};

try {
    await graph.invoke({}, config);
} catch (error) {
    console.log('Task failed:', error.message);
}

Running only the code so far should print Generating draft, Requesting review service, and Task failed: Review service unavailable, in that order.

Append code to simulate service recovery and resume the task:

unavailable = false;

const result = await graph.invoke(null, config);
console.log('Review after recovery:', result.review);

Run:

node 07.recovery.mjs

Expected application logs:

Generating draft
Requesting review service
Task failed: Review service unavailable
Requesting review service
Review after recovery: Review complete

The first run failed, but its generated draft was saved. Resuming with the same task ID does not require resubmitting the topic or starting from the beginning.

Retries, recovery, and replay can execute nodes again. For external writes such as publication, the application must prevent duplicates using unique task IDs, idempotency keys, or database constraints. A checkpointer alone is insufficient.

🛠 Persist State with PostgreSQL

MemorySaver retains records only within the current process. Reading state after a restart requires a persistent checkpointer. We use PostgreSQL because LangGraph.js provides PostgresSaver, avoiding a custom checkpoint storage implementation. MySQL can store this data too.

Prepare the Database

If PostgreSQL is already running, create a dedicated database. This example uses PostgreSQL 17 in Docker (install Docker first):

docker run -d --name langgraph-postgres -e POSTGRES_PASSWORD=local_demo_password -e POSTGRES_DB=langgraph -p 127.0.0.1:5432:5432 -v langgraph-pgdata:/var/lib/postgresql/data postgres:17

Check whether the database is ready:

docker exec langgraph-postgres pg_isready -U postgres -d langgraph

The output should include:

/var/run/postgresql:5432 - accepting connections

If startup is still in progress, check again shortly. If local port 5432 is occupied, use another host port and update the connection URL below. This password is for local teaching only; use a dedicated database account and secure credentials in production. Docker CLI output may vary by version and environment.

This section uses Node.js 24 LTS. Install version 1.0.6 of the PostgreSQL checkpointer dependency:

npm install --save-exact @langchain/langgraph-checkpoint-postgres@1.0.6

Create or update .env in the project root, preserving any existing fields:

DATABASE_URL=postgresql://postgres:local_demo_password@127.0.0.1:5432/langgraph

Do not commit .env to a public repository.

First Run: Write Workflow State

Create 07.postgres-write.mjs:

import { PostgresSaver } from '@langchain/langgraph-checkpoint-postgres';
import { createArticleGraph } from './article-graph.mjs';

const checkpointer = PostgresSaver.fromConnString(process.env.DATABASE_URL);

try {
    // Initialize the database tables used for checkpoints
    await checkpointer.setup();

    const graph = createArticleGraph(checkpointer);
    const config = {
        configurable: { thread_id: 'article-pg-001' },
    };

    const result = await graph.invoke({ topic: 'LangGraph' }, config);
    console.log('Completed review:', result.review);
} finally {
    await checkpointer.end();
}

Run:

node --env-file=.env 07.postgres-write.mjs

Expected application logs:

Running writing node
Running review node
Completed review: Missing an example

setup() initializes or migrates checkpoint tables. end() releases database connections so the script can exit normally. The framework manages the checkpoint schema; you do not need to write SQL to save state.

Second Run: Read State from the Database

Create 07.postgres-read.mjs:

import { PostgresSaver } from '@langchain/langgraph-checkpoint-postgres';
import { createArticleGraph } from './article-graph.mjs';

const checkpointer = PostgresSaver.fromConnString(process.env.DATABASE_URL);

try {
    await checkpointer.setup();

    const graph = createArticleGraph(checkpointer);
    const config = {
        configurable: { thread_id: 'article-pg-001' },
    };

    const snapshot = await graph.getState(config);
    console.log('State in database:', snapshot.values);
} finally {
    await checkpointer.end();
}

Confirm that the first script has exited, then run:

node --env-file=.env 07.postgres-read.mjs

Expected output:

State in database: { topic: 'LangGraph', draft: 'LangGraph can organize tasks.', review: 'Missing an example' }

These scripts run in separate Node.js processes, and the second never calls graph.invoke(). Reading the first script's result therefore demonstrates that state was saved in the database. Real applications should assign unique task IDs and verify access before querying or resuming. The example uses a fixed ID so both scripts access the same task; change it when testing a new task.

References: Checkpointers, Use time travel, PostgresSaver.


❓ Questions and Answers

Q1: Does saving a workflow in a database guarantee nodes will never execute twice?

No. Persistence retains successfully recorded execution state, but nodes that had not finished before a failure or interrupt may run again. External writes still need idempotency.


🧪 Exercise

Change topic and the task ID in 07.postgres-write.mjs to save another article. Run the read script with each ID and confirm that both drafts can be read independently without running the writing node.


🎉 Congratulations! You can now save, query, replay, and resume workflow state.