Control-plane PostgreSQL restore
Use this runbook when the control-plane database on box 2 is lost, or when bad data reached it (a wrong migration, an operator UPDATE).
The control-plane database is PostgreSQL 18 on box 2, with one primary and no replica (decided 2026-10-30). It keeps a WAL archive and daily base backups on its backup filesystem, and encrypted copies of both in R2 (deploy/postgres, disaster recovery). It holds everything durable: deployments, events, jobs and leases, fleet nodes and certificates, network evidence and allocations. With a replica (PUSHLEFT_PG_REPLICA_HOSTS), the loss of one node is a failover instead.
This runbook covers:
- point-in-time recovery (PITR) from the base backup and the WAL archive,
- restore from the encrypted off-host copies,
- a dump and its restore,
- the checks on the restored state before anything runs against it.
Before you start
$OWNER_URL: the migration-owner connection string.$RESTORED_URL: the same for the new databasepushleft_restored.$OPS_URL: the read-onlypushleft_opsrole (database roles).- For an off-host restore: the offline operator key and a read token for the R2 bucket.
Symptoms
service_not_readyfires for every/readyz. The API returns 500 from/readyz. The scheduler, controller and gateway health listeners return 503.- Journal lines such as
placement reconciliation failed,controller reconciliation failedorpool timed out. - Agents log
agent lease request was rejected: 500 Internal Server Errororagent lease request failed: ...every 2 to 5 s.
Agents during the outage
From crates/pushleft-agent/src/main.rs:
- Lease loop. A transport error retries after 2 s, and a non-2xx answer after 5 s, with no limit. No new work starts.
- Running job. Heartbeats fail and are logged. When the 45 s lease deadline passes without a renewal, the agent cancels local execution. Application containers that were already healthy, or that this attempt adopted, keep running. Only an unfinished rollout stops (
application::stop_on_lease_loss). - Completion. A failed completion is logged and dropped. The job stays
leasedin the database until its lease expires. Then it is retried under the same fencing. The work can run twice: delivery is at-least-once. - Running workloads. The agent does not touch workloads or their Caddy routes. Traffic continues.
Take a dump
-
Take the dump:
pg_dump --format=custom --file=/var/backups/pushleft/pushleft-$(date -u +%Y%m%dT%H%M%SZ).dump "$OWNER_URL" -
Check that the archive is readable:
pg_restore --list /var/backups/pushleft/pushleft-*.dump | head # the archive is readable -
Copy the file off the host.
Pushleft does not schedule this dump. The scheduled protection is the base backup and the WAL archive (below). Use a dump for a major-version change or a copy to another cluster. The dump contains token and session hashes, enrollment secret hashes and network evidence. It contains no secret values: the database stores Vault references only.
WAL archive and PITR
How the archive works:
archive_command(pushleft-pg-ha.sh archive) copies each completed WAL segment intoPUSHLEFT_PG_ARCHIVE_DIR(/var/backups/pushleft/wal-archiveon the backup filesystem) atomically.archive_timeout = 60limits the archive’s lag on a quiet primary.pushleft-postgres-basebackup.timerrunspushleft-pg-ha.sh base-backupdaily. It writes a compressed tar base backup under/var/backups/pushleft/postgres/<stamp>/and keeps the newest 7. It prunes archived WAL older than the oldest kept backup withpg_archivecleanup.- Both directories are local.
pushleft-postgres-offsite.timerencrypts them and copies them off the host (below). control_plane_wal_archive_stalepages when archiving fails after its last success, or when completed segments wait over 5 minutes.
To recover to a timestamp (just before the bad write), use a new, empty data directory. Any host with PostgreSQL 18 (the major of box 2) and read access to the backup and archive works.
-
Pick the newest backup taken before the target time.
-
Run steps 2 to 7 as the postgres user (
sudo -u postgres -s):pitr-restorewrites the copy’s files, andpg_ctlrefuses root. Load the env file and set an emptyPGDATA(owned by postgres,0700):set -a; . /etc/pushleft/postgres-ha.env; set +a unset PUSHLEFT_PG_LISTEN_ADDRESSES # the copy listens on localhost only, not box 2's address export PGDATA=/var/lib/postgresql/18/pitr # empty, owned by postgres, 0700 mkdir -m 0700 "$PGDATA" -
Restore the backup to the target time:
/etc/pushleft/postgres/pushleft-pg-ha.sh pitr-restore /var/backups/pushleft/postgres/<stamp> '2026-10-17 03:17:13+00' -
Copy the config files. Debian and Ubuntu keep them in
/etc, outside the backup:cp /etc/postgresql/18/main/{postgresql,pg_hba,pg_ident}.conf "$PGDATA"/ -
Remove the lines that name the live cluster’s directories from the copy, and Debian’s
include_dir, which the copy’s data directory does not have:sed -i '/^\(data_directory\|hba_file\|ident_file\|external_pid_file\|include_dir\)/d' "$PGDATA/postgresql.conf" -
Start the copy on port 5433:
pg_ctl start -D "$PGDATA" -o "-p 5433" -
Wait until recovery reaches the target and promotes. The answer is then
f:psql -p 5433 -Atc "SELECT pg_is_in_recovery()" # f once it reached the target and promoted -
Run the consistency checks against the copy.
-
Dump the rows you need from the copy, or make it the new primary. This step is for box 2 as
install-db-node.shsets it up: a plain primary, with at most one plain streaming replica. A cluster run by pg_auto_failover keeps its own state in the data directory, andinstall-db-node.shdoes not take it over. Recover such a cluster with automatic mode instead. For a new primary, stop every writer of the control-plane database first, so nothing writes to the old cluster again: on box 1,systemctl stop pushleft-api pushleft-scheduler pushleft-agent-gateway pushleft-controller pushleft-mesh pushleft-telemetry-gateway pushleft-errors pushleft-admin. Then swap the copy in on box 2. The installer queries a running cluster. The overrides ofpitr-restoreinpostgresql.auto.conf(archive_mode = 'off', the restore and target settings,listen_addresses) outlive it. So start the copy as the cluster and clear them first:# As root, in a new shell: export PATH=/usr/lib/postgresql/18/bin:/usr/sbin:/usr/bin:/sbin:/bin # pg_ctl and runuser, whichever env came before export PGDATA=/var/lib/postgresql/18/pitr # the copy from steps 2 to 7 runuser -u postgres -- /usr/lib/postgresql/18/bin/pg_ctl stop -D "$PGDATA" # the copy on 5433 (pg_ctl refuses root) pg_ctlcluster 18 main stop mv /var/lib/postgresql/18/main /var/lib/postgresql/18/main.old mv "$PGDATA" /var/lib/postgresql/18/main pg_ctlcluster 18 main start # Debian's config in /etc/postgresql/18/main runuser -u postgres -- psql -Xq -c "ALTER SYSTEM RESET archive_mode" -c "ALTER SYSTEM RESET restore_command" \ -c "ALTER SYSTEM RESET recovery_target_time" -c "ALTER SYSTEM RESET recovery_target_action" -c "ALTER SYSTEM RESET listen_addresses" PUSHLEFT_DB_LISTEN=<box 2 tailnet IPv4> install-db-node.sh cluster <db bundle> <the same clients> # TLS, listening, archiving; restarts runuser -u postgres -- psql -XAtc "SELECT pg_switch_wal()" >/dev/null; sleep 5 runuser -u postgres -- psql -XAtc "SELECT last_archived_wal, failed_count FROM pg_stat_archiver" # a new segment, no new failures systemctl start pushleft-postgres-basebackup.service # at once: the old backups belong to the previous timelinePoint the services at it again (
install-control-plane.sh migratechecks the connection). Start the writers on box 1 (install-control-plane.sh start, which coverspushleft-mesh). Then runsystemctl start pushleft-admin, whichstartdoes not touch. Deletemain.oldonce the new base backup is in R2. With a plain replica configured (PUSHLEFT_PG_REPLICA_HOSTS), build it again from the new primary withbootstrap-replica.
pitr-restore unpacks the base backup and writes recovery.signal, restore_command, recovery_target_time and recovery_target_action = 'promote'. It sets archive_mode = off, so the copy never writes into the production archive: its new timeline would collide with the real cluster’s next promotion. Recovery stops at the first commit after the target.
npm run test:control-plane-ha restores to a timestamp between two API writes in a new container. It checks that only the earlier write is present.
Off-host encrypted copies
pushleft-postgres-offsite.timer runs pushleft-pg-ha.sh offsite every 5 minutes on both data nodes. Only the current primary archives, so the standby usually has nothing new. For each base backup and each archived WAL file not yet shipped, the job:
- Encrypts it with
ageto the recipients inPUSHLEFT_PG_OFFSITE_RECIPIENTS_FILE, with no plaintext copy on disk. The recipients are the public keys of the offline operator key. The script refuses a file that holds a private key. The output isbase-<stamp>.tar.age(the backup directory as a tar) orwal-<segment>.gz.age(gzip, then age). - Runs
PUSHLEFT_PG_OFFSITE_COPY_COMMANDwith the encrypted file as$1. By default, it installs the file into the spool/var/backups/pushleft/offsite/postgres/.pushleft-offsite.timerships the spool to R2 under<host prefix>/postgres/, andoffsite_copy_stalewatches that step. The Vault snapshots use the same pattern. - Records the file in
/var/lib/pushleft/pg-offsite/shipped/. When every file went out, it writeslast-success(<epoch> <files shipped>).
Retention. Local copies follow base-backup: 7 base backups, and WAL back to the oldest. The job forgets what local retention removed. The target keeps its own retention (Storage Box snapshots, or a bucket with object lock and a lifecycle rule). Keep copies at least as long as the local window, and longer for PITR further back.
Alerts. A copy failure stops the run and leaves last-success unchanged. ops-alerts.sh fires pg_archive_copy_stale (ticket) when PUSHLEFT_OPS_PG_ARCHIVE_COPY_STATUS_FILE is missing or older than 15 minutes.
- The probe reads a local file, so it watches only the node that runs
ops-alerts. Point it at the node that is usually primary. - After a failover, check the other node’s
last-successby hand.control_plane_wal_archive_stalestill covers archiving on the current primary. - If the copy stays broken for days,
base-backupretention can delete WAL that never left the host. Fix the copy before then.
Restore from the off-host copy
Use any host with the PostgreSQL major of the control-plane database (18 on box 2). The host also needs the offline key, age, and deploy/postgres installed as /etc/pushleft/postgres (the restore copy’s restore_command calls pushleft-pg-ha.sh there). staging.sh rehearse pg-restore runs these steps on the rehearsal VMs.
-
Fetch box 2’s files from R2 with any S3 client and a read token for the bucket. With a replica, fetch both nodes’ uploads: after a failover, the newer timeline’s segments came from the other node.
aws s3 sync --endpoint-url https://<account>.eu.r2.cloudflarestorage.com s3://pushleft-offsite/<box 2 prefix>/postgres/ . # PUSHLEFT_OFFSITE_S3_PREFIX in box 2's offsite.env -
Make the restore directories:
mkdir -p /srv/restore/{backups,archive,data} -
Decrypt the base backups and the WAL:
for f in base-*.tar.age; do age -d -i operator.key "$f" | tar -C /srv/restore/backups -xf -; done for f in wal-*.gz.age; do n="${f#wal-}"; age -d -i operator.key "$f" | gunzip >"/srv/restore/archive/${n%.gz.age}"; done chown -R postgres:postgres /srv/restore -
Restore to the target time. Debian and Ubuntu keep
pg_ctland the other server tools in/usr/lib/postgresql/<major>/bin, outsidePATH(andsudoresetsPATH), so each command sets it:sudo -u postgres env PATH=/usr/lib/postgresql/18/bin:/usr/bin:/bin PGDATA=/srv/restore/data PUSHLEFT_PG_ARCHIVE_DIR=/srv/restore/archive \ /etc/pushleft/postgres/pushleft-pg-ha.sh pitr-restore /srv/restore/backups/<stamp> '<target time>' -
Give the copy a configuration. Debian and Ubuntu keep
postgresql.conf,pg_hba.confandpg_ident.confin/etc/postgresql, outside the backup, and PostgreSQL does not start without them. Sockets andpeerlogins are enough for the checks:cd /srv/restore/data && printf '# restore copy\n' >postgresql.conf && printf 'local all all peer\n' >pg_hba.conf && : >pg_ident.conf chown postgres:postgres postgresql.conf pg_hba.conf pg_ident.conf -
Start the copy on a socket only. A backup of a pg_auto_failover node carries that node’s listen address and TLS file paths:
sudo -u postgres env PATH=/usr/lib/postgresql/18/bin:/usr/bin:/bin PUSHLEFT_PG_ARCHIVE_DIR=/srv/restore/archive pg_ctl -D /srv/restore/data -w -l /tmp/restore.log \ -o "-p 5499 -c listen_addresses='' -c ssl=off -c unix_socket_directories=/tmp" start -
Run the consistency checks, then decide what to do with the copy.
-
To make the copy box 2’s database after box 2 is lost, restore on the replacement box 2 itself:
- Install the replacement as box 2 with Ubuntu and the backup partition (robot-hosts.md section 2). Add PostgreSQL 18 (its empty
18/maincluster) and the management tailnet asdb(install-control-plane.sh mgmt-key dbon box 1). - Run steps 1 to 6 there. Then run step 9 of WAL archive and PITR with
PGDATA=/srv/restore/data. It moves the copy into18/main, clears the restore settings, runsinstall-db-node.sh clusterand takes the first base backup. Then runinstall-db-node.sh clickhouseandinstall-db-node.sh vault-copyas on a new box 2. - Restore the off-host copies before you call it recovered. Install the recipients file (the public keys of the offline key) and set
PUSHLEFT_PG_OFFSITE_RECIPIENTS_FILEandPUSHLEFT_PG_OFFSITE_COPY_COMMANDin/etc/pushleft/postgres-ha.env. Install/etc/pushleft/offsite.envwith the R2 token and the samePUSHLEFT_OFFSITE_S3_PREFIXas before. Runinstall-db-node.sh clusteragain with the same arguments: it starts the offsite timers only when all of these exist, and says what is missing. Then runsystemctl start pushleft-postgres-offsite.service, thensystemctl start pushleft-offsite.service, and check that the new base backup is in R2 under the prefix. - On box 1: if the tailnet address of box 2 changed, set the new
PUSHLEFT_DB_ADDRESSininstall.env. Runinstall-control-plane.sh migrate, which points the services at it and checks the connection, theninstall-control-plane.sh startandsystemctl start pushleft-admin. - The mesh controller runs on box 1 since 2026-11-03, so
migrateandstartcover it (pushleft-meshreadsDATABASE_URLfrom/etc/pushleft/mesh.env).
- Install the replacement as box 2 with Ubuntu and the backup partition (robot-hosts.md section 2). Add PostgreSQL 18 (its empty
A three-VM Lima suite ran this end to end on 2026-10-20. The primary shipped a base backup and WAL, another machine decrypted them, and a third host restored them to a timestamp between two writes. The suite was removed with the Lima harness on 2026-10-23. Since 2026-10-30, scripts/staging/staging.sh rehearse pg-restore runs the off-host restore on the staging rehearsal VMs on PostgreSQL 18, without the R2 leg.
Restore from a dump
-
Stop every control-plane writer, so nothing writes to the old or the new database:
systemctl stop pushleft-api pushleft-scheduler pushleft-agent-gateway pushleft-controller pushleft-mesh pushleft-telemetry-gateway \ pushleft-errors pushleft-admin pushleft-ops-alerts.timer -
On a new cluster, create the cluster-wide roles (
pushleft_api,pushleft_agent_gatewayand the others) with the SQL in database roles. A database dump does not contain them. TheGRANTs are in the dump. -
Create an empty database owned by the owner role:
createdb --owner=pushleft_owner pushleft_restored -
Restore the dump into it:
pg_restore --exit-on-error --dbname="$RESTORED_URL" /var/backups/pushleft/pushleft-<stamp>.dump -
Migrate the schema to the running release:
DATABASE_URL="$RESTORED_URL" pushleft-api migrate -
Run the consistency checks against
pushleft_restored. -
Point the services at it: rename the databases, or change
DATABASE_URLin each/etc/pushleft/*.env. -
Start the gateway first, then the scheduler and the rest.
-
Start
pushleft-ops-alerts.timerlast.
Consistency checks after restore
Run these with psql as $OPS_URL against the restored database. The Fleet app is down at this point. Each query returns no rows, unless its note says otherwise.
-- Restore point: the newest durable writes. Everything after this is lost.
SELECT max(occurred_at) AS last_event FROM deployment_events;
SELECT max(reported_at) AS last_result FROM agent_job_results;
-- Results for jobs that do not exist, or results reported by another node (must be empty).
SELECT r.id FROM agent_job_results r LEFT JOIN jobs j ON j.id = r.job_id
WHERE j.id IS NULL OR (j.target_node_id IS NOT NULL AND j.target_node_id <> r.node_id);
-- Revocations made after the dump are LOST. Re-apply them from your incident notes before starting the gateway:
-- UPDATE fleet_node_certificates SET revoked_at = now() WHERE fingerprint_sha256 = '<fp>' AND revoked_at IS NULL;
-- Event sequences have no gaps per deployment (must be empty).
SELECT deployment_id FROM deployment_events GROUP BY deployment_id HAVING max(sequence) <> count(*);
Check capacity. On each row, used CPU and memory must not exceed the total:
DATABASE_URL="<restored database URL>" pushleft-controller fleet list
- Leases from before the restore expired long ago. The next lease of the owning node reclaims each one. A job with
attempt < max_attemptsrequeues, otherwise the job fails. - Certificates issued after the dump are missing from it. Those nodes now get 401, because their fingerprint is unknown. After the gateway starts,
fleet listshows a highSEEN(s)for those nodes. - A unique index enforces one active ingress route per host and node.
Then compare the database with the hosts. The database cannot answer these drift checks:
- Containers and routes created after the restore point. On each application node, compare
docker ps --filter label=com.pushleft.organizationand the Caddy route IDspl-ingress-*with Services and Routes on the deployment pages of the Fleet app. Pushleft does not adopt or remove a container or route that the database does not know (gap). Record it. Remove it only through a fenced teardown when the deployment is known again. Do not delete it by name. - Tokens and sessions created after the restore point no longer work. Revocations made after it are undone. Users must log in again, and you must revoke again any token you revoked in that window.
- Subnet sequence. The restore sets
network_subnet_slotsto the dump’s value. Subnets allocated after the dump can be handed out again (gap). Before you start the scheduler and mesh, advance the sequence past every allocation on the hosts:SELECT setval('network_subnet_slots', <highest slot seen on hosts> + 1);.
Check it worked
curl -fsS http://127.0.0.1:8080/readyzand every health listener return 2xx.scripts/ops-alerts.shexits 0 or fires only known items.pushleft-controller fleet listshows a heartbeat age under 60 s for every active node, within a minute of the gateway start.- One test deployment goes from
pl uptolive.
Do not
- Do not delete
jobs,deployment_events,agent_job_resultsorauth_eventsrows to clean up after a restore. The append-only triggers refuse it, and the rows are the audit trail. - Do not set
jobs.target_node_idorstatusby hand to move work. The owning node reclaims its leases. - Do not run two databases with the services split between them. Never let an old primary come back as a writer after the restore. Fence old nodes (
pushleft-pg-ha.sh fence) before the restored database takes writes.