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-failover.md

Control-plane PostgreSQL failover

Use this runbook when the control-plane database primary is lost: service_not_ready fires for every service, or control_plane_replication_lag pages.

The HA design runs the control-plane database as a primary with one synchronous streaming replica. It also keeps a WAL archive and daily base backups (deploy/postgres, control-plane PostgreSQL HA). This runbook moves the writer to the other node. At no time do two writers acknowledge a commit.

Production today is one PostgreSQL 18 primary on box 2 with no replica (decided 2026-10-30), set up by install-db-node.sh. There is no node to fail over to: when box 2’s database is lost, use restore. This runbook applies once a replica exists (PUSHLEFT_PG_REPLICA_HOSTS). The commands below name PostgreSQL 17, the staging and test layout; on box 2 use 18.

The same script (pushleft-pg-ha.sh) sets up two modes:

  • Automatic (the HA design). pg_auto_failover 2.2 from the PGDG packages. A monitor on a third host is the witness. The keeper on each data node runs PostgreSQL and follows the monitor’s decisions. HAProxy on each control-plane host sends db.internal.pushleft.dev:5432 to the writable primary. The services follow a failover with no restart and no config change. A three-VM Lima suite proved it on 2026-10-20. That suite was removed on 2026-10-23 and is not on staging yet (Proof).
  • Manual (fallback). An operator fences, promotes and repoints. npm run test:control-plane-ha proves this mode on Docker. Use it where there is no third host for a witness, or when the monitor is gone for good.

Automatic mode (pg_auto_failover)

Tool choice

Decided 2026-10-20. Compared:

OptionWitness / consensusMoving partsFit
pg_auto_failover (chosen)The monitor: one small PostgreSQL on a third hostpg_autoctl on each node and on the monitor, from apt (postgresql-17-auto-failover, pg-auto-failover-cli)Built for two data nodes and one witness. Keeps synchronous replication (ANY 1), fences an isolated primary itself, rejoins the old primary with pg_rewind. Has no HTTP role endpoint, so the script adds one (below).
PatroniA DCS: a 3-node etcd (control-plane box, replica box, a third box)etcd cluster + Patroni on each node, PythonMore general (REST role endpoint, many nodes). It adds a second consensus system to run, upgrade and back up for a 2-node database.
Manual onlyAn operatorNoneNo automatic recovery. RTO is the time to notice the page.

Layout

HostRunsNotes
Control-plane boxData node node_a (first primary), HAProxypushleft-pg-autoctl.service, pushleft-pg-health.socket
Second box (replica, control-plane cold standby)Data node node_b, HAProxySame units
Third hostThe monitorpushleft-pg-autoctl.service with the monitor’s PGDATA. The monitor needs a separate failure domain: on a data node’s box, the loss of that box also loses the witness.
Every host running control-plane servicesHAProxy with haproxy-pushleft-pg.cfg, 127.0.0.2 db.internal.pushleft.dev in /etc/hostsDATABASE_URL does not change. HAProxy forwards TCP, so TLS is end to end. For sslmode=verify-full, both nodes’ certificates must carry db.internal.pushleft.dev.

sqlx (the services’ driver) takes one host per URL and has no target_session_attrs, so a libpq-style multi-host URL does not work. A keepalived VIP needs its own role check and split-brain handling on the vSwitch. HAProxy with a role check is the simpler choice.

The role check is pushleft-pg-ha.sh health behind pushleft-pg-health.socket (port 8008, private and loopback sources only). It returns 200 when pg_is_in_recovery() is false, else 503. HAProxy polls it every second and marks a node down after two failures. It then closes every session to that node, so the pools reconnect to the new primary.

Setup

On all three hosts, install:

  • postgresql-17 postgresql-17-auto-failover pg-auto-failover-cli from PGDG (create_main_cluster = false; do not enable postgresql@17-main).
  • deploy/postgres as /etc/pushleft/postgres/, and the units from deploy/systemd.
  • /etc/pushleft/postgres-ha.env with the automatic-mode block of postgres-ha.env.example: PGDATA, both config paths, the node name, the monitor URI and the passwords.

