Skip to content

High Availability

Mohammad Rasoul Kazemi edited this page Dec 2, 2026 · 9 revisions

High Availability

Failover is new in the first release. High availability (phase 5) is built: manual failover, planned switchover (also of the map group), a hard failover of the map group while its server is alive, restore of preferred primaries, automatic failover (off by default) and escrow of the certificate authority key (off until switched on). Test your recovery procedure on your own cluster before you rely on it. This is the first release, 0.1.0 (2026-11-28); see Limitations and Known Issues for what is not tested on a cluster.

See Status and Roadmap for the state of every phase and Control Plane and REST API for the services that run these functions. Settings and timings are in Configuration; the steps for an incident are in Runbooks; the alerts raised are in Monitoring and Alerts; the console parts are in Web Console; the planned moves of a drain are in Rebalancing.

Model

  • Every shard group has one primary and defaultReplicaCount standbys (0 to 3; stored as replica.default in the system database, ADR 0011).
  • Failover is part of kingresd, fenced by leases. Patroni and etcd are not bundled (ADR 0021, which supersedes ADR 0012).
  • The manager leader is the server that runs the primary of the map group (group 0) (ADR 0018).
  • A cluster of one server has no failover. A failover cannot restore data that no standby had; the dry run says whether writes may be lost, and a real request must accept that explicitly.

Building blocks (control plane)

Heartbeats. Every server sends every other server a heartbeat each heartbeat-interval (default 1s). Each server keeps, on its own monotonic clock, when it last heard from each other server. Silence for suspect-timeout (5s) shows a server as suspect, silence for failure-timeout (10s) as dead. No time of day travels between servers.

The lease. Every server runs a grantor that keeps one holder per shard group. The kingresd that runs a group's primary renews its lease every lease-renew (2s); with a majority of the catalog's distinct hosts the lease is valid for lease-duration (10s) from the start of the round. A grantor writes a change of holder to disk before it answers, and after a restart refuses other holders for lease-duration plus lease-margin (3s). Every promotion needs the group's lease, so there is no way to two writable primaries for one group. The lease settings must be equal on every server (lease_settings_differ).

Fencing. A holder that cannot renew in time writes a fence marker on disk and stops its instance with an immediate stop (pg_ctl stop -m immediate); the instance does not start again without a lease, also not after a restart of kingresd or of the machine. This self-fence is armed for a group only once a standby that a failover may use is ready, so a primary is not fenced while its first standby is still being copied. For a group without a standby the loss of the lease raises the alert leaseLost and nothing is stopped.

The watchdog. kingres-watchdog is a small program next to kingresd that covers a dead or hung kingresd next to a live primary: kingresd writes a file for the instance after every renewal, and when the file has not changed for as long as the lease allows, the watchdog fences the instance. A server that runs the lease protocol does not start without it; the setting allow-no-watchdog is for tests and development only.

Stopping and starting a node. The orderly stop of a node (kingresd -stop-instances, which the service stop and the container stop run) asks every instance on the node for a fast shutdown at once, the primaries first, and tells each primary's watchdog to stand down as soon as PostgreSQL has accepted the request; only then does it wait, up to the stop timeout (60s), for each instance. A failure for one instance never keeps the others from being asked, and every error is reported. If the node is killed or kingresd hangs, nothing tells the watchdog: it stops the instance with an immediate shutdown once the lease has run out (about 10s after the last renewal), and the next start recovers from the WAL. No acknowledged commit is lost, and the node starts again by itself. In the logs this shows as received immediate shutdown request (PostgreSQL) and kingres-watchdog: the lease has run out, stopping the instance.

At a start, the primary of a group that has a ready standby on the cluster's standby list waits for its group lease before it starts, even when the node's lease record does not name the group yet; it never serves before it holds the lease. While it waits, kingresd logs the local instance is not running and the lease of its group is enforced: it starts once the lease is held. The wait has no time limit: in a cluster that starts up, it lasts until a majority of servers runs. A group without a standby, and a cluster of one server, do not wait. An unreadable standby list stops kingresd at start with an error.

Standbys. Standbys are placed on the next servers in the ring, skipping servers of the primary's server group where possible; a server never runs two instances of one group, so a small cluster can be under-replicated.

