Skip to content

Architecture Runtime Views Availability and Ledger

Mohammad Rasoul Kazemi edited this page Nov 26, 2026 · 2 revisions

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.

1. Leases and fencing (the basis of every promotion)

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).

2. Failover of an ordinary group

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
Loading

Points from the control plane README and the extension README:

  • Stop the old primary is 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 by allowDataLoss, otherwise the task pauses with the alert failoverNeedsDecision (409 failover_needs_decision for 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_rewind or 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 of kingresd. A hard failover that accepts a loss of data needs kingres_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 alert certificateAuthorityUnavailable until the operator restores pki/ca.key and pki/revoked.json from 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 command kingresd -release-map-hold -lost <serverId> -accept-data-loss, run on the server of the old leader while kingresd is 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.

3. Switchover (planned, graceful)

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
Loading
  • 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 KS006 and 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.

4. A ledger block

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
Loading
  • Triggers (ENABLE ALWAYS) capture every inserted row; for an updatable table an update or delete writes a D entry for the old version (and the old tuple to the history table) and an I entry 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 every kingres_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.

5. Signing and publication

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
Loading
  • The job ledger.round wakes every 10 s on the manager leader and runs a round per database with a ledger every publication.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 alert ledgerChainDiverged and repairs nothing. A group that cannot be read is marked stale and the digest says complete: false.
  • Restore protection: every holder of the key files keeps published.json with the highest size and root of every log; a database that is behind it signs nothing and raises ledgerSignerUnavailable. 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 and keyring.json are 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).

6. Anchoring

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
Loading
  • Jobs: ledger.anchor.enqueue (every anchor.intervalSeconds, and on anchorLedgerNow), 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 anchored only when the library of its kind returned a receipt whose evidence its own parser reads back. OpenTimestamps claimed is shown as submitted and 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 check anchors of a ledger verification and a scheduled audit of the publication are not built (the check answers 422 unsupported_operation).

7. Verification by the verifier

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
Loading
  • 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. monitor polls 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).

Sources

KingresDB

1. Product

Features in detail

Administration

2. Architecture (arc42)

3. Data architecture

4. Development

5. Operations

Clone this wiki locally