Then run each step as postgres with the env file loaded (set -a; . /etc/pushleft/postgres-ha.env; set +a):

  1. On the monitor host, create the monitor and start it:

    pushleft-pg-ha.sh auto-monitor
    systemctl enable --now pushleft-pg-autoctl

    This runs pg_autoctl create monitor (scram-sha-256, TLS, private address only). It replaces the initdb trust lines with peer authentication and sets the autoctl_node password.

  2. On the first data node, create the node and start it:

    pushleft-pg-ha.sh auto-node
    systemctl enable --now pushleft-pg-autoctl pushleft-pg-health.socket

    This creates the node and the pushleft database, registers with the monitor and hardens local access. It adds a host all all <host> scram-sha-256 line per PUSHLEFT_PG_CLIENT_HOSTS (type host; the TLS note below sets hostssl). It includes auto-failover.conf (archive settings, slot WAL cap) after pg_autoctl’s own settings, and sets the replication password.

  3. On the second data node, run the same commands. It clones the first node with pg_basebackup and becomes secondary. The monitor sets synchronous_standby_names = 'ANY 1 (pgautofailover_standby_N)' on the primary.

  4. On the primary, create the database roles and set the owner:

    ALTER DATABASE pushleft OWNER TO pushleft_owner;
  5. On every control-plane host, install HAProxy and the hosts line.

  6. On both data nodes, enable pushleft-postgres-basebackup.timer (it skips a standby) and pushleft-postgres-offsite.timer.

Check the setup:

  • pg_autoctl show state (on any node, or on the monitor) shows one primary and one secondary.
  • curl http://<node>:8008/ returns 200 on the primary only.

Failure cases

  • Primary host lost (power, kernel, network). The monitor’s health checks fail. After node_considered_unhealthy_timeout (20 s), it promotes the standby, if the standby is secondary (in sync) and reported recently.

    • The promoted node still has synchronous_standby_names naming the old primary, so it cannot acknowledge a commit yet.
    • The monitor waits for the old primary to report itself demoted, or for primary_demote_timeout (30 s). By then an unreachable primary has demoted itself (network_partition_timeout, 20 s).
    • The monitor then moves the new primary to wait_primary, which drops synchronous replication. This wait is the fencing, and most of the measured failover time.
    • The new primary runs wait_primary, asynchronously, until the old node rejoins. Writes continue on one node, but RPO for a second failure in that window is not 0.
    • HAProxy gets 200 from the new primary and drops the old sessions. The services reconnect on their own. For the times, see Proof.
  • The old primary comes back. Its keeper asks the monitor first and learns it was demoted. It rewinds onto the new timeline with pg_rewind and rejoins as secondary. The monitor then switches the new primary back to synchronous. The proof polled it every 0.2 s from before power-on: it never answered as writable, and its role check never returned 200.

  • Primary isolated (cut off from the monitor and the standby, still running). Its keeper demotes it after network_partition_timeout (20 s).

    • Until then it believes it is primary. With synchronous_standby_names set, it cannot acknowledge a commit, because the standby is gone. A client that reaches it waits and never gets a success. The rewind discards those writes.
    • In that window, HAProxy on a host that still reaches it can send sessions there, and reads there can be stale. This window is part of the design. The proof did not test it (it powers the node off).
  • Standby lost. The monitor moves the primary to wait_primary: synchronous replication off, writes continue (the manual mode blocks writes). The monitor does not promote a node that is behind, so a later failover cannot lose an acknowledged write. A write can be lost if the primary’s disk fails before the standby is back.

  • Monitor lost. Nothing fails over until it is back. The data nodes keep their roles, and the primary keeps writing synchronously. Rebuild the monitor from its backup, or create a new one and point each node at it:

    pg_autoctl disable monitor --force
    pg_autoctl enable monitor <new URI>
  • Both data nodes lost. Use restore.

