Skip to content

Architecture Components

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

Architecture Components

Chapter 5 (level 2) of the arc42 structure (Architecture), and level 3 of the C4 model: the components inside three containers, derived from the source directories, the extension READMEs and the design documents. The containers are on Architecture Containers.

kingres_shard

Source: contrib/kingres_shard/src (C), SQL install and update scripts kingres_shard--0.1.sql to kingres_shard--0.9.sql. Version 0.9 is the current one. It must be in shared_preload_libraries (it installs hooks and a background worker).

flowchart TB
    stmt["Incoming statement"]
    subgraph shard["kingres_shard"]
        planner["Planner and utility hooks<br/>planner.c, utility.c, prune.c"]
        catalog["Catalog and bucket map<br/>catalog.c, hashing.c, dist_table.c"]
        scan["Distributed scan<br/>dist_scan.c, remote_scan.c, fragment_scan.c"]
        push["Pushdown paths and joins<br/>pushdown.c, shippable.c, placement_check.c, repartition.c, merge.c, count_distinct.c"]
        router["Row router and batches<br/>row_router.c, batch_sender.c, copy_routed.c"]
        fan["Connections and fan-out<br/>node_conn.c, fanout.c, forward_auth.c"]
        tpc["Two-phase commit and recovery worker<br/>recovery.c, term.c"]
        move["Bucket movement, rebuild, schemas<br/>bucket_move.c, rebuild.c, schema_ddl.c"]
        ha["Standbys, promote, failover support<br/>ha.c, failover.c, node_admin.c"]
    end
    stmt --> planner
    planner --> catalog
    planner --> scan
    planner --> push
    planner --> router
    scan --> fan
    push --> fan
    router --> fan
    fan --> tpc
    move --> catalog
    ha --> catalog
Loading
Component Files Responsibility
Planner and utility hooks planner.c, utility.c, prune.c Look at each statement. With no distributed table, or one shard group, nothing changes. Otherwise a one-key statement goes to the owning group; other shapes use the scan or a pushdown path; DDL on distributed and reference tables is propagated
Catalog and bucket map catalog.c, hashing.c, dist_table.c The tables node, colocation, dist_table, bucket_map, map_version, local_node in the schema kingres, authoritative on the primary of the map group; the bucket of a key is compute_partition_hash_value(key) % bucket_count. See Data Model Sharding
Distributed scan dist_scan.c, remote_scan.c, fragment_scan.c The complete scan: each distributed table is read as local buckets plus one fragment per other group, with every restriction rechecked locally. Permanent (ADR 0022)
Pushdown paths and joins pushdown.c, shippable.c, placement_check.c, repartition.c, merge.c, count_distinct.c Phase 2b: closed queries run whole by every group, partial aggregation, sort and limit, join rows, colocated INSERT ... SELECT, objects of extensions on an allow-list. Phase 12: repartitioned joins on columns other than the distribution column, MERGE on distributed tables, approximate count(DISTINCT). The complete scan stays as the fallback. See Sharding Query Pushdown
Row router row_router.c, batch_sender.c, copy_routed.c Multi-row INSERT, INSERT ... SELECT and COPY FROM that span groups
Connections and fan-out node_conn.c, fanout.c, forward_auth.c Connections to other nodes, parallel calls, the forwarded flag and the proof of an identity forwarded to another node
Two-phase commit and recovery recovery.c, term.c, table kingres.dtx_log Distributed transactions with prepared transactions and a recovery worker on the map group primary; terms for fencing
Bucket movement and distributed schemas bucket_move.c, rebuild.c, schema_ddl.c Moving and splitting a bucket by logical replication; the rebuild of a table of phase 9 (table lifecycle); distributed schemas placed and moved as a unit (phase 11)
High availability support ha.c, failover.c, node_admin.c Standby nodes, promote_node, prepared transactions across a failover, distributed deadlock detection, coordinated restore points
Fault injection fault.c Hook for tests

