Skip to content

Why Open Postgres Checkpointer & How It Works

Open Postgres Checkpointer is a drop-in BaseCheckpointSaver for LangGraph on PostgreSQL. It runs directly on the four tables created by upstream's langgraph-checkpoint-postgres, adopts existing databases without migrating data, and replaces full-value rewriting, global locking, and missing lifecycle primitives with flat zstd-prefix patch storage, lock-free pooled execution, optimistic concurrency fencing, and production-grade retention.

This guide explains:

  1. What problems this solves — the specific weaknesses in upstream's langgraph-checkpoint-postgres and how this saver fixes each one.
  2. How the upstream saver works — the tables, write lifecycle inside a single run, and why multi-turn threads grow quadratically.
  3. How Open Postgres Checkpointer works — the schema extensions, flat patch model, end-to-end read/write flow, and how every upstream failure mode is closed.
  4. Inside the main optimizations — the codec, cache, SQL, concurrency, and indexing engineering behind the numbers.

1. Problems solved: where upstream's saver falls short

Upstream's langgraph-checkpoint-postgres (3.2.0) is clean and easy to start with, but running long-lived, multi-turn, or high-concurrency LangGraph agents on it exposes nine concrete weaknesses.

Upstream weakness (langgraph-checkpoint-postgres 3.2.0) Production impact How Open Postgres Checkpointer solves it
1. O(N²) disk & WAL amplification on plain channels — every step rewrites every changed channel blob in full. A 5,000-step conversation takes 1.79 GB on disk; a 10 MB agent thread rewrites 10 MB on every step. Stores changed blobs ≥ 1 KiB as flat zstd-prefix patches against an earlier full copy, with automatic rebasing. Cuts plain-graph disk 4.0×–12.5× with zero graph changes.
2. DeltaChannel is opt-in, changes semantics, and cannot be pruned — aprune(keep_latest) raises NotImplementedError on any DeltaChannel thread. Rewriting graphs per channel is invasive; _messages_delta_reducer drops REMOVE_ALL_MESSAGES; old history can never be pruned without deleting the whole thread. Works automatically on plain graphs and supports DeltaChannel threads fully: patches their snapshots (0.65× disk at 5,000 steps), compresses writes, and prunes them safely by preserving snapshot ancestor chains.
3. One saver-wide asyncio.Lock serializes all traffic — _cursor() holds a single lock even on an AsyncConnectionPool. Concurrency collapses to 1 DB operation at a time per saver; one 50 MB put stalls tiny threads behind it (2,968 ms p95 vs. 764 ms with ours). Completely lock-free across threads and coroutines, using one pooled autocommit connection per call (1.5×–1.7× higher turns/s at 8–32 concurrent threads; 2.0×–2.3× faster on 100-thread bursts).
4. Multi-statement, non-atomic writes — aput issues executemany for blobs then a separate checkpoint INSERT; AsyncPipeline is forbidden on pools. Extra network round trips per step, partial-write windows on failure, and hex-escaped bytea overhead. Fuses fence check, blob inserts, patch side rows, checkpoint upsert, and head update into one atomic SQL statement using binary bytea[] arrays (unnest). Same for aput_writes.
5. Redundant blob reads in alist — SELECT_SQL aggregates checkpoint_blobs inside a correlated subquery per checkpoint row. An unchanged 1 MB channel referenced by 50 checkpoints is transferred and deserialized 50 times. Deduplicates (thread_id, checkpoint_ns, channel, version) across each 100-row page in SQL (SELECT DISTINCT) and decodes shared values once per page.
6. No concurrent-run protection (silent thread forks) — two overlapping ainvoke calls on one thread_id both commit and interleave. Double-clicks, webhook retries, or worker timeouts silently fork and corrupt conversation history. Built-in optimistic second-writer fence (opc_thread_head + __opc_head token) checked inside PUT_SQL. The losing run writes nothing and raises ThreadConflictError.
7. Missing operational & lifecycle primitives — no thinning (keep_last), no delete_for_runs, no idle-thread expiry, no copy_thread, no thread listing, no concurrency-safe setup(). Teams build fragile ad-hoc SQL jobs that race live runs or accidentally break DeltaChannel replay. Ships aprune(..., keep_last=N), adelete_for_runs, asweep_expired, acopy_thread, alist_threads (with partial index), and advisory-locked setup().
8. Event-loop blocking & thread-pool allocator bloat — _load_blobs runs synchronously on the event loop; writes fan out over Python's default thread pool. Deserializing large channels stalls all async tasks; multi-thread allocations fragment glibc arenas. Runs all serde, zstd compression, patching, and decoding on one dedicated codec thread per saver (opc-codec).
9. Uncompressed pending writes — task outputs in checkpoint_writes are stored raw. Fan-out workflows (e.g., 50 Send workers) spend 69–74% of total disk on uncompressed writes. Compresses pending writes ≥ 256 B with zstd (opc:zstd:) when smaller, cutting fan-out write storage by up to 22%.

Headline benchmark results