TLS between the services and PostgreSQL (fixed 2026-10-20). sqlx is built with tls-rustls-ring-webpki. DATABASE_URL uses sslmode=verify-full&sslrootcert=<operator CA>, as in the *.env.example files. pushleft-pg-ha.sh writes the client lines as hostssl (PUSHLEFT_PG_CLIENT_HBA_TYPE; host only for test servers without a certificate). The server certificate must name db.internal.pushleft.dev, the name clients use through HAProxy. pg_auto_failover’s own connections (monitor, replication) also use TLS.

HAProxy 2.8 (Ubuntu 24.04) starts every server as up until its first check. For about a second after HAProxy starts or reloads, a connection can reach the standby. The standby refuses it as read-only and writes nothing. HAProxy 3.1+ has init-state down.

The timings are the monitor’s defaults (pgautofailover.* settings on the monitor, timeout.network_partition_timeout in each keeper’s config). Lower values shorten failover. Keep primary_demote_timeout above network_partition_timeout. Otherwise a cut-off primary can still think it is primary when the new one starts to acknowledge commits.

Operations

pg_autoctl show state                                  # roles, LSNs, reported and assigned states
pg_autoctl perform switchover --formation default      # planned move (on the monitor); waits until done
pg_autoctl enable maintenance                          # on the standby, before a reboot; disable afterwards
pg_autoctl show events                                 # the monitor's decisions, newest last

A dead standby’s slot keeps at most 20 GB of WAL (max_slot_wal_keep_size). Past that, the standby cannot catch up. To rebuild it, run pg_autoctl drop node, empty its PGDATA and run auto-node again.

The manual commands (configure-primary, bootstrap-replica, enable-sync, disable-sync, fence, promote) refuse to run on a node that pg_auto_failover manages.

Last resort: the monitor is gone for good and the primary is lost.

  1. On the standby, stop pushleft-pg-autoctl.

  2. Fence the old primary as in manual step 1.

  3. On the standby, as postgres, promote it:

    pg_ctl promote -D "$PGDATA"
  4. After the incident, build a new formation from this node: a new monitor, and auto-node for a new second node. The node is now outside pg_auto_failover.

Proof

No suite proves automatic failover today. The 3-VM failover test ran on Lima VMs on the Mac and was removed with the Lima harness on 2026-10-23. Staging runs only the manual mode. npm run test:control-plane-ha still runs the manual mode on Docker (below).

The results below come from that removed test. Setup: three Lima VMs (2 vCPU, 3 GiB each), PGDG PostgreSQL 17.x, pg_auto_failover 2.2 and HAProxy 2.8. The real pushleft-api ran on the third VM through HAProxy. A writer inserted sequence numbers one psql call at a time with synchronous commit, and logged each number only after COMMIT returned. The test powered off the primary VM during the writes.

Measured on 2026-10-20 on an M5 Max, two runs. All times are on the client VM’s clock, from the power-off command, so they are upper bounds:

Run 1Run 2
Standby promoted, its role check 20023.5 s25.3 s
First API write through HAProxy (no restart, no config change)54.5 s56.4 s
First acknowledged writer row on the new primary—56.2 s
Acknowledged writes, all present on the new primary51 of 5153 of 53
Old primary writable while it booted and rejoinednever (50 polls)never (46 polls)
Planned switchover back, API writing again3.6 s3.2 s

The 30 s between promotion and the first write is primary_demote_timeout (above).

The same run also checked the backups:

  • It took a base backup on the primary (the standby’s timer skips) and shipped it and the WAL with offsite.
  • It decrypted them with the operator key on the Mac and restored them on the monitor VM to a timestamp between two writes.
  • pg_archive_copy_stale stayed quiet on a new last-success and fired on a stale or missing one.
  • pushleft-pg-ha.sh promote refused on a managed node.

