Skip to content

Architecture

How the saver stores and reads checkpoints, and why. Decisions are recorded one per file in the decision records; the promise to adopters is in compatibility.md.

1. What it is, and why

A LangGraph checkpointer for Postgres that implements the BaseCheckpointSaver contract, runs on the tables upstream's langgraph-checkpoint-postgres already created, and stores a changed value as a small compressed patch against an earlier full copy instead of writing the whole value again. It ships an async saver, a sync saver and a thread listing function (ADR-0025).

Upstream rewrites every changed value in full at every step, so a list that grows by one item per step costs O(N²) bytes. Numbers below were measured before the first release with the harnesses in benchmarks/ on PostgreSQL 16, unless marked as estimated:

Approach Disk against upstream Write time Needs a graph change
Compression in the serde ~18% smaller about equal No
Upstream's DeltaChannel ~18× smaller on append-only message graphs faster on large lists Yes, per channel; marked beta upstream
Patch storage (this saver) 6.9× smaller on 400-step chat; 4.0× / 5.7× / 12.5× on 1 / 3 / 10 MB threads comparable or faster on warm pools No

Patch storage is the only lever that is both large and automatic, and it applies to any value, not only to channels that have a reducer, so it is on by default (ADR-0037). A saver that only matched upstream's rows would tie upstream on disk by construction.

2. Feature set

Feature Status
No saver-wide lock; a pooled connection per operation Ships
One round trip per put and put_writes, safe to retry Ships
list fetches each distinct stored value once Ships
Delta-channel history by walking the real parent chain Ships
Patch storage, the loud guard against upstream, rehydrate Ships
copy_thread Ships
prune that works on DeltaChannel threads Ships
Thinning retention: keep last N, keep the last checkpoint of each run Ships
delete_for_runs Ships
Second-writer fence Ships
Thread expiry and a sweeper method the application calls Ships
List threads with a metadata filter (alist_threads) Ships
Sync saver (OpenPostgresCheckpointer) Ships
History of one channel Not built yet (ADR-0034)
Latest value of named channels; messages of a thread, paged Not shipped: a recipe on aget_state (ADR-0025)
Channels changed between two checkpoints; latest checkpoint of many threads Not shipped: a recipe on aget_tuple (ADR-0025)

Out of scope: compression as a serde wrapper and synchronous_commit = off (ADR-0038); element decomposition, projection, run leases, a Redis relay and a blob cache (ADR-0039).

3. Tables

  • Upstream's four tables, created by upstream's own migration list run verbatim under upstream's version numbers (head is 9 in langgraph-checkpoint-postgres 3.2.0). At start-up the saver checks the recorded head and refuses a head it does not know.
  • Our tables, tracked in a migration ledger of our own: opc_blob_patch (which stored value is a patch, and against which full copy), opc_thread_head (fence generation, head checkpoint and last-write time per thread) and opc_patching_off (the switch rehydrate sets).
  • Patches live in upstream's checkpoint_blobs under the type tag opc:zstd-patch:<type>, and saver-compressed full copies under opc:zstd:<type>. The side table's foreign key to the base row is DEFERRABLE INITIALLY DEFERRED; an immediate key would make upstream's delete_thread fail on every thread that holds a patch (ADR-0008).
  • Our index on upstream's tables: the partial index opc_checkpoints_root_latest on root checkpoints' (checkpoint_id DESC, thread_id DESC), for thread listing (ADR-0040, superseding ADR-0029). There is no index on the run id in checkpoint metadata (ADR-0016), so delete_for_runs reads every checkpoint to find its threads.

