Recovery and time travel
The history of every row change on a PostgreSQL server, the SQL that undoes a change, a row as it was at a past moment, a whole table rebuilt for psql, and the sequences after a restore.
DBTrail keeps every change to your tables, with the row as it was before and after. So you can see a row as it was, and get the SQL that puts it back. DBTrail never runs that SQL for you: you read it, then you run it.
Copy and paste
See a row as it was
Open psql on DBTrail's PostgreSQL port (Connect a client):
psql "host=127.0.0.1 port=5433 dbname=shop user=app sslmode=require"Then ask for the row at a past moment. Put your table and its key in place of
orders and 42:
SET TimeZone = 'UTC';
SELECT * FROM _flashback.orders AS OF '5 minutes ago' WHERE id = 42;The moment is read in UTC, which is why the SET comes first.
Get the SQL that undoes a change
The easy way is the web interface: Events shows a row's history, and Restore gives the undo SQL. From a terminal:
bintrail-pg recover --index-dsn "$IDX" --schema public --table orders --pk 42 \
--since "2026-11-29 14:00:00" --dry-run > undo.sql--sinceis a moment just before the bad change, in UTC. Do not leave it out: without it, the file undoes every change ever made to the row, itsINSERTtoo, and undoing anINSERTdeletes the row.--schemais the table's PostgreSQL schema.- This needs
bintrail-pg(theghcr.io/dbtrail/bintrail-pgimage has it) and$IDX, the address of DBTrail's history store (index-dsn).
The file holds the statements that undo the row's changes, the newest first. Read it before you run it. Then run it on your PostgreSQL:
psql -v ON_ERROR_STOP=1 -f undo.sqlYour table has an id from a sequence (SERIAL or IDENTITY)? Run the
sequence fix after loading rows into another
database or a restored one.
In detail
DBTrail keeps every change it captures from your PostgreSQL with the row as
it was before and after. From that history you can see what happened to a
row, get the SQL that undoes a change, read a row as it was at a past moment,
and rebuild a whole table as files psql loads. DBTrail never runs the undo
SQL for you: you review it and run it.
Recovery and time travel
The web interface has Events, dry-run undo SQL from Restore, and a row's state at any past moment with a backup configured.
AS OF from psql, over the PostgreSQL wire protocol:
SELECT * FROM _flashback.orders AS OF '5 minutes ago' WHERE id = 42;Setup: querying and recovering.
Limits: sequences need setval after a restore
(sequences after recovery), and a whole table is
rebuilt as a snapshot or as SQL files psql loads. All of them:
limitations.
A whole table at a moment, for psql
On a PostgreSQL server (from 0.139.1) the web interface's card to build a
backup for any moment says To load into PostgreSQL. The build writes one
<schema>.<table>.sql file per table, and the download is one .tar.gz of
them. Load each file with psql:
psql -v ON_ERROR_STOP=1 -f <file>The build is a plaintext copy of your tables. It stays on the daemon's disk until the first of: your download completes, 4 hours pass unclaimed, a new build for that server starts, the daemon restarts. What each file holds, and what it leaves out: the output is a snapshot, or SQL psql loads.
Querying and recovering
Once events are flowing, the read/recovery commands work over the index, which is the same for every source:
bintrail-pg query --index-dsn '…' --schema public --table orders --limit 20
bintrail-pg recover --index-dsn '…' --schema public --table orders --pk 42 --dry-run
bintrail-pg status --index-dsn '…'(The core bintrail binary works against the same index too: the read plane is
identical across binaries.)
What's recoverable: every captured row change, with full before/after
images: DBTrail captures a table only at REPLICA IDENTITY FULL. Under it,
unchanged out-of-line TOAST values are present in the before-image, so a
reversal of a large-column row is correct. An UPDATE or a DELETE that version
0.138.0 recorded for a table that was not at FULL is refused
(Upgraded from 0.138.0). FK ON DELETE CASCADE / SET NULL cascades are visible in the stream
(PostgreSQL performs them as ordinary row changes), so recover undoes them
directly.
Baseline snapshots exist for PostgreSQL, with a narrower scope.
bintrail-pg baselinetakes a consistent Parquet snapshot directly from a live PostgreSQL source, anchored to the replication slot's own LSN floor. It feeds single-rowreconstructand the shim's single-row_snapshot: both fold a PG baseline with the captured changes. This fold is validated end-to-end for scalar types: the canonical set (int2/4/8,numeric,bool,uuid,text/varchar/char,json,jsonb, enums) and the GUC-sensitive set (timestamptz,timestamp/date/time,real/double precision,bytea,interval), whose text rendering is pinned identically on the baseline COPY connections and the logical-decoding session (TimeZone=UTC,DateStyle=ISO,extra_float_digits=3,bytea_output=hex,IntervalStyle=postgres), and user-defined composite types. Container types beyond that (arrays beyond the testedinteger[]/text[], range/multirange,hstore, geometric) remain untested through the fold: validate your own round-trip. Re-baseline after upgrading: baselines taken before the rendering-GUC pin were rendered under your server's session defaults; on a server whose defaults differ from the pinned values, re-runbintrail-pg baseline: the baseline↔delta merge is an exact text join (the reader warns when it meets a pre-pin baseline). Events indexed before the upgrade also keep their pre-pin rendering: on such a server a GUC-sensitive primary key (timestamptz,float) has two text identities across the upgrade, so--pklookups and--historycan split there; re-baselining resolves this going forward (deltas before the new anchor are not replayed). Where the changes after a snapshot start. A PostgreSQL snapshot records an LSN floor read just before it opens, and reads start there, not at the snapshot's time: a transaction committing at the instant the snapshot opens can be missing from it, and is then applied from the index. Such a commit is looked for at least a minute before the snapshot's time; one held longer than that across the snapshot's start (a synchronous standby that stopped answering) is not covered. A primary-key-changing UPDATE in that minute makes the shim's whole-table_snapshotandverifyrefuse, as one after the snapshot does. Full-tablereconstruct --output-format parquetandbintrail baseline refreshwork for PostgreSQL: they fold a snapshot forward to a point in time, and the result is a snapshot the next fold starts from (see Full-table snapshots).--output-format psqlwrites SQL files psql loads, andbintrail-pg drillrehearses a restore with them into a scratch PostgreSQL (see Restore drills).--output-format mydumperstays out of scope.verifydigests row content without emitting a dump, so both baseline-anchored and live-sourceverifyare supported for PostgreSQL (see Verify a recovery).queryandrecover(which work from the indexed deltas alone, no baseline required) round out the recovery surface; see Limitations for the complete picture.
Restore drills
bintrail-pg drill does a real restore into a scratch PostgreSQL and checks
it. Run it on a schedule and you know that a restore works and how long it
takes.
What one run does:
- Reconstruct each selected table at
--at(default: now) as the SQL filereconstruct --output-format psqlwrites: the table's snapshot plus the indexed changes after it. - Load each file into the scratch PostgreSQL given by
--target-dsn, written as a URL (postgres://...), the waypsql -fwould run it, inside the file's one transaction. A load that fails anywhere leaves no table behind. The load is refused if the target holds anything in the drilled schemas (a table, a sequence or a view), which makes pointing it at a real server hard by default. - Check that each table's
count(*)equals the rows the file holds. A load error or a different count fails the table. - Report pass or fail per table, with the reconstruct and load times,
and exit non-zero on any failure.
--format jsonis for cron and automation.
The files are written to a temporary folder: removed on success, kept on
failure so you can see what did not load. --output DIR sets the folder
and always keeps it.
A table with no usable snapshot always fails, with the reason:
rebuilding it would start from an empty table and replay only the recorded
changes, and a rehearsal that never touched a snapshot must not read PASS.
Nothing is written or loaded for that table, and the folder is left marked
_INCOMPLETE.
The SQL file makes what the snapshot recorded: columns, types, NOT NULL,
defaults, identity and sequences, generated columns and the primary key.
Other indexes, constraints and grants are not rebuilt
(Full-table snapshots).
A drill proves the restore works and how long it takes. Whether the rebuilt rows match your PostgreSQL is what verify checks.
The scratch PostgreSQL
drill never starts a database itself: it loads into the URL you give it.
Any throwaway PostgreSQL works. The compose file has an opt-in drill profile
with a scratch PostgreSQL on a volume of its own:
docker compose --profile drill up -d drill-postgres
bintrail-pg drill \
--index-dsn "$IDX" \
--baseline-dir /var/lib/bintrail/baselines \
--tables public.orders \
--target-dsn "postgres://postgres:${DRILL_POSTGRES_PASSWORD:-drill}@127.0.0.1:15433/postgres?sslmode=disable"
docker compose --profile drill rm -sf drill-postgres
docker volume rm "$(basename "$PWD")_drill-postgres-data"$IDX stands for the history store's connection string
(index-dsn).
Remove only the scratch volume
Never run docker compose down -v to clean up after a drill. It removes
every volume in the compose file, including the one that holds DBTrail's
history store.
Verify a recovery
verify checks that rebuilding a table (a snapshot plus the indexed changes
after it) gives the same rows as a reference read from your PostgreSQL. It is
read-only: it never writes to your PostgreSQL or to the index. It runs over
DBTrail's history store, so every mode works wherever its inputs exist.
| Mode | Reads | Answers |
|---|---|---|
| Baseline-anchored (the default) | two snapshots and the index | does the rebuilt table match the table's last snapshot? |
| Live-source | a snapshot, the index and your PostgreSQL | does the rebuilt table match the live table? |
| Recover-input | the index only | are the before and after images that recover uses consistent with each other? |
bintrail-pg verify runs it. $IDX is the history store's address
(index-dsn) and $PG a postgres://
connection string to your PostgreSQL. Without --tables, every table in the
latest schema snapshot is checked.
# Baseline-anchored: rebuild and compare with the last snapshot
bintrail-pg verify --index-dsn "$IDX" --baseline-dir /path/to/snapshots
# Live-source: compare with the live table instead
bintrail-pg verify --index-dsn "$IDX" --baseline-dir /path/to/snapshots \
--source-dsn "$PG"
# Recover-input: the index alone
bintrail-pg verify --index-dsn "$IDX" --check recoverSnapshots kept in S3 are read with --baseline-s3 s3://bucket/prefix/
instead of --baseline-dir. --format json prints the result for a script.
All three work for a PostgreSQL server:
- Baseline-anchored is anchored on WAL positions (LSNs).
- Recover-input works from the index alone and needs no anchor.
- Live-source reads the table inside one
REPEATABLE READsnapshot, in PostgreSQL's own text rendering, under the same session settings the capture and the snapshots use (TimeZone=UTC,DateStyle=ISO,extra_float_digits=3,bytea_output=hex,IntervalStyle=postgres).
Live-source in detail
An index checkpoint at or past the anchor proves the index holds everything
the read saw. A checkpoint behind it proves nothing (WAL from other databases,
and autovacuum and checkpoints, move the anchor without producing any change
to index), so the run goes on and the result carries a coverage unverified
note.
With a role that has REPLICATION, the table is read at the snapshot of a
temporary logical slot created for the read, and the anchor is that slot's
consistent point. The snapshot holds exactly the transactions committed
before it, and every change the capture indexes carries its commit LSN, so
the rebuild stops just before that point, on the index and on the archives
alike, and a table that takes writes compares equal.
The check then waits, up to 60 seconds per table, for the running capture to save a position at or past that point:
- On a quiet database no later commit moves the capture's position, so the capture also saves how far PostgreSQL has sent it the WAL (saved only once every change received before it is indexed). When that reaches the point, every commit before it is in the index, and the table is compared with no note.
- If it does not reach the point within the wait, the table is
inconclusive: a capture held up before receiving a commit (a large transaction still being decoded, heavy WAL in other databases, network lag) cannot otherwise be told apart from a quiet one. - A capture still moving, but not yet at the point when the wait runs out, is
behind: the table is
inconclusive. - A capture older than this check saves no such position. There the wait ends
once the capture has saved its position twice without it moving, and the
result carries a
coverage unverifiednote. That is not proof: a capture held up before delivering a commit saves the same position too.
Without REPLICATION (or with no free slot, or no replication entry in
pg_hba.conf), the read is anchored on pg_current_wal_lsn() and not cut,
the result says why, and the table must take no writes while it is read.
A permanent capture loss stamped inside the compared window makes the
result inconclusive, never a false mismatch. A loss older than the snapshot
is outside the window and does not change the verdict: the snapshot is a
fresh read of your PostgreSQL, so it covers whatever the loss missed.
What a match does not prove
- The comparison is a 64-bit fingerprint over each table's rows, not a cryptographic hash. A match is strong evidence that capture and rebuild work; it is not proof against tampering.
- The default check does not test
recover. It rebuilds each row from its latest change.recoveralso uses before images, deleted rows' images and older changes later replaced by a newer one on the same key; a bad one of those can pass the content check. The recover-input mode checks them, as a separate run. - Recover-input proves the images agree with each other, not that they are true: a chain captured consistently but wrongly still passes.
- It does not test a rebuild at a moment between two snapshots, and it does not cover the schema (table definitions, indexes, sequence state, triggers).
- A table with no snapshot yet is
inconclusivein the default mode, never a proof.
Sequences after recovery
Restoring row data does not restore the sequence cursor behind a
SERIAL or IDENTITY column. This is the classic PostgreSQL dump/restore
gotcha, and it applies to bintrail-recovered data too: read this section if
your tables use auto-generated ids.
Why this happens
PostgreSQL's logical decoding does not replicate sequence state. In the words of the PostgreSQL docs: "Sequence data is not replicated. The data in serial or identity columns backed by sequences will of course be replicated as part of the table, but the sequence itself would still show the start value on the subscriber."
For bintrail that means:
- The id values in your rows are fully captured: the materialized id
rides in the row image, and
recoverputs it back verbatim. No data is lost. - The sequence's own
last_valueis a separate catalog object bintrail never sees. Nothing in the index knows how far the sequence had advanced.
So after loading recovered rows into a target, the sequence can lag behind the
ids that are now in the table, and the next INSERT that draws from it fails
with a duplicate-key error on the primary key.
Note that in PostgreSQL an INSERT that supplies an explicit id (which is exactly
what recover's reversal SQL does) never advances the sequence.
When you need to fix the sequence
- Recovering into a fresh or restored target (a different database, or the same database rebuilt from a backup): always. The target's sequence reflects the backup (or the start value), not the history you just replayed.
- After the sequence was reset on the source (
TRUNCATE … RESTART IDENTITY, a manualsetval,ALTER SEQUENCE … RESTART): yes: the recovered ids are ahead of the rewound cursor. - Applying
recoveroutput on the same live database where the rows were deleted: usually not needed. The sequence advanced when the rows were first inserted, and a sequence never goes backward on its own, so the cursor is still past the re-inserted ids. Running the fix anyway is cheap and harmless, so when in doubt, run it.
The fix: setval to MAX(id)
After the recovered rows are loaded, point each sequence just past the highest
id actually in the table. pg_get_serial_sequence finds the sequence name for
you (it works for both SERIAL and IDENTITY columns):
SELECT setval(
pg_get_serial_sequence('public.orders', 'id'),
COALESCE((SELECT MAX(id) FROM public.orders), 0) + 1,
false
);The + 1, false form makes the next nextval return exactly MAX(id) + 1,
and handles an empty table (next value is 1). Run one setval per
sequence-backed column; a table can have more than one.
Avoid running it while writers are actively inserting into the table (the
MAX and the setval are not atomic together); recovery windows are normally
quiesced anyway.
To fix every owned sequence in a schema at once, generate the statements
from the catalog (covers SERIAL and IDENTITY columns; run the output it
prints):
SELECT format(
'SELECT setval(%L, COALESCE((SELECT MAX(%I) FROM %I.%I), 0) + 1, false);',
quote_ident(sn.nspname) || '.' || quote_ident(seq.relname),
att.attname, tn.nspname, tbl.relname
)
FROM pg_class seq
JOIN pg_namespace sn ON sn.oid = seq.relnamespace
JOIN pg_depend dep ON dep.objid = seq.oid AND dep.deptype IN ('a', 'i')
JOIN pg_class tbl ON tbl.oid = dep.refobjid
JOIN pg_namespace tn ON tn.oid = tbl.relnamespace
JOIN pg_attribute att ON att.attrelid = tbl.oid AND att.attnum = dep.refobjsubid
WHERE seq.relkind = 'S'
AND tn.nspname = 'shop'; -- your schemaOut of scope: standalone sequences
A standalone sequence (one whose nextval values are used directly,
such as counters or ticket numbers, and that never land in a captured table) is
irrecoverable from bintrail. Its values never entered the row history, so
there is nothing to derive a cursor from. If such sequences matter to you,
snapshot them by other means (e.g. include them in your regular dumps:
pg_dump records sequence state).
One connection, with ProxySQL
Your application keeps one connection and its own PostgreSQL login. ProxySQL sends writes and transactions to your PostgreSQL, and reads to DBTrail, which answers the heavy ones from the copy.
Schema changes
How DBTrail sees an ALTER TABLE, a new table or a TRUNCATE on a PostgreSQL server, and what it does with each.