See Sharding for use and Data Model Sharding for the catalog.

kingres_ledger

Source: contrib/kingres_ledger/src (C), install scripts up to kingres_ledger--0.3.sql. Needs shared_preload_libraries for the block-building workers.

flowchart TB
    dml["INSERT, UPDATE, DELETE on a ledger table"]
    subgraph ledger["kingres_ledger"]
        capture["Capture triggers<br/>capture.c, history.c"]
        guard["Protection and guard<br/>protect.c, guard.c, write.c"]
        hash["Row hash and Merkle tree<br/>row_hash.c, merkle.c"]
        worker["Block workers<br/>worker.c"]
        proof["Digests, proofs, verification<br/>proof.c, kingres_ledger.c"]
        sign["Client signatures<br/>sign.c, ed25519_check.c"]
        read["Reading the chain for publication<br/>part A of version 0.3"]
    end
    dml --> capture
    capture --> hash
    capture --> guard
    worker --> hash
    worker --> proof
    sign --> capture
    proof --> read
Loading
Component Files Responsibility
Capture triggers capture.c, history.c Append a row to kingres.ledger_entry for every change and queue the transaction; for updatable tables, copy the old tuple to a history table
Row hash and Merkle tree row_hash.c, merkle.c Hash format version 1; the tree over each transaction and each block
Block workers worker.c A launcher starts a short-lived worker per database every kingres_ledger.block_interval; the worker calls ledger_build_block() once
Protection protect.c, guard.c, write.c Who can write the ledger tables; protection against the triggers being switched off
Proofs and records proof.c, kingres_ledger.c Digest, inclusion proof, verify functions, recorded digests and verifications, a status view
Client signatures sign.c, ed25519_check.c Registry of client keys, attestation of an entry with an Ed25519 signature, a signature policy of a table
Publication reads functions of version 0.3 part A Three read-only functions from which kingresd publishes the chain

See Ledger for use and Data Model Ledger for the tables.

Analytics extensions

Extension Where Components
kingres_columnar 0.2 contrib/kingres_columnar/src (C) A table access method: storage and encoding (kc_storage.c, kc_encode.c, kc_catalog.c), write path (kc_write.c), scans with skipping and a column scan (kc_scan.c, kc_cscan.c, kc_skip.c), vacuum and reuse of free space (kc_vacuum.c), the access method itself (kc_am.c). Append-only, B-tree indexes, logical decoding of inserts. Its WAL uses the resource manager id 255; kingresd preloads it
kingres_sketch 1.0 contrib/kingres_sketch/src (C) Distinct count (hll.c), top-n (topn.c), percentiles (tdigest.c), the hash (sketch_hash.c); partial aggregation that the shard groups compute
kingres_timepart 0.3 contrib/kingres_timepart (SQL and PL/pgSQL) Time partitions created ahead and dropped by policy, conversion of old partitions to columnar storage and back, policies on user-partitioned distributed tables; the control plane runs the policies (partsched)

See Analytics Extensions.

kingresd

Source: kingres/control-plane (Go module github.com/KingresDB/Kingres/kingres/control-plane), cmd/kingresd and cmd/kingres-watchdog, packages under internal.

flowchart TB
    rest["REST client and web console"]
    peers["Other servers"]
    subgraph kd["kingresd"]
        http["Public API<br/>httpapi, contract, spec, problem, api, auth, webui"]
        internal["Internal API and membership<br/>internalapi, peerclient, peers, membership, pki, gather, fwdproof"]
        engine["Task engine and state<br/>task, fence, sysdb, store, audit, setup, config"]
        inst["Instance manager<br/>instance, cluster, pgconfig, localsettings"]
        ops["Operations<br/>ops, sqlx, scram, rebalance"]
        ha["High availability<br/>lease, liveness, failover, standby, ha, clientproxy"]
        led["Ledger<br/>ledgersign, ledgerkeys, ledgerlog, ledgerround, ledgerpub, ledgerstate, ledgeranchor, anchor"]
        xfer["Data transfer and extension trust<br/>transfer, staging, relay, archive, sqlshape, dumpnorm, importdb, extguard, extgate"]
        mon["Monitoring and scheduling<br/>monitor, scheduler, partsched, leader, clock, serverinfo"]
    end
    rest --> http
    http --> ops
    http --> engine
    peers <--> internal
    internal --> engine
    ops --> inst
    engine --> inst
    ha --> engine
    led --> engine
    xfer --> engine
    http --> xfer
    ops --> xfer
    mon --> engine