Found during the run: a power cut a few minutes after setup left the unit and env files empty (unsynced). systemd reads an empty unit file as a masked unit. After that, the test synced first. Reboot a real host once after setup.

Not proven: a network partition (the isolated-primary window), monitor loss and replacement, operator-CA certificates (PUSHLEFT_PG_SSL_*; the run used self-signed certificates), Robot hardware.

Manual mode

scripts/control-plane-postgres-ha-e2e.sh (npm run test:control-plane-ha) runs every step below against the pinned PostgreSQL image on Docker.

We measured three runs on 2026-10-17 on a dev Mac (Docker Desktop, debug API build). The first API write on the promoted node came 4.92–4.96 s after SIGKILL of the primary. readyz went red at 4.25 s, the fence at 4.5 s, the promotion at 4.7 s. Most of the time is the readiness probe’s 2 s database timeout against the dead primary. Fence, promote and API restart together take about 0.7 s. The real RTO adds the time to notice the page and decide.

Nothing here promotes on its own. Without a witness, automatic promotion can create two writers.

Symptoms

  • service_not_ready for the API and every health listener (/readyz returns 503, {"database":{"reachable":false}}).
  • control_plane_replication_lag on the primary, if the primary is still up but the replica is not streaming.
  • Agents log lease failures and retry. Running workloads and routes keep serving (what agents do).

Decide

Fail over only when the primary is gone or you cannot bring it back quickly. For a restart or a short network failure, wait. With synchronous commit, a primary that comes back has lost nothing.

  1. Check that the replica is a usable target:

    psql "$REPLICA_OWNER_URL" -Atc "SELECT pg_is_in_recovery(), now() - pg_last_xact_replay_timestamp(), pg_last_wal_replay_lsn()"
  2. Expect t, and a replay age that matches the outage.

With synchronous_standby_names = 'ANY 1 (pushleft_replica)' (set by enable-sync), every COMMIT that the API acknowledged was on the replica’s disk before the client saw success. The RPO for the loss of one node is 0. If sync was off (disable-sync, below), anything after the replica’s last replayed LSN is lost.

1. Fence the old primary

The old primary must never accept a write again. Use the first option that applies, and record which one in the incident notes.

If its disk is reachable (host up, PostgreSQL dead or hung), run this on that host as postgres:

set -a; . /etc/pushleft/postgres-ha.env; set +a
/etc/pushleft/postgres/pushleft-pg-ha.sh fence
systemctl mask --now postgresql@17-main

fence stops a running server with -m immediate and writes standby.signal and pushleft.fenced into the data directory. If the server starts again, it comes up in recovery and refuses writes (cannot execute INSERT in a read-only transaction; the e2e proves this).

If the host is unreachable, do one of these through the provider (Hetzner Robot/Cloud console or API):

  • Power it off.
  • Remove it from the private network, or block 5432 from every control-plane host in the provider firewall.

Do not assume that it is dead. Continue only when one of these is done.

2. Promote the replica

  1. On the replica host, as postgres, promote it:

    set -a; . /etc/pushleft/postgres-ha.env; set +a
    PUSHLEFT_PG_OLD_PRIMARY_FENCED=yes /etc/pushleft/postgres/pushleft-pg-ha.sh promote

The script refuses to run without PUSHLEFT_PG_OLD_PRIMARY_FENCED=yes. It runs pg_ctl promote and resets synchronous_standby_names, so writes do not wait for the dead node. It creates the pushleft_replica slot for the next replica. The new primary runs asynchronously until a replica rejoins.