Client entry point. Off unless client-listen (primary) or client-standby-listen (lag-tolerant reads on a local standby) is set. It forwards TCP bytes to the chosen destination without reading them, so TLS and SCRAM stay end to end. Because the instance sees the proxy's address, address rules in pg_hba.conf cannot tell proxied clients apart; limit access through the bind address, firewall, roles and passwords. Settings: client-max-connections (1000), client-connect-timeout (5s), client-idle-timeout (1h).

In the extension: kingres_shard

kingres_shard (0.9) has standby nodes, promote_node, prepared transactions across a failover, distributed deadlock detection and coordinated restore points. kingres.promote_node(node_id int) returns jsonb (superuser) makes a promoted standby the primary of its group and the former primary a standby in one two-phase transaction. It raises the map version and the catalog term, can be resumed, lists the nodes it could not reach, and refuses, changing nothing, when the committing node cannot get its synchronous standbys to confirm. It answers {"status": "promoted"|"completed"|"already", "term", "unreached"}. For a planned switchover the extension offers the proof functions (switchover_mark, switchover_replayed, switchover_verify), and promote_map_group_without_majority is the operator's way out when the majority rule refuses for ever. The README of the extension writes out the call sequences a control plane must follow and names the test behind every answer.

Failover by hand

POST /api/v1/servers/{serverId}/failover (operation failoverServer; kingres_ops) promotes, for every shard group whose primary runs on that server (or the groups named in shardGroupIds), one standby, one group at a time, as the task server.failover. The map group is the last group of the task.

  • mode is required: hard is for a dead or unresponsive server and can lose asynchronously replicated writes; graceful is the planned switchover (below).
  • A request that could lose data is refused with 409 failover_needs_decision until it says allowDataLoss. Accepting a loss in a hard failover of the map group needs kingres_admin.
  • dryRun answers 200 with the plan (FailoverPlan) and changes nothing. The plan has a verdict per group: none (every ready standby was read, the best one is chosen and the group streamed a synchronous standby, so nothing acknowledged is lost), asyncOnly (only commits acknowledged under async can be lost), possible (the group ran without its synchronous standby, or the standby you named is behind the best one) or unknown (a ready standby could not be read). Any verdict but none needs allowDataLoss.
  • The body can also name the standby per group (targets) and carry a comment for the audit event.
  • Other refusals: no_replica_available, cluster_inconsistent, quorum_unavailable (503), lease_settings_differ, version_mismatch, failover_in_progress (one at a time, cluster wide), rebalance_in_progress.

GET /api/v1/failover returns the status, GET /api/v1/failover/reports and /failover/reports/{reportId} the reports (including incidents). After a failover the old primary comes back as a standby of the new one, by pg_rewind or, when the WAL it needs is gone, by a new copy; only a directory proved to be a former primary is touched.

Automatic failover

Built and off by default. A server is failed over when its tracker has not heard it for at least max(timeoutSeconds, 3 x failure-timeout), a strict majority of the servers report it not live, the deciding server hears a majority, no failover task is unfinished and none of its groups was failed over in the last 5 minutes. A failed start backs off 60 s doubling to 10 minutes. The setting autoFailover (enabled, timeoutSeconds, maxCount, eventsSinceReset) lives in the cluster settings and on the Replication page; at maxCount the loop raises autoFailoverLimitReached, and POST /api/v1/settings/cluster/auto-failover/reset sets the counter to 0 (a completed rebalance does too). Two failures at once, and a failure during a rebalance, are not tested on a cluster.

Fixed in 0.2.2 (a known issue of 0.2.1 and earlier): a server that vanishes was failed over slowly. The timing above holds for a server that crashes. When the host of a primary loses power or its address stops answering (packets are dropped, not refused), the decision is still on time, but the failover starts only about 14 minutes later and can then wait at "Choose the standby" for an operator. No data is at risk; the group is unavailable meanwhile. It is fixed in 0.2.2, published on 2026-12-02 (ADR 0060); see Limitations and Known Issues. The fix is also on the main branches and will be in 0.3.0. In the gate tests of 0.2.2 a vanished primary's group was writable again after about 82 s (PostgreSQL 18) and 71 s (PostgreSQL 19), a killed one after about 38 to 40 s, with no acknowledged row lost; the fix is in force once the leader of the cluster runs 0.2.2. The guard against data loss is as strict as before. In a cluster of two servers a vanished server still waits for an operator, because no majority is left to judge it.

