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-postgres3.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) andopc_patching_off(the switchrehydratesets). - Patches live in upstream's
checkpoint_blobsunder the type tagopc:zstd-patch:<type>, and saver-compressed full copies underopc:zstd:<type>. The side table's foreign key to the base row isDEFERRABLE INITIALLY DEFERRED; an immediate key would make upstream'sdelete_threadfail on every thread that holds a patch (ADR-0008). - Our index on upstream's tables: the partial index
opc_checkpoints_root_lateston 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), sodelete_for_runsreads every checkpoint to find its threads.
4. Write path
- 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. - On
put, each changed channel of at leastMIN_PATCH_BYTESis patched against its base (ADR-0031). If the patch is at mostPATCH_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. - One statement, array parameters,
ON CONFLICT. A retriedputis a no-op. - 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
DeltaChannelthread, 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_runsdeletes 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 untildelete_thread, andcopy_threadrefuses it as a target until then.prunealways 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 rootputthat 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; aputwithout a token is admitted. A refusedputwrites nothing and raisesThreadConflictError(ADR-0017). The check runs inside theputstatement, soputstays one round trip. - Expiry.
asweep_expired(idle_for=…)deletes whole threads idle longer thanidle_foron 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 mostmax_threads(100 by default) and returns aSweepReportwhosemoresays 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 nextputis 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, andrehydrateleaves 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
- 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. - Upstream changes its storage between minor releases. 3.2.0 changed write ordering and added
prune. The migration-head check and the weeklyupstream-driftworkflow are the guards. - Against
DeltaChannel, we roughly tie on disk. On a 400-stepDeltaChannelgraph this saver uses ~0.95× upstream's disk (and ~0.83× at 10 MB). The main gain onDeltaChannelthreads is thatpruneand deletion work. - 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).
- 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).
- A second dependency. Patching needs a zstd binding on Python versions before 3.14:
backports.zstd, the standard library'scompression.zstdbackported, so 3.14+ needs none.