Adopting the saver
How to move an application from upstream's langgraph-checkpoint-postgres saver to this one on
the same database, without migrating data. The way back is Rolling back.
What you need
- The Python, PostgreSQL and
psycopgversions in Supported versions. - A database upstream's saver set up, at the migrations of
langgraph-checkpoint-postgres3.2.0, or an empty one. The saver checks upstream's migration ledger on its first operation and raisesMigrationErrorunlesssetup()has brought it to the head this saver knows. - Every pooled connection in autocommit mode.
from_conn_stringsets that up; a pool you build yourself needskwargs={"autocommit": True}, or the first operation raisesPoolConfigError. -
A pool sized for your concurrency.
from_conn_stringdefaults to a fixed pool of 4 connections and acceptsmin_size,max_size,pool_kwargsandconn_kwargson bothAsyncOpenPostgresCheckpointerandOpenPostgresCheckpointer. By default,from_conn_stringinstalls a zero-RTT socket-readability check on checkout (falling back toAsyncConnectionPool.check_connectionon EOF/RST/activity and sweeping remaining dead sockets on failure, so a Postgres restart does not fail the next turn; ADR-0041), along with TCP keepalives (keepalives=1,keepalives_idle=30,keepalives_interval=10,keepalives_count=3),connect_timeout=10, andapplication_name="open-postgres-checkpointer"when not already set in the connection string,conn_kwargs, orPGCONNECT_TIMEOUT/PGAPPNAME. A value set only in apg_service.confentry is not seen and loses to these defaults: repeat it inconn_kwargs. Passpool_kwargs={"check": AsyncConnectionPool.check_connection}to ping on every checkout (for stricter immediate verification) orpool_kwargs={"check": None}to disable it. An async application that wants to own its checkpointer pool's lifecycle — for example in a web framework lifespan or across multiple savers — gets the same pool fromopen_pool, which takes the samemin_size,max_size,pool_kwargsandconn_kwargs:from open_postgres_checkpointer import AsyncOpenPostgresCheckpointer, open_pool async with open_pool(DB_URI, max_size=20) as pool: async with AsyncOpenPostgresCheckpointer(pool) as saver: ...
Closing the saver (async with, or await saver.aclose()) stops its codec thread and leaves
the pool open. Keep this pool dedicated to checkpointer traffic: its connections run with
autocommit=True, prepare_threshold=0 (preparing every statement on first use), and
application_name="open-postgres-checkpointer". Sharing it with general application queries
would make statements outside an explicit async with conn.transaction(): commit on their own,
prepare ad-hoc SQL on first execution, and mask app queries under the checkpointer's
application_name. A pool built directly with
AsyncConnectionPool(DB_URI, kwargs={"autocommit": True}, open=False) works too, with none of
the defaults above.
The one-way door
The saver reads every row upstream's saver wrote. Upstream's saver cannot read a thread once this
saver has stored a patch or a compressed copy in it: it raises on our type tags rather than
return partial state. So the rollout below keeps every row upstream-readable until no copy of
upstream's saver is left running, and rehydrate is the way back after that.
Rolling out
- Run
setup()once, from one process. It applies upstream's migrations and ours (our tables areopc_migrations,opc_blob_patch,opc_patching_offandopc_thread_head, the sequenceopc_head_seq, and the indexopc_checkpoints_root_latestoncheckpoints) and gives each existing thread a head row. Do not run it while upstream's ownsetup()runs: upstream'ssetup()can fail with a rawUniqueViolation; ours retries for up to 120 seconds, then raisesMigrationError. Runsetup()again on whichever failed. - Deploy with
full_copies_only=Trueeverywhere. In that mode every row the saver writes is upstream's, byte for byte, so replicas still on upstream's saver keep reading every thread. - When no replica runs upstream's saver, drop
full_copies_only. From then on the saver stores changed values as patches, and a thread it writes is ours to read.
The async saver:
from open_postgres_checkpointer import AsyncOpenPostgresCheckpointer
async with AsyncOpenPostgresCheckpointer.from_conn_string(DB_URI, full_copies_only=True) as saver:
await saver.setup()
graph = builder.compile(checkpointer=saver)
await graph.ainvoke(inputs, {"configurable": {"thread_id": "t1"}})
The sync saver, for code with no event loop of its own (it runs the async saver on a loop in a thread it owns):
from open_postgres_checkpointer import OpenPostgresCheckpointer
with OpenPostgresCheckpointer.from_conn_string(DB_URI) as saver:
saver.setup()
graph = builder.compile(checkpointer=saver)
graph.invoke(inputs, {"configurable": {"thread_id": "t1"}})
In a web service
Keep one checkpointer pool and one saver per process, opened at startup and closed on
shutdown. Opening a fresh pool per request throws away warm prepared plans (costing 1–1.5 ms per
put on DeltaChannel graphs; see Known limits) and discards the in-memory
base cache. Size the pool with your worker count in mind: 4 Uvicorn workers with max_size=20
can hold up to 80 connections to PostgreSQL (and default min_size=4 holds 16 idle connections
across 4 workers).
FastAPI / ASGI lifespan (async)
from contextlib import asynccontextmanager
from fastapi import FastAPI, Request
from open_postgres_checkpointer import AsyncOpenPostgresCheckpointer, open_pool
@asynccontextmanager
async def lifespan(app: FastAPI):
async with (
open_pool(DB_URI, max_size=20) as pool,
AsyncOpenPostgresCheckpointer(pool) as saver,
):
await saver.setup()
app.state.graph = builder.compile(checkpointer=saver)
yield # serves requests here; closes saver codec thread first, then pool
app = FastAPI(lifespan=lifespan)
@app.post("/threads/{thread_id}/turn")
async def turn(thread_id: str, request: Request, inputs: dict):
config = {"configurable": {"thread_id": thread_id}}
return await request.app.state.graph.ainvoke(inputs, config)
Calling await saver.setup() at startup is safe across rolling replicas: concurrent boots are
serialized by the migration lock, and on an already-current database setup() only reads the two
migration ledgers.
Sync frameworks with separate startup/shutdown hooks (Flask, Django, Celery)
Because OpenPostgresCheckpointer is constructed only through from_conn_string, frameworks
that expose separate startup and shutdown hooks (rather than one enclosing with block) can hold
it open with contextlib.ExitStack:
from contextlib import ExitStack
from open_postgres_checkpointer import OpenPostgresCheckpointer
_stack = ExitStack()
saver: OpenPostgresCheckpointer | None = None
def on_worker_start() -> None:
global saver
saver = _stack.enter_context(
OpenPostgresCheckpointer.from_conn_string(DB_URI, max_size=8)
)
saver.setup()
def on_worker_shutdown() -> None:
_stack.close()
Create the sync saver after process fork (for example in a Gunicorn post_fork or Celery
worker_process_init hook), never in a pre-fork master process: a saver created before fork()
refuses calls in child processes with CheckpointerError.
Behaviour that differs from upstream's saver
- Two runs on one thread. When a second run moves a thread on after a run read it, the
first run's next
putraisesThreadConflictErrorand writes nothing. The saver does not retry it; the application decides whether to read the thread again and re-run. Under the defaultdurability="async", the refused run's nodes have all run by the time the error surfaces; withdurability="sync", no node runs after the refused put. - Expiry. The saver starts no background task. Call
asweep_expired(idle_for)(orsweep_expiredon the sync saver) on a schedule: it deletes whole threads no put of ours touched foridle_for, on the database's clock. Makeidle_forlonger than your longest run; a run whose thread was swept getsThreadConflictErrorat its next put. Each call deletes at mostmax_threads(100 by default) threads and returns aSweepReport; call it again whilereport.moreis true. Threads counted inreport.failedare tried again on the next call.
while (await saver.asweep_expired(idle_for)).more:
pass
aprune(thread_ids) keeps the latest checkpoint per namespace, as upstream's
does, and works on DeltaChannel threads; keep_last=N keeps the latest N and each run's
latest instead. adelete_for_runs(run_ids) deletes the checkpoints of given runs, and
acopy_thread copies a thread. Run-based retention needs run_id in config metadata.
- Listing threads. alist_threads(saver, filter=..., before=..., limit=...) (or
list_threads for the sync saver) pages through threads newest first by their latest root
checkpoint, filtered on its metadata.
- Memory. Each saver keeps recent full copies to patch against, bounded by
base_cache_bytes (64 MiB by default). Values under 256 bytes are stored as upstream stores
them; values under 1 KiB are compressed but never patched.
Known limits
Figures below come from the benchmark cases in benchmarks/README.md on PostgreSQL 16, run before the first release.
- On a
DeltaChannelgraph, where upstream'sputis already cheap, ours pays about 1–1.5 ms more perputon a new connection, planning its larger statement; on a pool that stays open it is 0.72–1.16× upstream's. Keep the saver's pool open across runs, not one per request. - At 8 concurrent threads on one saver, the plain graph's
putp50 is 3.6–5.2× its single-thread p50, below upstream's at the same concurrency. The time is spent waiting for the event loop of the process running the graphs, not in the saver (concurrent-put-profile.md); spreading the threads over more processes should shorten it (not measured). - A value larger than
base_cache_bytesis stored as full copies: no base that size is held. Raising the bound lets such a value patch up to about 128 MB, past which a value and its base no longer fit zstd's window; set it per saver for threads of 64–128 MB values. - With a 16, 64 and 256 MiB base cache, 50 threads of about 1 MB on one saver grew RSS by 28 MB, 64 MB and 40 MB, against upstream's 26 MB: inside the bar of 2× the cache bound plus upstream's growth.
- A subgraph call stores its whole input, and its first value, as full copies each call (an open follow-up).
The measured numbers behind these are in the README and the design notes.
Behind a connection pooler
The saver is tested against PostgreSQL directly, not through PgBouncer or another pooler. What follows is what its code and psycopg's documentation imply for one:
- Pool once. Where the pooler already keeps the server connections, pass the saver a
psycopg_pool.AsyncNullConnectionPool(DB_URI, kwargs={"autocommit": True}, open=False), which opens a connection per operation and keeps none.setup()and a put and read on one are tested against PostgreSQL. - Prepared statements.
from_conn_stringandopen_poolsetprepare_threshold=0, as upstream'sfrom_conn_stringdoes, which prepares each statement on first use. In transaction mode that needs PgBouncer 1.22 or newer withmax_prepared_statementsabove 0 and a libpq from PostgreSQL 17 or newer (psycopg); otherwise passconn_kwargs={"prepare_threshold": None}. - Run
setup()on a direct connection. Its migration lock is a session lock (Advisory locks), and in transaction mode the unlock can reach another server connection than the one holding it. Session mode keeps one server connection per client and has neither constraint.
Supported versions
| Supported | |
|---|---|
| Python | 3.11, 3.12, 3.13, 3.14 (CI runs the unit suite on each; the integration suite runs on 3.13 and 3.14) |
| PostgreSQL | 15 and 16, required in the weekly integration matrix; 17 and 18 run in that matrix as early warning, without failing it |
langgraph-checkpoint |
4.3.1 up to, not including, 5 |
langgraph-checkpoint-postgres |
the tables and migrations of 3.2.0 (not a dependency: the saver carries its migrations) |
psycopg |
3.3.6 or newer (older versions can hang when a task is cancelled on Python 3.11) |
psycopg-pool |
3.2 or newer |
Storage format and versioning
What the saver stores beside upstream's rows:
- Type tags. In the
typecolumn ofcheckpoint_blobsandcheckpoint_writes, a value of ours is taggedopc:zstd:<serde type>, a full copy the saver compressed (one zstd frame with its content size and checksum), or, incheckpoint_blobsonly,opc:zstd-patch:<serde type>, a patch: the value compressed with its base's bytes as a zstd prefix. Upstream's tags never start withopc:. Values under 256 bytes, values zstd does not shrink, and every value written in full-copies mode keep the serde's own type and bytes, as upstream writes them. A value of 1 KiB and up is stored as a patch when the saver holds a base for it and the patch is at most a quarter of the base's stored size. Pending writes are compressed by the same rule, never patched. - Tables.
opc_blob_patchnames each patch's base, which is always a full copy, so a read applies at most one patch (indexopc_blob_patch_base).opc_patching_offholdsrehydrate's switch.opc_thread_headand the sequenceopc_head_seqhold each thread's head and generation, forThreadConflictErrorand expiry. The partial indexopc_checkpoints_root_latestoncheckpointsserves thread listing. - Migration ledger. Our tables come from our own migrations, recorded in
opc_migrations(version 8 in this release). Upstream's ledger,checkpoint_migrations, records only upstream's migrations.
What a version promises. From 1.0.0 on, the stored format (the type tags, the frames and
opc_blob_patch) changes only in a major release, and every release reads what an earlier one
stored. tests/corpus/ours/ guards that: it holds rows this saver wrote in the format 1.0.0rc1
ships, and an integration
test builds a database at the migration versions they record, runs the current setup() on it
and checks every read against the values recorded when the rows were written. Those files are
never regenerated to match the code; a new format adds files beside them.
Python API stability. From 1.0.0 on, the public Python API is everything listed in
open_postgres_checkpointer.__all__ together with open_postgres_checkpointer.rehydrate
(rehydrate, RehydrateReport, DEFAULT_BATCH_BYTES) and the opc-rehydrate CLI. Everything in
_-prefixed modules (_connection, _sql, _patch, _migrations, _errors) and any
_-prefixed attribute is internal and may change in any release. Public breaking changes happen
only in a major release; deprecations emit DeprecationWarning for at least one minor release
before removal.
A later 1.x release may add migrations of its own. A saver checks both ledgers on its first
operation and raises MigrationError when either records a version newer than it knows, so an
earlier release refuses a database that a later release's setup() has migrated instead of
writing into tables it does not know. It also raises when the database is behind, until
setup() brings it to its head. A saver checks once, so a process already running when the
ledger moves keeps running.
Mixed versions during a rolling deploy. A release that adds a migration: run its setup()
once, from one process, then replace the replicas; until a replica is replaced, a restart of it
raises MigrationError. Whenever replicas that cannot read our rows are still running
(upstream's saver, or a release of ours that does not know a newer format), deploy the new one
with full_copies_only=True first. In that mode every row it writes is upstream's, which every
version reads; drop the flag once no such replica is left.
Advisory locks
The saver takes two Postgres advisory locks:
- Migrations. When a ledger is missing or behind,
setup()takes the session lock on the single key1869637475(0x6F706763, ASCIIopgc) withpg_try_advisory_lock, so concurrentsetup()calls of ours run one at a time. It polls for up to 120 seconds, then raisesMigrationErrornaming the key;pg_locksshows the holder (locktypeadvisory,objid1869637475). It releases the lock when it finishes. Upstream'ssetup()does not take it. On a database already at its headsetup()only reads the two ledgers: no lock and no DDL, so a role withoutCREATEon the schema can call it. - Copies.
acopy_thread/copy_threadtakes the transaction lock on the key pair(1869636468, hashtext(target_thread_id))(1869636468is ASCIIopct), so copies to one target run one at a time. Postgres keeps one-key and two-key advisory locks apart, so the two never meet.
setup() also needs table locks on a database it has migrations to apply to: creating our side
table adds foreign keys to checkpoint_blobs. Each such statement waits at most 1 second for its
lock, so statements arriving behind it are not held up for longer, and is retried after 2 seconds
until the same 120-second deadline. A transaction left open on the table for that long makes
setup() raise MigrationError; calling it again continues
(ADR-0043).
An application that takes the same keys serializes against the saver: holding the migration key
makes a setup() with migrations to apply wait and then fail; holding a copy key makes each
copy whose target hashes to it wait. Two targets whose hashtext collide only make their
copies take turns. The locks never decide what is written: each copy checks in its own
statement that its target holds no rows and refuses otherwise, and the primary keys refuse a
duplicate row.
When upstream adds a migration
The saver carries upstream's migrations as of langgraph-checkpoint-postgres 3.2.0 (version 9 in
checkpoint_migrations) and refuses a database whose ledger records a newer version, raising
MigrationError: a newer upstream's tables may differ from the ones this saver writes. So:
- Upgrading
langgraph-checkpoint-postgresin an application changes nothing in the database until itssetup()runs. - Once a newer upstream's
setup()has applied a new migration, this saver stops at its next check, at a saver's first operation. - Using that database needs a release of this package that carries the new migration. Until one
is out, do not run a newer upstream's
setup()on a database this saver uses.