Switchover (planned)

failoverServer with mode: graceful moves the primaries of a live server to standbys that stream from them. For each group it pauses the writes, lets distributed transactions end, stops the old primary cleanly, proves that the standby replayed everything (the shutdown checkpoint), then promotes it. Any failure before the promotion rolls back: the old primary takes the writes again, and the task ends failed with standby_behind, switchover_unproven, cannot_quiesce or prepared_transactions_pending. The task can be cancelled until the promotion begins. The pause of the writes is not kept across a restart of kingresd in the middle of a switchover.

A planned switchover must not run while servers of two versions run, because an older server does not honour the proof-only request (Upgrades).

Switchover of the map group

mode: graceful for the server that runs the primary of the map group, sent while that leader answers, is a planned switchover with the map group last: the chosen standby's server starts the bootstrap, the old leader stops cleanly and sends the proof, the standby promotes and becomes the manager leader, and its task engine finishes the task. Read the task from the new leader once the old leader's system database is stopped.

  • The old leader is held back (it keeps its lease) until the clean stop is over. The task lease is a row of the same system database, so the old leader lengthens it before the clean stop to cover the longest stop the call allows (90 seconds, about 105 seconds in all); a switchover therefore survives a clean stop that outlasts the lease of the task. A stop that outlasts the allowed 90 seconds is not clean: the switchover is rolled back, the old leader is started again, and the task ends failed with switchover_unproven. Nothing is promoted without the proof. Under heavy machine load such a give-up is more likely (a lease that lapses, a slow shutdown checkpoint); repeat the request when the load is lower. After the promotion, a step that reads a catalog whose instance is starting or stopping (the promoted instance of the map group can be stopped by the fence of its lease and started again) waits up to three minutes in all, then pauses the task with a message that names the step and the read and with the critical alert failoverBlocked; the repeated request runs the step again, and the alert ends when the step ends well. The task does not end as failed after the promotion.
  • A repeated clean stop of the old primary asks only for the proof that it stopped and does not release the lease again. A switchover ends when the held-back old server has forgotten the leader (state, unquiesce and unfreeze are accepted from the leader that a majority of ready members names).
  • If the move gets stuck, POST /api/v1/failover/map/abandon (kingres_admin) gives up the bootstrap; for a planned switchover it makes the old leader roll back.
  • The abandon waits at most 25 seconds, then answers 503. If a promotion, a create, a remove or a rebuild of a standby is running on that server, the abandon waits for it for at most 25 seconds and then answers 503 with Retry-After; repeat the call. A call that another server forwards to the server of the map group answers the same 503 when that server could not give its bootstrap up now (its lifecycle lock was held, or the lease of a bootstrap it gave up could not be let go of yet); it never answers "nothing in progress" in that case. A server where the feature does not run is only one that did not answer.
  • A bootstrap that is given up while it asks for a lease lets the lease go. The abandon marks the journal and releases the lease. A bootstrap call that was already on its way used to adopt the lease again after that, and the adoption was renewed for ever, so the old leader whose primary the abandon started again never won the lease, its primary stayed down and a drain never ended. The bootstrap now looks at the journal before every call and lets go of what it adopted for a journal that was given up.
  • A drain of the server that runs the map group uses this switchover as its hand-over step (Rebalancing).

Hard failover of the map group

