Repository navigation
Architecture Runtime Views Availability and Ledger
This page is the second runtime view (arc42 chapter 6): failover and switchover, and the life of a ledger block from its creation to its verification by an auditor. The sharding flows are on Architecture Runtime Views Sharding.
Note. Failover and switchover are new in this release: test your recovery procedure on your own cluster before you rely on it, and see High Availability for what is and is not tested. The RFC 3161 and OpenTimestamps anchoring paths were tested against local fakes only (Ledger Anchoring). The limits are on Architecture Risks and Technical Debt.
Every kingresd runs a grantor that keeps one holder per shard group. The kingresd that runs a group's primary renews the group's lease every lease-renew; with a majority of the catalog's distinct hosts the lease is valid for lease-duration from the start of the round. A holder that cannot renew writes a fence marker and stops its instance with an immediate stop. 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. Every promotion needs the group's lease; two writable primaries for one group are excluded by design. A group lease is enforced only once a standby that a failover may use is ready, so a primary is not fenced while its first standby is being copied. A server that runs the lease protocol does not start without kingres-watchdog, which stops its primary when kingresd is gone. Time never travels between servers: each server measures silence on its own monotonic clock (heartbeat 1 s, suspect after 5 s, dead after 10 s by default).
Started by an operator (failoverServer, mode hard) or by the automatic loop (off by default). The task runs on the manager leader and each step is idempotent: on a repeat it reads what exists first.
sequenceDiagram
participant Op as Operator or auto loop
participant L as kingresd leader
participant Old as Old primary server
participant G as Lease grantors
participant New as Chosen standby
participant M as Map group primary
Op->>L: failoverServer mode hard
L->>L: preflight, refusals, dry run shows the plan
L->>Old: freeze the group, stop the old primary
L->>G: wait until the old lease is no longer held
L->>New: read positions, choose standby, verdict on data loss
L->>New: hand the lease to the new server
L->>New: promote, role file first, lease checked, then pg_promote
L->>M: kingres.promote_node
L->>M: read the catalog back, check the term rose
L->>New: repoint the other standbys
L->>M: recover prepared transactions, check_cluster
L-->>Op: report
Points from the control plane README and the extension README:
-
Stop the old primaryis irreversible: from there the group has no primary and the task cannot be cancelled. An unreachable server is skipped; its lease fences it. - The verdict (
none,asyncOnly,possible,unknown) must be accepted byallowDataLoss, otherwise the task pauses with the alertfailoverNeedsDecision(409failover_needs_decisionfor the request). - The standby is chosen from its received and replayed positions, then synchronous state, preferred server, ring and id; the choice is pinned once, so a repeat never chooses again. Two standbys out of recovery stop the task with
split_promotion. -
kingres.promote_node(node_id)makes the promoted standby the primary of its group in one two-phase transaction, raises the map version and the catalog term, can be resumed, and refuses when the committing node cannot get its synchronous standbys to confirm. The control plane repeats it by the rules of the extension README (10 calls, 15 minutes, answers by SQLSTATE). - Afterwards the old primary comes back as a standby, by
pg_rewindor a new copy, and only a directory proved to be a former primary is touched. - A failover is refused while a rebalance is pending or running, and only one failover runs at a time cluster wide.
- The failover of the map group (the leader's own server) is started by hand in mode
hard, also while its server is alive (the leader judges the loss, fences its own primary of the map group and hands the lease to a standby's server), and is run by a standby of group 0 from a journal that survives a restart ofkingresd. A hard failover that accepts a loss of data needskingres_admin. The key of the certificate authority reaches the new leader only if the escrow was switched on beforehand (off by default); otherwise the new leader raises the critical alertcertificateAuthorityUnavailableuntil the operator restorespki/ca.keyandpki/revoked.jsonfrom a backup. - If the candidate of a map group failover or switchover dies and the map group has only one standby, every REST call answers 503. The declaration
lostServerId(it carries the proof of the operator's session, ADR 0026) needs a second standby; the local commandkingresd -release-map-hold -lost <serverId> -accept-data-loss, run on the server of the old leader whilekingresdis stopped, is the way out otherwise. - Automatic failover needs the server unheard for at least
max(timeoutSeconds, 3 x failure-timeout), a strict majority reporting it not live, no unfinished failover task and no failover of its groups in the last 5 minutes.
failoverServer with mode: graceful moves the primaries of a live server to standbys that stream from them, one group at a time. The proof that nothing is lost is kingres.switchover_verify, which answers true only when the old primary's control file says exactly shut down and the new primary's own WAL holds that shutdown checkpoint as the last record it replayed.
sequenceDiagram
participant L as kingresd leader
participant Old as Old primary
participant New as Standby
participant M as Map group primary
L->>Old: pause writes, wait for distributed transactions to end
L->>Old: switchover_mark, then check New replayed it
L->>Old: clean stop with pg_ctl stop fast
L->>New: switchover_verify with the shutdown checkpoint
alt proven
L->>New: pg_promote
L->>M: promote_node
L->>Old: becomes a standby of New
else not proven or any earlier failure
L->>Old: take the writes again
Note over L: task ends failed with a reason such as standby_behind
end
- Failure reasons named in the documents:
standby_behind,switchover_unproven,cannot_quiesce,prepared_transactions_pending. The task can be cancelled until the promotion begins. - An immediate stop, a crash or a power loss are not a clean stop: the proof answers
KS006and the promotion is a failover, with possible loss. - The caller must make sure the old primary is not started between reading its control file and the promotion; the extension README names this as a duty of the caller that the function cannot check.
- A planned switchover of the map group is built; it survives a clean stop that outlasts the lease of the task (a stop that outlasts that too is rolled back), and a repeated clean stop of the old primary asks only for the proof that it stopped. A switchover must not run while servers of two versions run, because an older server does not honour the proof-only request (Upgrades). A drain hands the map group over by this switchover. 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.
sequenceDiagram
participant App as Application
participant DB as Ledger table
participant P as kingres.ledger_pending
participant W as Block worker
App->>DB: INSERT UPDATE DELETE and COMMIT
Note over DB: capture trigger writes ledger_entry rows with row hashes
DB->>P: queue the transaction on its first entry
W->>P: every block_interval, read pending transactions by xid
W->>W: Merkle root per transaction, block header with previous hash
W->>DB: write ledger_tx and ledger_blocks, delete processed pending rows
- Triggers (
ENABLE ALWAYS) capture every inserted row; for an updatable table an update or delete writes aDentry for the old version (and the old tuple to the history table) and anIentry for the new one. - A launcher (needs
shared_preload_libraries, starts when recovery has finished, so a standby has none) starts a short-lived worker per database everykingres_ledger.block_interval(default 10 s);ledger_build_block()can also be called by hand and serialises with the worker on the builder lock. A committed transaction is in a block within about one interval, a committed prepared one within six. - The chain is per shard group. The window in which a privileged attacker could alter a committed entry unnoticed is the block interval plus the digest export interval.
sequenceDiagram
participant L as kingresd leader job ledger.round
participant G as Primary of each shard group
participant S as System database kingres_cp
participant K as Signing keys in files
participant P as Publication listener
L->>G: ledger/read head and blocks
L->>L: check the first block read equals the last published one
L->>S: append tiles, store frontier, term guard on every write
L->>K: sign the checkpoint of the chain log
L->>S: store the checkpoint
L->>S: build the aggregate leaf, append, sign, store
P->>S: serve checkpoint, tiles, events, keyring
- The job
ledger.roundwakes every 10 s on the manager leader and runs a round per database with a ledger everypublication.intervalSeconds; it appends at most 9 999 blocks per round. A follower never signs; a leader that loses its term is refused at its first write. - A log never gets a smaller tree and never a second root for a size; signing and retiring a key exclude each other.
- A head below what was published, or a changed published block, stops the log (
diverged), raises the critical alertledgerChainDivergedand repairs nothing. A group that cannot be read is marked stale and the digest sayscomplete: false. - Restore protection: every holder of the key files keeps
published.jsonwith the highest size and root of every log; a database that is behind it signs nothing and raisesledgerSignerUnavailable. After a restore of the system database the operator accepts the loss, and the acceptance is a signed event (ADR 0025); the aggregate log and the events cannot be re-derived, so the logs fork against what was published. - The listener is off by default (
--ledger-publication-listen), serves GET and HEAD only, with no authentication. Tiles, bundles and events are immutable; the checkpoint andkeyring.jsonare cached for 5 seconds. - The private keys are files; the review of the key handling found no path for a secret to a log, an answer or a stored row (Ledger Signing and Publication).
sequenceDiagram
participant J as Jobs on the leader
participant S as kingres_cp ledger_anchor
participant T as Target WORM TSA or OTS
J->>S: enqueue a record for the newest aggregate checkpoint per target
J->>S: write the start of the submission before the call
J->>T: submit with no transaction open and a timeout
T-->>J: receipt
J->>S: store the result by compare and swap on the row version
J->>S: upgrade and monitor pending records
- Jobs:
ledger.anchor.enqueue(everyanchor.intervalSeconds, and onanchorLedgerNow),ledger.anchor.submit(30 s),ledger.anchor.upgrade(60 s),ledger.anchor.monitor(10 s). Only the latest aggregate checkpoint is anchored; an older pending record is superseded. - A record is
anchoredonly when the library of its kind returned a receipt whose evidence its own parser reads back. OpenTimestampsclaimedis shown assubmittedand never counts. Outgoing requests reach exactly the configured host and port, follow no redirect and use no proxy. - RFC 3161 and OpenTimestamps are tested against local fakes only. A job
ledger.anchor.credentials(every 60 s) brings the credentials files of the targets to every holder. The checkanchorsof a ledger verification and a scheduled audit of the publication are not built (the check answers 422unsupported_operation).
sequenceDiagram
participant A as Auditor
participant V as kingres-verify
participant P as Publication or bundle
participant X as Anchor evidence
A->>V: trust file obtained outside the cluster, last state
V->>P: fetch checkpoint, tiles, events
V->>V: check signature against pinned keys
V->>V: recompute root from tiles, prove extension of the stored state
V->>X: check time-stamp token, Bitcoin header, WORM object
V-->>A: result or status 3 when an input is missing
- The verifier uses only the Go standard library and trusts neither the database nor the publisher: it checks signed checkpoints, tile logs, consistency proofs, aggregate digests, bundles, client signatures and anchors against keys and certificates the auditor pins.
monitorpolls a publication and keeps the last checkpoint seen to detect a rollback or a fork. - A check whose input is missing ends with status 3 (could not check), never with success.
- The verifier trusts neither the database nor the publisher; a verification inside the database is relative to a digest that you keep elsewhere (The Verifier).
- https://github.com/KingresDB/Kingres/blob/kingres-18/kingres/README.md
- https://github.com/KingresDB/Kingres/blob/kingres-18/kingres/control-plane/README.md
- https://github.com/KingresDB/Kingres/blob/kingres-18/contrib/kingres_shard/README.md
- https://github.com/KingresDB/Kingres/blob/kingres-18/contrib/kingres_ledger/README.md
- https://github.com/KingresDB/Kingres/blob/kingres-18/kingres/verifier/README.md
- https://github.com/KingresDB/Kingres/blob/kingres-18/kingres/docs/design/ha-phase5-part2.md
- https://github.com/KingresDB/Kingres/blob/kingres-18/kingres/docs/design/ledger-phase7.md
- https://github.com/KingresDB/Kingres/blob/kingres-18/kingres/docs/reviews/2026-11-20-kingresd-failover-increments-4-7.md
- https://github.com/KingresDB/Kingres/blob/kingres-18/kingres/docs/reviews/2026-11-20-kingresd-anchoring-wiring-and-publication-fixes.md
- https://github.com/KingresDB/Kingres/blob/kingres-18/kingres/docs/reviews/2026-11-19-kingres-verifier-publication-and-client-signatures.md
- https://github.com/KingresDB/Kingres/blob/kingres-18/kingres/docs/adr/0021-failover-in-kingresd.md
KingresDB's own code is licensed under AGPL-3.0-only. PostgreSQL code keeps the PostgreSQL License. Copyright of the project's own code: RooyeKhat Media Co. KingresDB is derived from PostgreSQL and is not endorsed by the PostgreSQL project. Repository | Licence | COPYRIGHT
KingresDB
1. Product
- Product Overview and Features
- Status and Roadmap
- User Guide
- Administrator Guide
- REST API Reference
- Web Console
- Console Tour
- Command Line Client
- Extensions
- Limitations and Known Issues
- Release Notes
Features in detail
- Sharding
- Sharding Query Pushdown
- Sharding Table Lifecycle
- High Availability
- Ledger
- Ledger Signing and Publication
- Ledger Anchoring
- The Verifier
- Analytics Extensions
Administration
- Cluster Setup
- Servers Databases and Roles
- Rebalancing
- Configuration
- Memory and Warm-up
- Control Plane and REST API
- Upgrades
- Kubernetes
2. Architecture (arc42)
- Architecture
- Architecture Introduction and Goals
- Architecture Constraints
- Architecture System Context
- Architecture Containers
- Architecture Components
- Architecture Runtime Views Sharding
- Architecture Runtime Views Availability and Ledger
- Architecture Deployment
- Architecture Crosscutting Concepts
- Security Model
- Architecture Decisions
- Architecture Quality Requirements
- Architecture Risks and Technical Debt
- Enterprise Architecture
3. Data architecture
- Data Architecture
- Data Model Sharding
- Data Model Ledger
- Data Model System Database
- Data Model Analytics
- Data Lifecycle
- Backup Restore and PITR
- Data Security
- Data Quality and Integrity
4. Development
- Building from Source
- Development and Testing
- Repository Layout
- Coding Standards
- Branching and Synchronisation
- Testing Strategy
- Review Process
- Release Process
- Contributing
5. Operations