4. Write path

  1. A run starts with get_tuple, which has just loaded each channel's value. The saver keeps the bytes and version of the latest full copy per (thread, namespace, channel), so the writes of that run find their base in memory.
  2. On put, each changed channel of at least MIN_PATCH_BYTES is patched against its base (ADR-0031). If the patch is at most PATCH_FRACTION (0.25) of the base's stored size, the patch is stored; otherwise a compressed full copy is stored and becomes the new base. The fraction is a constant, not a setting.
  3. One statement, array parameters, ON CONFLICT. A retried put is a no-op.
  4. Serializing, compressing, patching and decoding run on one thread per saver, never on the event loop.

Seven rules close the main failure modes of patch storage:

# Rule Rationale
1 A writer that does not hold the base fetches it. It never falls back to a full copy just because memory is cold. Full copy on a miss erases the disk saving; fetching the base preserves 4–6× savings.
2 Memory holds base bytes, not ready-built compressors, and is bounded by real size. Ready-built compressors bloat RSS; raw base bytes fit 200 threads in 64 MiB.
3 Above 1 MiB the hash and chain tables are sized to the base, not only the window. Default settings leave large appends poorly matched; tuned LDM shrinks a 10 MB append to ~1.5 KB.
4 The database refuses a patch whose base row does not exist. Prevents writing an unreadable patch against a concurrently pruned base.
5 Bases are keyed by thread, namespace, channel and version. Prevents cross-thread or cross-namespace collisions when version strings coincide.
6 Every read path that returns values resolves patches: get_tuple, list, delta history, copy_thread (thread listing returns metadata only). Prevents any read path from surfacing raw patch bytes or dropping channels.
7 Large values with a writer that lacks the base are bounded by base_cache_bytes. Avoids unbounded memory growth on cold-cache rebuilds.

The patch format, zstd parameters and memory handling are in patch write and read paths. Pending writes of MIN_COMPRESS_BYTES and up are compressed when that makes them smaller (ADR-0036).

5. Read path

  • get_tuple: one statement returning each channel's stored bytes and, for a patch, its base. The client applies at most one patch per channel, whatever the history length.
  • list: page the checkpoint rows, collect the distinct (channel, version) pairs, fetch each once, resolve patches.
  • Delta history: one primary-key probe per hop along the real parent chain. Pending writes come back in upstream 3.2.0's order (task path, task id, index).

6. Concurrency

Upstream holds one lock for the whole saver. We hold none across threads, and no per-thread gate either: a trace (write ordering without a lock) showed that within one run LangGraph already submits checkpoint writes in order, and that two concurrent runs on one thread fork it whatever the saver does — that is the fence's job (§8). tests/ordering/test_write_ordering_trace.py and tests/integration/test_write_ordering_postgres.py run that trace against this saver. Pending writes can arrive before their checkpoint row, so nothing may require that row to exist first.

7. Lifecycle

delete_thread, copy_thread, prune, thinning and delete_for_runs touch SQL only; they never rewrite a stored value. copy_thread copies every row, patches as patches, in one statement, and refuses a destination that has rows (ADR-0015). The other three keep a set of checkpoints chosen by their policy and close it before deleting the rest, all in one snapshot per thread:

  • every stored value a kept checkpoint names, and each named patch's base (a base is always a full copy, so one step closes it);
  • on a DeltaChannel thread, every ancestor a kept checkpoint's history walks through back to each channel's snapshot, by the walk delta history runs, for the channels whose updates its metadata counts (counters_since_delta_snapshot) (ADR-0013);
  • a pre-v4 kept checkpoint's parent that holds its pending sends;
  • the stored values (and their bases) that each namespace's newest checkpoint names, even when delete_for_runs deletes that checkpoint (not for a subgraph call's namespace that goes with its root). A run that goes on from that checkpoint after the snapshot names its unchanged channels' values without writing them. These values stay until a later operation deletes a checkpoint of the thread, or the thread is deleted; a thread left with no checkpoint keeps them until delete_thread, and copy_thread refuses it as a target until then. prune always keeps the newest, so this changes nothing for it.