3. Repoint the services

  1. Change the host in DATABASE_URL in every /etc/pushleft/*.env: api, scheduler, agent-gateway, controller, mesh, telemetry-gateway, errors, admin (also PUSHLEFT_ADMIN_ACTION_DATABASE_URL), ops-alerts.

  2. Restart the services:

    systemctl restart pushleft-agent-gateway pushleft-scheduler pushleft-api pushleft-controller pushleft-mesh pushleft-telemetry-gateway \
      pushleft-errors pushleft-admin
  3. Check readiness. Expect 200 with "in_recovery": false:

    curl -fsS http://127.0.0.1:8080/readyz | jq .database

A service that still points at a standby (or at the fenced node) answers 503 with "in_recovery": true, and so do the health listeners. Readiness refuses a standby, so you can see a half-done repoint.

In manual mode, nothing moves the endpoint. A DNS name in DATABASE_URL and a changed record give the same result. You still restart, because pools do not reconnect to a different address on their own. HAProxy from the automatic mode also works here: it follows the node that answers 200, so a promotion alone moves the services.

4. Rejoin the old primary

Use a re-base with pg_basebackup. A re-base works in all cases, including after timeline divergence and lost WAL. The control-plane database is small, so the full copy is cheap. wal_log_hints = on is set, so pg_rewind --source-server=<new primary> is an option if the database grows. Nothing scripts or tests pg_rewind yet.

  1. On the old primary host (still fenced, PostgreSQL stopped), set PUSHLEFT_PG_PRIMARY_HOST to the new primary.

  2. Destroys data: re-base the old primary. This wipes its data directory (the script accepts only a fenced or standby one):

    PUSHLEFT_PG_REBASE=1 /etc/pushleft/postgres/pushleft-pg-ha.sh bootstrap-replica   # wipes only a fenced or standby data dir
    systemctl unmask --now postgresql@17-main
  3. On the new primary, check that the replica streams:

    psql -Atc "SELECT application_name, state, sync_state FROM pg_stat_replication"   # pushleft_replica|streaming|async
  4. On the new primary, turn synchronous replication back on:

    /etc/pushleft/postgres/pushleft-pg-ha.sh enable-sync                             # → quorum
  5. On the new primary, check that the replication line in its hba names the other host’s address. The line from configure-primary came across in the base backup.

  6. Move pushleft-postgres-basebackup.timer to the new primary.

  7. In ops-alerts.env, set PUSHLEFT_OPS_REPLICA_DATABASE_URL to the new replica.

Replica lost, primary fine

With sync on, writes block while the replica is away, to keep RPO at 0. If the replica will not be back within minutes:

  1. On the primary, turn sync off. Writes continue, and RPO is now above 0:

    /etc/pushleft/postgres/pushleft-pg-ha.sh disable-sync      # on the primary: writes flow again, RPO > 0
  2. Re-base the replica with bootstrap-replica (PUSHLEFT_PG_REBASE=1 if its data dir is a standby), and start it.

  3. On the primary, run enable-sync.

The replica’s slot keeps up to max_slot_wal_keep_size (20 GB) of WAL. Past that, PostgreSQL invalidates the slot and only a re-base works.

Check it worked

  • /readyz on every service returns 200 with "in_recovery": false.
  • Automatic mode: pg_autoctl show state shows one primary and one secondary.
  • Manual mode: scripts/ops-alerts.sh exits 0.

Alerts

  • control_plane_replication_lag (page): a pushleft_* slot on the primary is inactive or retains over 64 MiB. It also fires when the replica replays over 30 s behind (the time needs pg_read_all_stats). ops-alerts.sh also fires it when PUSHLEFT_OPS_REPLICA_DATABASE_URL is unreachable or not in recovery. Not in recovery means that someone promoted the replica without a repoint or a fence: two writers. Stop the services, find the node with the newest writes, and fence the other.
  • control_plane_wal_archive_stale (page): see the restore runbook.

Do not

  • Do not promote before the old primary is fenced, even if it seems dead.
  • Do not pg_ctl start a node that has pushleft.fenced before you re-base it.
  • Do not point some services at one node and some at the other.
  • Do not restore a PITR copy over the shared archive. pitr-restore turns archiving off for the copy; keep it off.
Rendered from the repository at build time. Edit docs/runbooks/control-plane-postgres-failover.md to change it.