Measured before release on an uncontended benchmark host (PostgreSQL 16, 8 pool connections per arm; disk is bytes above each arm's empty schema after VACUUM, including all opc_* side tables and indexes; full results in core-set-results.md):

Workload Disk vs. upstream Latency / throughput vs. upstream
400-step chat (plain graph) 6.9× smaller put p50 0.41× (2.4× faster)
5,000-step thread (plain graph) 10.1× smaller (177 MB vs. 1,792 MB) put p95 0.53× (36.9 ms vs. 69.9 ms)
5,000-step thread (DeltaChannel) 0.65× (28.5 MB vs. 43.5 MB) put p50 0.54× (1.60 ms vs. 2.99 ms)
Agent thread growing to 1 / 3 / 10 MB (plain) 4.0× / 5.7× / 12.5× smaller put p50 0.43× / 0.34× / 0.15×
8 / 32 concurrent threads on one saver (plain) — put p50 0.53× / 0.47×; 1.7× / 1.6× turns/s
100 concurrent mice + 50 MB elephant (plain) 2.1× smaller (43.9 MB vs. 92.2 MB) Mouse step p95 764 ms vs. 2,968 ms (3.9× lower)
Deep DeltaChannel fork read 0.45×–1.01× Fork head read 6–7× faster
Supervisor + 50 Send workers (plain / DeltaChannel) 0.50× / 0.77× (with compressed writes) Plain put p50 25.2 ms vs. 143.8 ms (5.7× faster)

Honest trade-off: On a DeltaChannel graph with a brand-new connection pool, our larger PUT_SQL statement pays ~1–1.5 ms more Postgres planning time on the first few puts; on a long-lived warm pool (how production workers run), DeltaChannel put p50 is 0.72–1.16× upstream's (put-planning-cold-pools.md). Also, once patches are enabled, upstream's saver cannot read patched threads — see Adopting the saver for zero-downtime rolling deploys and Rolling back for online rollback via rehydrate.


2. How the upstream saver works

To understand why checkpoints grow so fast and where concurrency bottlenecks come from, it helps to see exactly what langgraph-checkpoint-postgres stores at each step.

2.1 The four upstream tables

Upstream's setup() creates four tables:

  1. checkpoint_migrations — tracks applied schema migration versions (0 through 9 in langgraph-checkpoint-postgres 3.2.0).
  2. checkpoints — one row per checkpoint (thread_id, checkpoint_ns, checkpoint_id) with parent_checkpoint_id, checkpoint (JSONB), and metadata (JSONB).
  3. checkpoint -> 'channel_versions' maps every channel name to a monotonic version string (e.g., "00000000000000000000000000000004.0.7319...").
  4. checkpoint -> 'channel_values' stores primitive values inline (None, str, int, float, bool) and a literal true marker for _DeltaSnapshot blobs. Everything else (lists like messages, dicts, custom objects) is moved out to checkpoint_blobs.
  5. checkpoint_blobs — versioned binary storage keyed by (thread_id, checkpoint_ns, channel, version) -> (type, blob).
  6. Unchanged channels are deduplicated by version: if channel config_doc didn't change at step 3, checkpoint 3 simply keeps "config_doc": "v1" in channel_versions and writes no new blob row.
  7. Changed channels are rewritten in full: whenever a channel changes (even appending one 200-byte message to a 5 MB list), LangGraph assigns a new version string and upstream inserts a brand-new complete serialized copy into checkpoint_blobs.
  8. checkpoint_writes — task-level intermediate outputs keyed by (thread_id, checkpoint_ns, checkpoint_id, task_id, idx) -> (channel, type, blob, task_path). Written by aput_writes as each graph node finishes inside a superstep, before the next checkpoint is finalized, so crashed or interrupted runs can resume without re-executing completed nodes.
flowchart LR
    subgraph CP["checkpoints (one row per superstep)"]
        C1["cp_1 (step -1, input)
        parent: NULL
        channel_versions:
          messages -> v1
          profile -> v1
        inline: turn_count = 1"]
        C2["cp_2 (step 0, loop)
        parent: cp_1
        channel_versions:
          messages -> v2
          profile -> v1 (reused)
        inline: turn_count = 1"]
        C3["cp_3 (step 1, loop)
        parent: cp_2
        channel_versions:
          messages -> v3
          profile -> v1 (reused)
        inline: turn_count = 1"]
    end

    subgraph BL["checkpoint_blobs (non-primitive values)"]
        P1["profile @ v1
        (msgpack, full copy)"]
        M1["messages @ v1
        [U1] (full copy)"]
        M2["messages @ v2
        [U1, A1_call] (full copy)"]
        M3["messages @ v3
        [U1, A1_call, T1] (full copy)"]
    end

    subgraph WR["checkpoint_writes (intermediate task outputs)"]
        W1["cp_1 / task_llm / idx 0
        channel: messages, delta: A1_call"]
        W2["cp_2 / task_tool / idx 0
        channel: messages, delta: T1"]
    end

    C1 -->|"profile: v1"| P1
    C2 -->|"profile: v1"| P1
    C3 -->|"profile: v1"| P1

    C1 -->|"messages: v1"| M1
    C2 -->|"messages: v2"| M2
    C3 -->|"messages: v3"| M3

    C1 -.->|"writes during step 0"| W1
    C2 -.->|"writes during step 1"| W2

2.2 Inside one run (supersteps of a single user turn)

A single graph.ainvoke() executes in Pregel supersteps (for example: receive user input → LLM decides to call a tool → tool runs → LLM writes the final answer). Notice how multiple checkpoints are saved during one user turn, and notice that aput_writes runs asynchronously in the background (so a step's writes can land before or after its checkpoint row):

sequenceDiagram
    autonumber
    participant App as Application / LangGraph
    participant Saver as AsyncPostgresSaver (global asyncio.Lock)
    participant PG as PostgreSQL

    Note over App,PG: User Turn 1 starts: ainvoke({"messages": [U1]})
    App->>Saver: aget_tuple(thread_id)
    Saver->>PG: SELECT_SQL (latest checkpoint + all blobs + writes)
    PG-->>Saver: None (new thread)
    Saver-->>App: None

    Note over App,PG: Input checkpoint (step = -1, source = "input")
    App->>Saver: aput(cp_1, messages=[U1])
    Saver->>PG: executemany UPSERT checkpoint_blobs (messages v1: [U1])
    Saver->>PG: execute UPSERT checkpoints (cp_1, parent=NULL)

    Note over App,PG: Superstep 0: LLM node runs -> requests tool call A1_call
    App->>Saver: aput_writes(cp_1, task_1, [A1_call])
    Saver->>PG: executemany INSERT checkpoint_writes (cp_1, task_1)
    App->>Saver: aput(cp_2, parent=cp_1, messages=[U1, A1_call])
    Saver->>PG: executemany UPSERT checkpoint_blobs (messages v2: [U1, A1_call])
    Saver->>PG: execute UPSERT checkpoints (cp_2, parent=cp_1)

    Note over App,PG: Superstep 1: Tool node runs -> produces tool output T1
    App->>Saver: aput_writes(cp_2, task_2, [T1])
    Saver->>PG: executemany INSERT checkpoint_writes (cp_2, task_2)
    App->>Saver: aput(cp_3, parent=cp_2, messages=[U1, A1_call, T1])
    Saver->>PG: executemany UPSERT checkpoint_blobs (messages v3: [U1, A1_call, T1])
    Saver->>PG: execute UPSERT checkpoints (cp_3, parent=cp_2)

    Note over App,PG: Superstep 2: LLM node runs -> final answer A2
    App->>Saver: aput_writes(cp_3, task_3, [A2])
    Saver->>PG: executemany INSERT checkpoint_writes (cp_3, task_3)
    App->>Saver: aput(cp_4, parent=cp_3, messages=[U1, A1_call, T1, A2])
    Saver->>PG: executemany UPSERT checkpoint_blobs (messages v4: [U1, A1_call, T1, A2])
    Saver->>PG: execute UPSERT checkpoints (cp_4, parent=cp_3)

Even a single tool-using turn writes four checkpoints and four progressively larger full copies of messages, plus three checkpoint_writes batches — all serialized through the saver's single asyncio.Lock.

2.3 Across multiple user turns: the O(N²) triangle

When User Turn 2 arrives on the same thread_id, LangGraph calls aget_tuple to load cp_4, appends U2, and begins the next sequence of supersteps. Every step that mutates messages (or any growing list, artifact map, or agent scratchpad) writes the entire accumulated history again:

flowchart TD
    subgraph T1["User Turn 1 (4 checkpoints)"]
        B1["v1: [U1] — 1 msg"]
        B2["v2: [U1, A1_call] — 2 msgs"]
        B3["v3: [U1, A1_call, T1] — 3 msgs"]
        B4["v4: [U1, A1_call, T1, A2] — 4 msgs"]
    end

    subgraph T2["User Turn 2 (loads cp_4, adds 4 more checkpoints)"]
        B5["v5: [U1..A2, U2] — 5 msgs"]
        B6["v6: [U1..U2, A3_call] — 6 msgs"]
        B7["v7: [U1..A3_call, T2] — 7 msgs"]
        B8["v8: [U1..T2, A4] — 8 msgs"]
    end

    subgraph TN["User Turn K (step N)"]
        BN["vN: [U1 .. A_last] — N msgs rewritten AGAIN in full"]
    end

    T1 --> T2 --> TN

    Total["Total bytes written to checkpoint_blobs = 1 + 2 + 3 + ... + N = O(N²)"]
    TN --> Total

What about upstream's DeltaChannel? Upstream introduced an opt-in DeltaChannel that avoids writing a blob on every step: it records only deltas in checkpoint_writes, and writes a full _DeltaSnapshot blob every snapshot_frequency updates (default 100). On read, LangGraph asks the saver for aget_delta_channel_history (walking backwards to the nearest snapshot) and replays every write through the channel's reducer. That cuts disk on append-only lists, but:

  • You must change every channel in your graph (and it only fits reducer channels, not arbitrary mutated dicts or documents).
  • Its message reducer (_messages_delta_reducer) does not match add_messages (it silently ignores REMOVE_ALL_MESSAGES and unknown-ID removals).
  • Upstream cannot prune DeltaChannel threads (aprune(keep_latest) raises NotImplementedError).
  • Full snapshots themselves are still written whole, and reading deep history replays writes from scratch on the client.

3. How Open Postgres Checkpointer works

Open Postgres Checkpointer solves these problems at the storage and SQL layer without changing LangGraph's graph contract or upstream's table layout.

3.1 Minimal schema additions on top of upstream's tables

setup() runs upstream's exact migrations 0..9 into checkpoint_migrations (leaving an already migrated upstream database completely untouched), then applies its own migrations into a separate ledger, opc_migrations:

flowchart TB
    subgraph UP["Upstream tables (unchanged structure, tracked in checkpoint_migrations)"]
        CP["checkpoints
        PK: (thread_id, checkpoint_ns, checkpoint_id)
        + partial index opc_checkpoints_root_latest
          (checkpoint_id DESC, thread_id DESC) WHERE checkpoint_ns = ''"]
        CB["checkpoint_blobs
        PK: (thread_id, checkpoint_ns, channel, version)
        type: serde_type | opc:zstd:serde_type | opc:zstd-patch:serde_type"]
        CW["checkpoint_writes
        PK: (thread_id, checkpoint_ns, checkpoint_id, task_id, idx)
        type: serde_type | opc:zstd:serde_type"]
    end

    subgraph OPC["Our side tables (tracked in opc_migrations)"]
        BP["opc_blob_patch
        PK: (thread_id, checkpoint_ns, channel, version)
        base_version TEXT NOT NULL
        FK1: patch row -> checkpoint_blobs ON DELETE CASCADE
        FK2: base row -> checkpoint_blobs DEFERRABLE INITIALLY DEFERRED
        Index: opc_blob_patch_base"]
        TH["opc_thread_head (fillfactor = 70, no secondary indexes)
        PK: thread_id
        head_id TEXT | seq BIGINT (opc_head_seq) | touched_at TIMESTAMPTZ"]
        PO["opc_patching_off
        single-row switch set by rehydrate"]
    end

    BP -->|"FK1: CASCADE when patch deleted"| CB
    BP -->|"FK2: DEFERRED refuses deleting needed base"| CB
    TH -.->|"tracks root head, generation & idle time"| CP
    PO -.->|"gates PUT_SQL & PUT_WRITES_SQL"| CB

Every upstream table keeps its exact columns and primary keys. Existing rows written by langgraph-checkpoint-postgres are read in place with zero migration.

3.2 Flat three-tier blob storage (zero patch chains)

When aput serializes a changed blob value with the configured serde, _patch.encode() places it into one of three tiers based on its raw serialized byte length and compressibility:

Tier Condition checkpoint_blobs.type Side row in opc_blob_patch? Readable by upstream?
1. Plain < 256 B, incompressible (e.g. encrypted serde), or full_copies_only=True <serde_type> (unchanged) No Yes
2. Compressed full copy (base) 256 B – 1,023 B, or first copy / reset copy (patch > 25% of base's stored size, or base > 4× value size) opc:zstd:<serde_type> No No (raises loudly)
3. Flat patch ≥ 1,024 B, eligible base exists, and len(patch) <= 0.25 * base.stored_len opc:zstd-patch:<serde_type> Yes (base_version) No (raises loudly)

The critical invariant: a base is always a full copy, never another patch. There are no multi-hop patch chains. Whether a thread is at step 10 or step 5,000, reading any checkpoint applies at most one patch per channel.

Across multiple turns, here is what checkpoint_blobs stores instead of upstream's O(N²) triangle:

flowchart LR
    subgraph Bases["Full copies (bases, opc:zstd:msgpack)"]
        B1["v1: Base B0
        [U1..A2]
        (compressed full copy)"]
        B2["v9: New Base B1
        (auto-rebased when patch
        exceeds 25% of B0)"]
    end

    subgraph P0["Patches against B0 (opc:zstd-patch:msgpack)"]
        P1["v2: tiny patch (+A3_call)"]
        P2["v3: tiny patch (+T2)"]
        P3["v4: tiny patch (+A4)"]
        P4["v5..v8: small patches..."]
    end

    subgraph PNext["Patches against B1"]
        P9["v10: tiny patch (+next)"]
        P10["v11: tiny patch (+next)"]
    end

    P1 -.->|"opc_blob_patch -> B0"| B1
    P2 -.->|"opc_blob_patch -> B0"| B1
    P3 -.->|"opc_blob_patch -> B0"| B1
    P4 -.->|"opc_blob_patch -> B0"| B1

    P9 -.->|"opc_blob_patch -> B1"| B2
    P10 -.->|"opc_blob_patch -> B1"| B2

When a channel grows enough that the delta against B0 exceeds 25% of B0's compressed size, the saver automatically writes a new compressed full copy B1, and subsequent steps patch against B1 — keeping every patch small without ever creating chains. Conversely, if a channel shrinks dramatically (e.g., a conversation is summarized or truncated so base.raw_len > 4 * len(raw)), max_base_len refuses to patch against the huge old base and writes a fresh small full copy instead, so future reads don't have to decode a giant discarded base.

3.3 End-to-end warm read & write flow

Here is how a typical graph step executes once a thread is warm in the saver's BaseCache:

sequenceDiagram
    autonumber
    participant Graph as LangGraph Run
    participant Saver as AsyncOpenPostgresCheckpointer
    participant Cache as BaseCache (LRU ZstdDicts)
    participant Codec as opc-codec Thread
    participant PG as PostgreSQL (Pooled Conn)

    Note over Graph,PG: 1. Run opens: load latest checkpoint
    Graph->>Saver: aget_tuple(thread_id)
    Saver->>Cache: scope_bases(thread_id, ns)
    Cache-->>Saver: {messages: Base(v1, ZstdDict)}
    Saver->>PG: GET_LATEST_SKIP_SQL (tuple_row, skip cached base blobs)
    PG-->>Saver: checkpoint row + head_seq + patch bytes (base blob = NULL)
    Saver->>Codec: _load_page (decompress patch using cached ZstdDict)
    Codec-->>Saver: CheckpointTuple (with __opc_head token) + any new bases
    Saver-->>Graph: CheckpointTuple

    Note over Graph,PG: 2. Graph executes node & commits next checkpoint
    Graph->>Saver: aput(config with __opc_head, checkpoint, new_versions)
    Saver->>Cache: get((thread_id, ns, "messages"))
    Cache-->>Saver: Base(v1, ZstdDict)
    Saver->>Codec: dumps_typed + make_patch(Base v1, raw)
    Codec-->>Saver: Encoded("opc:zstd-patch:msgpack", patch_bytes, base="v1")
    Saver->>PG: PUT_SQL (1 statement: fence check + blobs + opc_blob_patch + checkpoint + head move)
    PG-->>Saver: inserted (channel, version) rows
    Saver->>Cache: update cache only AFTER commit (if new full copy)
    Saver-->>Graph: next_config

On a cold saver (after a process restart or when a request lands on a different replica):

  1. A graph run always begins with aget_tuple, which fetches the base from Postgres and primes BaseCache from the bytes it already decoded — so the run's very first aput is already a warm cache hit (0 extra base-fetch queries across 360 steps in the 60-thread fleet benchmark!).
  2. If a caller invokes aput directly without a prior aget_tuple (cold cache miss), the saver never silently falls back to a full copy (Rule 1). It fetches the parent checkpoint's base with BASES_SQL (skipping bases too large to patch server-side via octet_length(blob) <= max_len), decodes the base, and encodes the patch in a single codec-thread hop.

3.4 Specifically: how each upstream problem is solved

This is the core of the design — every guarantee is enforced by Postgres or zstd itself, never left to application-level hope.

Problem 1: Eliminating O(N²) disk growth without graph changes

  • Mechanism: checkpoint_blobs holds opc:zstd-patch:<serde_type> bytes compressed with the base's raw bytes as a zstd prefix; opc_blob_patch stores the (channel, version) -> base_version mapping. Pending writes ≥ 256 B are compressed with opc:zstd:<serde_type> when smaller.
  • Why it works everywhere: Patching operates on the serialized bytes produced by LangGraph's serde, so it shrinks add_messages lists, arbitrary dicts, tool artifacts, file maps, and DeltaChannel snapshots alike — with zero changes to graph code.
  • Safety net against corruption: Every zstd frame records its content size and content checksum (checksum_flag = 1). Applying a patch against anything other than its exact base bytes fails the checksum and raises PatchError.

Problem 2: Preventing silent partial state on mixed fleets & enabling safe rollback

  • Why patches live in checkpoint_blobs (not a separate blob table): If patch bytes lived in a side table with no row in checkpoint_blobs, upstream's aget_tuple would silently return missing channels (or try to replay partial writes). Instead, storing patch bytes directly in checkpoint_blobs under an opc: type prefix forces upstream's JsonPlusSerializer to raise NotImplementedError: Unknown serialization type: opc:zstd-patch:msgpack loudly (ADR-0008).
  • Zero-downtime rolling deploy: Roll out AsyncOpenPostgresCheckpointer(..., full_copies_only=True) first. In that mode, every row written is byte-for-byte upstream's format (while the saver still reads any patches). Once no upstream replica remains, remove full_copies_only=True (adoption.md).
  • Online, resumable rollback (rehydrate): Running python -m open_postgres_checkpointer.rehydrate "$DB_URI" sets the single-row switch in opc_patching_off, waits for all pre-switch transactions to finish (so no live saver can write another opc: row), and rewrites patches → compressed full copies → compressed pending writes back into plain upstream rows in byte-bounded, resumable batches (rollback.md). Live savers that hit opc_patching_off inside PUT_SQL or PUT_WRITES_SQL automatically drop into full-copies mode and retry cleanly.

Problem 3: Referential integrity vs. deletes and pruning

  • The trap with a naive foreign key: opc_blob_patch needs two foreign keys into checkpoint_blobs: one on the patch row itself (ON DELETE CASCADE) and one on the base row (so nobody can delete a base that a kept patch still depends on). If the base foreign key were immediate, a single DELETE FROM checkpoint_blobs WHERE thread_id = $1 (which deletes both base and patches together) would fail with ForeignKeyViolation because the immediate check runs before the cascade removes the patch side rows!
  • The fix: The base foreign key is DEFERRABLE INITIALLY DEFERRED (patch-placement.md). Postgres checks it at commit time, after the CASCADE has removed deleted patches' side rows:
  • Deleting a whole thread (even with upstream's adelete_thread!) succeeds cleanly and cascades all opc_blob_patch rows.
  • Any prune that would delete a base still referenced by a kept patch rolls back whole with ForeignKeyViolation.
  • If a writer commits a patch against a base that a concurrent prune just deleted, PUT_SQL fails at commit with ForeignKeyViolation (writing nothing — not even moving the head), and aput drops that cached base and retries once with compressed full copies.

Problem 4: Removing upstream's global lock safely

  • Why upstream has a lock, and why we don't need one: Upstream's AsyncPostgresSaver wraps every cursor in async with self.lock: (langgraph/checkpoint/postgres/aio.py:428), serializing all threads on a saver. A comprehensive trace of 6 real LangGraph topologies across sync, async, and exit durabilities (write-ordering.md) proved two structural facts:
  • Within a single run, LangGraph already chains aput calls sequentially and awaits DeltaChannel writes before each aput (0 reordered aput calls across 750 single-run traces).
  • aput_writes runs concurrently and may commit before its own checkpoint row exists — so no foreign key may require the checkpoint row first.
  • Result: Each operation checks out its own autocommit connection from AsyncConnectionPool with zero Python locks — scaling linearly across pooled connections until client CPU saturates.

Problem 5: Stopping concurrent runs from silently forking a thread

  • Mechanism: Every root-namespace read (aget_tuple and alist) reads opc_thread_head.seq in the same SQL query and embeds an opaque token ["<thread_id>", <seq>, "<checkpoint_id>"] under configurable["__opc_head"] (the __ prefix keeps LangGraph from persisting it into checkpoint metadata).
  • Admission inside PUT_SQL: A root-namespace aput carrying a token is admitted atomically inside PUT_SQL only if:
  • Idempotent retry: head_id = checkpoint_id (retried put leaves seq unchanged); or
  • Forward continuation: head_id = parent_checkpoint_id and that parent exists; or
  • Deliberate branch / time travel from the read: seq = token_seq, parent_checkpoint_id = token_at, and that parent exists (nothing of ours moved the head since the read); or
  • First write on an adopted / new thread: no head row exists, token_seq = 0, parent_checkpoint_id = token_at, and parent exists.
  • Under READ COMMITTED, two racing runs both try to update the same opc_thread_head row: the second writer blocks on the first's row lock, re-evaluates the WHERE predicate against the newly committed head, fails, writes zero blobs/checkpoints, and raises ThreadConflictError (fence-and-expiry.md). Direct callers without a token and subgraph namespaces (which have unique task-scoped namespaces and never collide across runs) pass through unblocked.

Problem 6: Making DeltaChannel pruning, thinning, and delete_for_runs work safely

  • Why upstream refuses aprune(keep_latest) on DeltaChannel threads: Keeping only the latest checkpoint row deletes the ancestor checkpoints and checkpoint_writes rows that DeltaChannel must replay from the last snapshot.
  • How our _retain() solves it (SQL-only, never rewrites a blob): Every retention operation (aprune(keep_latest), aprune(..., keep_last=N), adelete_for_runs) runs inside one REPEATABLE READ transaction per thread:
  • Selects the policy's kept checkpoints (keep_latest, keep_last=N + latest per run_id, or all checkpoints not matching run_ids).
  • For any kept checkpoint whose metadata holds counters_since_delta_snapshot, runs RETAIN_CHAINS_SQL — the exact same WITH RECURSIVE parent walk used by aget_delta_channel_history — and adds every visited ancestor back to each channel's snapshot into the kept set (ADR-0013).
  • Closes the kept set over pre-v4 pending_sends parents, subgraph-call lifetimes, every blob version referenced by any kept checkpoint (and by each namespace's newest checkpoint), and every kept patch's base_version (one hop, because bases are never patches).
  • Deletes everything outside that closed set in one statement (RETAIN_DELETE_SQL).

Problem 7: Production thread listing, expiry, and cloning

  • Thread listing (alist_threads): Walks the partial index opc_checkpoints_root_latest (checkpoint_id DESC, thread_id DESC) WHERE checkpoint_ns = '', verifies each row is its thread's newest root checkpoint via one PK probe (NOT EXISTS), filters on metadata @> filter, and paginates with a two-column keyset cursor. Reads zero blobs and never touches the codec thread or serde (thread-listing.md, ADR-0040).
  • Idle-thread expiry (asweep_expired): Finds threads whose opc_thread_head.touched_at is older than idle_for on the database clock, locks each candidate in its own READ COMMITTED transaction with FOR UPDATE SKIP LOCKED (never blocking active puts; aput_writes and subgraph puts take FOR KEY SHARE on the head row so they cannot race a sweep), and in a second statement (a fresh snapshot!) checks whether any newer root checkpoint exists (e.g., written by upstream during a rolling deploy) before deleting all four tables atomically.
  • Thread cloning (acopy_thread): Acquires a per-target transaction advisory lock (1869636468, hashtext(target)), refuses occupied targets or mid-rehydrate copies of opc: rows, and copies checkpoints, blobs, writes, and opc_blob_patch rows in one SQL statement (patches stay patches; zero decompression), minting a fresh opc_head_seq generation on the destination.

4. Inside the main optimizations

Beyond the architectural shift to flat patches and lock-free pooling, six targeted engineering optimizations drive the latency, memory, and disk profile.

Note on measurement provenance: Four-arm numbers come from uncontended PostgreSQL 16 release runs (core-set-results.md). Targeted before/after deltas for recent hot-path optimizations come from focused PostgreSQL 16 and micro-benchmarks recorded in optimization-backlog.md.

4.1 Zstd raw-prefix + Long-Distance Matching (LDM) with fixed tables

Early testing hit a subtle libzstd cliff: under the fast and dfast strategies, zstd 1.5.7 only digests the last 2^24 − 2 bytes (~16.78 MB) of a standard dictionary. Once a base grew past ~17 MB, its head became invisible to the compressor, appends had to re-encode the head, patches failed the 25% check, and the saver fell back to writing full copies.

Switching to raw-prefix mode (zstd.ZstdDict(raw, is_raw=True).as_prefix) with long-distance matching solved both the cliff and memory cost:

  • Parameters (_patch.py): level 3, strategy = dfast, enable_long_distance_matching = 1, fixed hash_log = 17 and chain_log = 17 (small, constant-size tables because LDM finds distant matches across the prefix), dynamic window_log = max(10, ceil(log2(base_len + raw_len))) up to 28 (256 MiB window, supporting bases up to ~128 MB), and checksum_flag = 1.
  • Precomputed option tables: _PATCH_OPTIONS is built once at import time for every window_log from 10 to 28, eliminating per-call option dictionary allocation (−31.9% on 3.7 KiB patches in micro-benchmarks).
  • Impact on large bases (1 MB append on growing bases, patch-write-path.md):
Base size Old dictionary mode Prefix + LDM mode
10 MB 376 KB in 0.17 s 399 KB in 0.03 s (5.7× faster)
24 MB 3,017 KB in 0.57 s (failed 25% check -> full copy) 402 KB in 0.06 s (9.5× faster, stays patched)
100 MB 30,760 KB in 3.90 s (full copy) 413 KB in 0.20 s (19.5× faster, stays patched)

4.2 Two-threshold storage sizing & bidirectional PATCH_FRACTION

Not every value benefits from patching:

  • Compression floor (MIN_COMPRESS_BYTES = 256): Below 256 B, zstd's frame header and checksum overhead outweigh compression savings, so tiny blobs stay plain upstream rows.
  • Patch floor (MIN_PATCH_BYTES = 1024): An opc_blob_patch side row plus its two indexes costs ~360 B on disk. Benchmark 9 showed that patching 256–512 B values used 1.03–1.31× upstream's value storage and slowed wide 50-channel reads. Separating the patch floor at 1 KiB brought value storage down to 0.79–1.02× upstream and made 50-channel aget_tuple reads 2.9× faster (10.06 ms → 3.50 ms; ADR-0031).
  • Bidirectional PATCH_FRACTION = 0.25:
  • Rejects patches larger than 0.25 * base.stored_len → triggers automatic rebasing to a fresh full copy.
  • Rejects bases larger than 4 * len(raw) (max_base_len) → prevents a tiny post-summary value from pinning and forcing every read to decode a multi-megabyte historical base.

4.3 BaseCache: pre-built ZstdDict reuse & wire-skipping cached base blobs

Each saver maintains a byte-bounded LRU BaseCache (default 64 MiB, configurable via base_cache_bytes), keyed by (thread_id, checkpoint_ns, channel) with a secondary scope index _by_scope[(thread_id, checkpoint_ns)] for O(1) per-read lookup.

  • Stores ZstdDict, not compressors: Each entry holds a Base(version, ZstdDict, raw_len, stored_len) at ~1× raw size (never ready-built compressor contexts, which bloat RSS). Holding the ZstdDict directly also avoids copying the base bytes into a new dictionary on every patched aput.
  • Warm read ZstdDict reuse: When aget_tuple reads a patched channel whose base version is already in BaseCache, Stored.raw() decodes the patch directly against the cached ZstdDict without decompressing the base blob or allocating a temporary dictionary (−78.1% latency / 4.6× faster and −22% peak RAM on a 1 MiB base in micro-benchmarks).
  • Wire-skipping cached base blobs (GET_LATEST_SKIP_SQL / GET_BY_ID_SKIP_SQL): When BaseCache already holds bases for (thread_id, checkpoint_ns), aget_tuple passes those (channel, version) pairs to Postgres. For any patch-only base row matching the cache, Postgres returns NULL::bytea instead of bl.blob — skipping both Postgres TOAST detoasting and sending megabytes of base bytes over the network, while still confirming the base row exists and has the right type. If a cached base ever became stale, zstd's content checksum catches it, raises an internal StaleCachedBaseError, drops the stale cache entries, and transparently re-fetches the full blobs from Postgres. Measured on Postgres 16 (485 KiB compressed / 1.1 MiB raw base): 2.784 ms → 0.916 ms (−67.1%, 3.04× faster), with zero overhead on cold reads (which stay on plain GET_LATEST_SQL).
  • Fast cold-cache base lookup (BASES_SQL): On a cold direct aput, BASES_SQL extracts c.checkpoint -> 'channel_versions' ->> w.channel directly per requested channel instead of expanding the entire JSONB object with jsonb_each_text (−27.7% narrow / −11.9% wide) and filters oversized bases server-side via octet_length(blob) <= w.max_len.

4.4 Single-statement atomic SQL, binary bytea[], plan stability & tuple_row

Every SQL statement in _sql.py is engineered for minimum round trips and predictable PostgreSQL query plans:

  • One round trip per aput and aput_writes: PUT_SQL combines opc_patching_off check, parent existence check, opc_thread_head fence update/insert, unnest-driven bulk checkpoint_blobs insert, opc_blob_patch insert (joined to blobs RETURNING, so retried puts insert zero duplicate side rows), and checkpoints upsert in a single atomic statement.
  • Binary bytea[] arrays (%(blobs)b): Passing Python list[bytes] with psycopg's %s placeholder serializes a text array with hex-escaped bytea (doubling wire size and spending CPU hex-encoding on the client and hex-decoding on Postgres). Using %(blobs)b sends raw binary bytea[] directly.
  • Prepared-statement OID stability (prepare_threshold=0): Every SQL statement is a constant template prepared on first use per connection. To prevent psycopg from preparing duplicate server plans for different Python types, aput / aput_writes / BASES_SQL pin parameter OIDs: str(token.seq) (TEXT OID 0), [Int4(...)] (int4[]), [Int8(...)] (int8[]), and a [b""] placeholder filtered by b.channel IS NOT NULL when channels is empty (bytea[]).
  • Planner-proof LATERAL ... LIMIT 1 probes: Postgres estimates jsonb_each_text(...) at 100 rows per checkpoint regardless of actual channel count, which can trick the planner into scanning and hash-joining checkpoint_blobs or checkpoints. Wrapping per-key lookups in CROSS JOIN LATERAL (... LIMIT 1) forces index-only / primary-key probes every time.
  • Positional tuple_row reads (_fetch_tuples): aget_tuple, alist, and alist_threads fetch positional tuples instead of allocating a Python dict per row (−24.5% on 20-channel aget_tuple, −21.3% on 100-row alist).

4.5 Single codec thread & hot-path allocation hygiene

  • One opc-codec thread per saver (ThreadPoolExecutor(max_workers=1)): Keeps CPU-bound serialization, deserialization, and zstd compression off the asyncio event loop so network I/O and concurrent coroutines stay responsive, while confining zstd's short-lived large buffers to a single glibc malloc arena rather than fragmenting RSS across a multi-thread pool.
  • Fewer codec hops & zero wasted copies:
  • aput splits inline vs. blob channels in a single pass without copying the entire channel_values dict or populating unchanged blob entries (−48.6% in Python overhead) and serializes + encodes warm channels in one codec-thread hop.
  • _load_page partitions checkpoint and blob rows in a single pass, builds parent_config lazily, merges channel_values in place, and skips Counter and sorting on single-row aget_tuple reads (−34.1%).
  • Public result dataclasses (ThreadInfo, SweepReport, RehydrateReport) use slots=True (−76% to −84% per-object memory).

4.6 Deduplicated alist, recursive-CTE delta walk, HOT head updates & partial listing index

  • One-pass deduplicated alist: Fetches checkpoints in 100-row pages (keyset-paginated within a namespace; key-fetch + batched PK probes via SELECT_BY_KEYS_SQL across namespaces so Postgres never rescans below the cursor). SELECT DISTINCT over (thread_id, checkpoint_ns, channel, version) fetches each distinct blob and base once per page, and Stored keeps only multi-referenced values decoded across the page (keep set).
  • One-statement WITH RECURSIVE delta history (walk_sql): Follows parent_checkpoint_id directly via primary-key lookups until every requested DeltaChannel hits its seed snapshot, fetching all pending writes and seeds (resolving patched snapshots too) in one SQL round trip. Uses a fast depth < 256 cycle guard (falling back to a single uncorrelated count only past depth 256) instead of SQL CYCLE path arrays. On forked threads, this makes DeltaChannel reads 6–7× faster than upstream's 1,024-row paged scan.
  • HOT (Heap-Only Tuple) updates on opc_thread_head: opc_thread_head is created with WITH (fillfactor = 70) and no secondary indexes (not even on touched_at, ADR-0024). Because no indexed column changes on head_id / seq / touched_at updates, Postgres performs in-page HOT updates with zero index write amplification (1,005 of 1,005 updates measured HOT in fence-and-expiry.md).
  • Partial root-only listing index (opc_checkpoints_root_latest): Indexing only (checkpoint_id DESC, thread_id DESC) WHERE checkpoint_ns = '' means subgraph checkpoints pay zero index maintenance cost, while alist_threads serves metadata-filtered pages in 243 buffers vs. 80,245 buffers without the index at 1% selectivity (thread-listing.md, ADR-0040).

Where to go next