A subgraph call's namespace goes with its root checkpoint, and a kept checkpoint whose parent goes is left with no parent, as in upstream's prune. The deferred foreign key on opc_blob_patch is the backstop: a writer that commits a patch on a full copy a running lifecycle operation deletes makes that operation fail with ForeignKeyViolation, and retrying is safe.

Thinning is prune(..., keep_last=N): the newest N checkpoints per namespace, plus each run's newest (ADR-0014). delete_for_runs matches the run_id key in checkpoint metadata. That key is present only when the caller put it in config metadata or configurable; a plain invoke does not store it (estimated from upstream's metadata merge), so callers who thin or delete by run must pass it there. delete_for_runs logs how many checkpoints matched and how many it deleted. It is not an erasure guarantee (ADR-0012).

8. Fence and expiry

Both live in one row per thread, opc_thread_head, keyed by thread_id: the root namespace's head checkpoint id, a generation drawn from one global sequence, and the time of the last write on the database's clock (fence and expiry design).

  • Fence. Every read puts a token [thread_id, generation, checkpoint_id] in the returned configs (ADR-0018). A root put that carries a token is admitted only forward from the head, from the read when nothing of ours wrote since (both only onto a parent that still exists), idempotently, or as a thread's first write; a put without a token is admitted. A refused put writes nothing and raises ThreadConflictError (ADR-0017). The check runs inside the put statement, so put stays one round trip.
  • Expiry. asweep_expired(idle_for=…) deletes whole threads idle longer than idle_for on the database clock, re-checking each against the checkpoint table before it deletes, so a thread deleted and re-created is never swept (ADR-0019). One call deletes at most max_threads (100 by default) and returns a SweepReport whose more says idle threads remain, so the application calls again while it is true. A thread that expires under a live run is deleted, and the run's next put is refused (ADR-0023). The last-write time has no index, so head updates stay HOT (ADR-0024).
  • Adopted databases. setup() backfills a head row per existing thread; a thread upstream creates later gets one on our first write (ADR-0020). Head rows are written in every mode, and rehydrate leaves them (ADR-0022, ADR-0021).

9. Sync saver

One implementation. The sync saver, OpenPostgresCheckpointer in sync.py, drives the async one on a dedicated event loop in a thread. It is made only by from_conn_string: it owns the loop, so it builds the pool on it. list_threads(saver) is alist_threads for it. Upstream's conformance suite is async only, so the sync saver has its own test tier (tests/integration/test_sync_saver.py) that runs upstream's conformance suite, patches on and in full-copies mode, and the lifecycle property through the sync saver's own methods, with tests of what only the sync path has: a sync graph, puts from many threads on one read, the sync listing, and the loop's thread ending with the saver.

10. Known limits

  1. The saving depends on the writer holding the base. After the run's own read on a fresh saver, the first write found its base in every run but the thread's first (11 of 12, 22 of 23, 87 of 88 runs at 1, 3 and 10 MB). The run input __start__ is never primed, so values whose base the read did not provide are not patched.
  2. Upstream changes its storage between minor releases. 3.2.0 changed write ordering and added prune. The migration-head check and the weekly upstream-drift workflow are the guards.
  3. Against DeltaChannel, we roughly tie on disk. On a 400-step DeltaChannel graph this saver uses ~0.95× upstream's disk (and ~0.83× at 10 MB). The main gain on DeltaChannel threads is that prune and deletion work.
  4. Memory in workers that hold many large threads. The base cache bounds the bytes it accounts for, not the process's RSS; the allocator may keep freed buffers (ADR-0011, ADR-0032). On 50 threads of about 1 MB, RSS growth stayed inside the memory bar (core-set results).
  5. The deferred foreign key makes deletes heavier. Its cost on deletes has not been measured on a quiet host (estimated from the extra key check per deleted base row).
  6. A second dependency. Patching needs a zstd binding on Python versions before 3.14: backports.zstd, the standard library's compression.zstd backported, so 3.14+ needs none.