Loading
Group Packages Responsibility
Public API httpapi, contract, spec, problem, api, auth, webui Router and guard pipeline; operation table generated from openapi.yaml; RFC 9457 problem documents; role hierarchy, sessions, CSRF and rate limiting; PostgreSQL login; the embedded console with single-page fallback
Internal API and membership internalapi, peerclient, peers, membership, pki, gather, wire, fwdproof Mutual-TLS listener; client of it and forwarding to the leader; joining and removing servers; the cluster certificate authority, renewal and revocation; cluster-wide reads; proof of a forwarded identity
Task engine and state task, fence, sysdb, store, audit, setup, config Resumable tasks with leases and fencing epochs; embedded migrations of the system database; the append-only audit file; the node state machine and the one-time setup token; one table of settings from flags, environment and a JSON file
Instance manager instance, cluster, pgconfig, localsettings, pgconninfo, pgframe initdb, rendering of pg_hba.conf, pg_ident.conf and the managed configuration, pg_ctl; init-cluster; service credentials; PostgreSQL parameters at cluster, group and server level (phase 13)
Operations ops, sqlx, scram, rebalance Operations that change the cluster (roles, grants, databases, tables, network rules, workbench); safe identifier quoting, the only way names reach SQL; SCRAM-SHA-256 verifiers; the rebalance as one task
High availability lease, liveness, failover (with mapgroup and journal), standby, ha, clientproxy, cmd/kingres-watchdog Group leases granted by a majority, liveness of peers, manual and automatic failover and switchover of ordinary groups and of the map group, restore of preferred primaries, the standby agent (placement, base backups, replication slots, synchronous standby names), the client entry point, and the watchdog (a separate program) that stops a primary whose kingresd is gone
Ledger ledgersign, ledgerkeys, ledgerlog, ledgerround, ledgerpub, ledgerstate, ledgeranchor, anchor Signing keys and their state machine; logs, tiles and checkpoints; the collector rounds; storage and serving of the publication; what was published; wiring of the anchoring libraries
Monitoring and scheduling monitor, scheduler, partsched, leader, clock, serverinfo Periodic health checks that raise and clear alerts (also extensionSchemaUntrusted); recurring jobs of the manager leader, among them the runs of time-partitioning policies; the leader read from the catalog; two kinds of time for the lease code; operating-system information
Data transfer and extension trust transfer, staging, relay, archive, sqlshape, dumpnorm, importdb, extguard, extgate Export and import of a table (CSV) and of a database (a zip archive): the staging store of sealed files, the streaming relay that carries an upload or a download of any size to the manager leader, the archive writer and reader, the grammar that decides which statements of an archive may run, the normaliser of pg_dump output, the rule that names the private database of a running import. extguard decides, with one catalog query, whether a KingresDB extension in a user database is the real one before the service role reads or calls anything in its schema, and extgate turns the answer into refusals of the operations (Security Model)
Test support and small helpers clustertest, contracttest, pgtest, testutil, fault, spooftest, sdnotify Multi-process and contract tests, real instances, fault injection; sdnotify sends the systemd readiness notification

The leader of the manager is the kingresd on the server of the map group primary (ADR 0018); recurring jobs and the cluster-wide operations run there, and other servers forward to it.

Sources

Clone this wiki locally