pushleft
Deploy your first app
Manual contents
Handbook
HandbookPushleftArchitecture
Operate
Install the control planeYour own serversFleetOperations and alertsAuthenticationAccess gateDomains and DNSUsage and budgetsScheduled jobsAbuse controlsAI provider proxyCustomer mailErrors and performanceLogs and metricsRetentionObject storageContainer registryGit server
Develop
The .pl.yaml manifestOnboard with an AI agentThe pl up demoBuild executorSource ingestionAgent gatewayManaged databasesSecurity findingsTunnels and shellsDev workspacesPrivate hostnamesMesh coordinatorsDesign baseline
Runbooks
Control-plane host failoverControl-plane PostgreSQL failoverControl-plane PostgreSQL restoreCustom domains and certificatesGateway key compromiseIngress host failureNode busyNode disk fullNode drain and replacementNode lostRegistry outageHetzner Robot hostsSecret rotationSecurity incidentStaging fleet on ProxmoxStaging build cacheStuck deploymentVault/OpenBao backup and recovery
More
CI pipelines
Manual · docs/runbooks/control-plane-postgres-restore.md

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 database pushleft_restored.
  • $OPS_URL: the read-only pushleft_ops role (database roles).
  • For an off-host restore: the offline operator key and a read token for the R2 bucket.

Symptoms

  • service_not_ready fires 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 failed or pool timed out.
  • Agents log agent lease request was rejected: 500 Internal Server Error or agent 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 leased in 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

  1. Take the dump:

    pg_dump --format=custom --file=/var/backups/pushleft/pushleft-$(date -u +%Y%m%dT%H%M%SZ).dump "$OWNER_URL"
  2. Check that the archive is readable:

    pg_restore --list /var/backups/pushleft/pushleft-*.dump | head   # the archive is readable
  3. 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 into PUSHLEFT_PG_ARCHIVE_DIR (/var/backups/pushleft/wal-archive on the backup filesystem) atomically. archive_timeout = 60 limits the archive’s lag on a quiet primary.
  • pushleft-postgres-basebackup.timer runs pushleft-pg-ha.sh base-backup daily. 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 with pg_archivecleanup.
  • Both directories are local. pushleft-postgres-offsite.timer encrypts them and copies them off the host (below).
  • control_plane_wal_archive_stale pages 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.

  1. Pick the newest backup taken before the target time.

  2. Run steps 2 to 7 as the postgres user (sudo -u postgres -s): pitr-restore writes the copy’s files, and pg_ctl refuses root. Load the env file and set an empty PGDATA (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"
  3. 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'
  4. 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"/
  5. 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"
  6. Start the copy on port 5433:

    pg_ctl start -D "$PGDATA" -o "-p 5433"
  7. 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
  8. Run the consistency checks against the copy.

  9. Dump the rows you need from the copy, or make it the new primary. This step is for box 2 as install-db-node.sh sets 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, and install-db-node.sh does 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 of pitr-restore in postgresql.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 timeline

    Point the services at it again (install-control-plane.sh migrate checks the connection). Start the writers on box 1 (install-control-plane.sh start, which covers pushleft-mesh). Then run systemctl start pushleft-admin, which start does not touch. Delete main.old once the new base backup is in R2. With a plain replica configured (PUSHLEFT_PG_REPLICA_HOSTS), build it again from the new primary with bootstrap-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:

  1. Encrypts it with age to the recipients in PUSHLEFT_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 is base-<stamp>.tar.age (the backup directory as a tar) or wal-<segment>.gz.age (gzip, then age).
  2. Runs PUSHLEFT_PG_OFFSITE_COPY_COMMAND with the encrypted file as $1. By default, it installs the file into the spool /var/backups/pushleft/offsite/postgres/. pushleft-offsite.timer ships the spool to R2 under <host prefix>/postgres/, and offsite_copy_stale watches that step. The Vault snapshots use the same pattern.
  3. Records the file in /var/lib/pushleft/pg-offsite/shipped/. When every file went out, it writes last-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-success by hand. control_plane_wal_archive_stale still covers archiving on the current primary.
  • If the copy stays broken for days, base-backup retention 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.

  1. 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
  2. Make the restore directories:

    mkdir -p /srv/restore/{backups,archive,data}
  3. 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
  4. Restore to the target time. Debian and Ubuntu keep pg_ctl and the other server tools in /usr/lib/postgresql/<major>/bin, outside PATH (and sudo resets PATH), 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>'
  5. Give the copy a configuration. Debian and Ubuntu keep postgresql.conf, pg_hba.conf and pg_ident.conf in /etc/postgresql, outside the backup, and PostgreSQL does not start without them. Sockets and peer logins 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
  6. 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
  7. Run the consistency checks, then decide what to do with the copy.

  8. 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/main cluster) and the management tailnet as db (install-control-plane.sh mgmt-key db on 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 into 18/main, clears the restore settings, runs install-db-node.sh cluster and takes the first base backup. Then run install-db-node.sh clickhouse and install-db-node.sh vault-copy as 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_FILE and PUSHLEFT_PG_OFFSITE_COPY_COMMAND in /etc/pushleft/postgres-ha.env. Install /etc/pushleft/offsite.env with the R2 token and the same PUSHLEFT_OFFSITE_S3_PREFIX as before. Run install-db-node.sh cluster again with the same arguments: it starts the offsite timers only when all of these exist, and says what is missing. Then run systemctl start pushleft-postgres-offsite.service, then systemctl 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_ADDRESS in install.env. Run install-control-plane.sh migrate, which points the services at it and checks the connection, then install-control-plane.sh start and systemctl start pushleft-admin.
    • The mesh controller runs on box 1 since 2026-11-03, so migrate and start cover it (pushleft-mesh reads DATABASE_URL from /etc/pushleft/mesh.env).

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

  1. 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
  2. On a new cluster, create the cluster-wide roles (pushleft_api, pushleft_agent_gateway and the others) with the SQL in database roles. A database dump does not contain them. The GRANTs are in the dump.

  3. Create an empty database owned by the owner role:

    createdb --owner=pushleft_owner pushleft_restored
  4. Restore the dump into it:

    pg_restore --exit-on-error --dbname="$RESTORED_URL" /var/backups/pushleft/pushleft-<stamp>.dump
  5. Migrate the schema to the running release:

    DATABASE_URL="$RESTORED_URL" pushleft-api migrate
  6. Run the consistency checks against pushleft_restored.

  7. Point the services at it: rename the databases, or change DATABASE_URL in each /etc/pushleft/*.env.

  8. Start the gateway first, then the scheduler and the rest.

  9. Start pushleft-ops-alerts.timer last.

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_attempts requeues, 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 list shows a high SEEN(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.organization and the Caddy route IDs pl-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_slots to 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/readyz and every health listener return 2xx.
  • scripts/ops-alerts.sh exits 0 or fires only known items.
  • pushleft-controller fleet list shows a heartbeat age under 60 s for every active node, within a minute of the gateway start.
  • One test deployment goes from pl up to live.

Do not

  • Do not delete jobs, deployment_events, agent_job_results or auth_events rows 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_id or status by 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.
Rendered from the repository at build time. Edit docs/runbooks/control-plane-postgres-restore.md to change it.