Failing over the server that holds the primary of the map group is failoverServer with mode: hard.

  • While the server is alive (contract 0.28.0). Use it when the server is alive for the cluster but its primary of the map group is sick or unwanted and you do not want to wait for the clean stop and the proof of a switchover. The leader judges the loss before it changes anything, asks the server of a standby to start the bootstrap, ends the renewal of its own lease and writes a marker that keeps its primary from starting, stops that primary with an immediate shutdown, and only when the primary is seen stopped hands the lease to the standby's server, which promotes and becomes the leader. A primary that does not stop is stopped by the watchdog when its lease runs out (30 to 42 seconds in the cluster tests). Nothing is promoted without the lease, so two writable primaries are not possible.
  • A dead leader. A standby of group 0 takes over from a journal that survives a restart of kingresd.
  • A decision after the stop. If a loss shows only after the old primary was stopped, nothing is promoted, the task pauses with failoverNeedsDecision, and the old primary stays down. Repeat the request to the server of the standby that runs the bootstrap (the message names it), with the decision.
  • Declaring a candidate lost. If the standby that was handed the map group dies, the old leader stays held back. POST /api/v1/failover/map/abandon (kingres_admin) takes reason and lostServerId: the operator states that this server is lost. The server must be seen dead by the cluster (silent for the failure timeout), and what it promoted and acknowledged before it was lost is accepted with the declaration. The declaration carries a proof of the operator's session (made with the SCRAM client key) and goes only to the server whose primary of the map group is held back, which checks it against a cache of the administrators' keys (failover/admin-keys.json, refused when older than admin-keys-max-age, 72 hours by default). It needs a second standby of the map group, a session with a SCRAM password, and a current cache; the console's failover dialog of the map group has a field for it (ADR 0026).
  • Only one standby and the candidate dies. Every REST call then answers 503, and lostServerId cannot release the old leader. The way out is a local command, run on the server of the old leader with kingresd stopped: kingresd -release-map-hold -lost <serverId> -accept-data-loss (with the settings of the server, at least -data-dir and -server-host). It refuses without both words, for the local server, while the data directory is in use, for another server than the one the hold was made for, and while a bootstrap is in progress. It is audited (releaseMapGroupHold, contract 0.34.0) and can be repeated after a crash. -accept-data-loss is the operator's word that everything the lost server may have promoted is given up and that it is never started again with its old data directory.
  • An old leader whose hold cannot be resolved because every other server is gone does not resume by itself; an operator ends the hold with the abandon call once a standby answers.

Escrow of the key of the certificate authority

Off until an administrator switches it on (getCaEscrow, setCaEscrow, rotateCaEscrow; kingres_admin; contract 0.26.0; the Certificate authority tab of the Security page). When on, the leader seals the CA key and the revocation list to every server that hosts a ready standby of the map group and keeps the copies current. A new leader after a failover of the map group opens its own copy and goes on issuing, renewing and revoking certificates. A server that holds a copy can become the certificate authority, so its disk is as sensitive as the leader's: switch it on only when the servers that host standbys of the map group are as trusted as the leader. Without it, the new leader raises the critical alert certificateAuthorityUnavailable until the operator restores pki/ca.key and pki/revoked.json of the old leader from its backup into the pki directory of the new leader and restarts kingresd (Cluster Setup). No backup of the CA key is automated.

Restore of preferred primaries

POST /api/v1/replication/restore-preferred-primaries (operation restorePreferredPrimaries; kingres_ops; the Replication page has the dialog) hands each group back to its home server by a planned switchover after a failed server returned, one group at a time, also with dryRun. A group whose home server has no ready standby is skipped and listed in the report; a group that fails before its promotion is rolled back and the task ends partial. The map group is restored like any other group, and it works also when the leader was the old primary of the restore.

Operating notes

  • Settings. The timings (heartbeat-interval 1s, suspect-timeout 5s, failure-timeout 10s, lease-duration 10s, lease-renew 2s, lease-margin 3s) and the client entry point are listed in Configuration.
  • Replica count. PATCH /settings/cluster with defaultReplicaCount (0 to 3) starts the task standby.reconcile, which adds, removes and rebuilds standby instances until every group has that many. A group without a standby has no failover target; the alert groupUnderReplicated (warning) shows fewer standbys than the count, and groupWithoutSynchronousStandby (critical) shows that the primary no longer waits for an unreachable standby, so acknowledged commits exist on one server only.
  • Lost lease. The alert leaseLost (critical): the kingresd that runs a group's primary could not renew the lease in time; for a group with a standby the instance was stopped (fenced), for a group without one it keeps running and the alert is the only effect.
  • Rebalance and failover exclude each other. A failover first stops a running rebalance and nothing resumes it afterwards (Rebalancing).
  • Console. The Replication page shows the groups, the last failover, the lease and whether a commit waits for a standby; the dialogs plan, run and report a failover, switch a group over (the map group too) and restore preferred primaries.
  • Not tested on a cluster. Two failures at once, a failure during a rebalance, and a failover of the manager leader at every step of a table transfer or of a database import. A database import fails when a primary changes during it (Limitations and Known Issues).

Sources

Clone this wiki locally