Repository navigation
Architecture Runtime Views Sharding
This page is the runtime view (arc42 chapter 6) of the sharding part of KingresDB: how one distributed query, one distributed write and one bucket move run, step by step. The static structure is on Architecture Containers and Architecture Components; the concepts are on Sharding, Sharding Query Pushdown and Rebalancing. The failover, switchover and ledger flows are on Architecture Runtime Views Availability and Ledger.
All three flows below are built. The limits that remain are on Architecture Risks and Technical Debt and Limitations and Known Issues.
Every node can receive any statement. The planner hook of kingres_shard looks at it; without distributed tables, or on a cluster with one shard group, PostgreSQL plans it as usual. Otherwise there are four outcomes, tried from the cheapest to the most general. The last one, the row-moving distributed scan, is permanent: it answers every query shape, and a faster path that cannot prove its conditions leaves the statement to it (ADR 0022).
sequenceDiagram
participant C as Client
participant O as Origin node
participant G1 as Shard group A
participant G2 as Shard group B
C->>O: SELECT
Note over O: planner hook reads the placement from the local catalog copy
alt key restricted to one bucket
O->>G1: routed statement "Kingres Remote Statement"
G1-->>O: rows
else a faster path accepts the statement
Note over O: closed query, partial aggregation, sort and limit, or join rows
O->>G1: fragment with marker
O->>G2: fragment with marker
G1-->>O: rows or transition states
G2-->>O: rows or transition states
Note over O: merge, finalize, OFFSET and LIMIT
else no faster path
O->>G1: placement check, open cursor, fetch in batches
O->>G2: placement check, open cursor, fetch in batches
G1-->>O: rows
G2-->>O: rows
O->>G2: placement check again
Note over O: all restrictions are applied again here, joins and aggregates run here
end
O-->>C: result
What decides the branch, from the extension README and Sharding Query Pushdown:
-
Single group. Every distributed table is restricted to one key (
dist_column = constant or parameterin the top-levelAND), all in one colocation group and one bucket. If the bucket belongs to the origin's group, PostgreSQL's planner runs; otherwise the statement is deparsed and run on the owner. -
Faster paths (all on by default, each with a switch, the planner takes one only when its cost is lower than the scan's): closed query (every output row depends on one group), partial aggregation, sort and limit of a closed query, join rows, shipping of objects of the extension
kingres_sketch, and (phase 12) a repartitioned join that moves one table to join on a column other than the distribution column (from 0.2.0: up to three tables, also the preserved side of an outer join, and the writesUPDATE ... FROMandDELETE ... USING; see Sharding Query Pushdown). With all switches off the extension behaves as in phase 2a;EXPLAIN (VERBOSE)says why a statement was not pushed. -
Distributed scan. One "Kingres Distributed Scan" per distributed table: the local buckets plus one cursor per other group, read in batches of
kingres_shard.scan_fetch_size. Groups that cannot own the key are pruned (EXPLAINshowsRemote groups: 1 of 2). -
Stale map. Before a cursor is opened and again after, the scan asks every node for the hash of the placement of its colocation group and for the identity of its partitions. A difference raises
KS001; the origin reloads the catalog from the map group and retries once when no earlier statement of the transaction ran on that node. Otherwise the client repeats the statement. -
Trust in a fragment. A group parses the fragment again and checks it against its own rules; a forged text or a marker the statement does not fit is refused with
0A000; a stale placement or a different extension version isKS001. A fragment runs with the rights of the session role, never of the node.
Known limits that the flow cannot remove: no global snapshot, so each group reads at its own snapshot and a cross-group read can see a partially committed distributed transaction (ADR 0009; atomic visibility of covered read-only statements is phase 8, in design and not built).
A transaction that writes on two or more nodes commits with two-phase commit. The decision is a row in the node-local table kingres.dtx_log, written by the committing transaction itself, so it is atomic with the local commit.
sequenceDiagram
participant C as Client
participant O as Origin node
participant R as Remote group
C->>O: BEGIN and writes
O->>R: routed writes in a remote transaction
C->>O: COMMIT
O->>R: PREPARE TRANSACTION with a tagged name
R-->>O: prepared
Note over O: decision row in kingres.dtx_log, local commit flushed before the first COMMIT PREPARED
O->>R: COMMIT PREPARED
R-->>O: committed
O-->>C: COMMIT
Rules the extension README states for this flow:
- The local commit is flushed before the first
COMMIT PREPAREDwhateversynchronous_commitsays; a session withofforlocalhas it raised toonfor such a transaction, so the commit also waits for the synchronous standbys of the origin and the decision survives a failover. - The name of a prepared transaction is
kingres_h<origin group>_<timeline>_<pid>_<xid>_<target node>[_<n>]_<tag>; the tag is an HMAC of the rest with the cluster secret, so recovery touches only names it can verify. A name with a wrong tag is reported bycheck_cluster()asforeign_prepared_transaction. - A participant that does not answer
COMMIT PREPAREDwithinkingres_shard.node_timeoutis left to recovery with a warning; later participants are not delayed. - Every node needs
max_prepared_transactionsgreater than zero.
sequenceDiagram
participant W as Recovery worker
participant N as Node with a prepared transaction
participant L as dtx_log of the origin group
W->>N: list prepared transactions with a valid tag
W->>L: look up the decision with a fresh snapshot
alt decision row exists
W->>N: COMMIT PREPARED
else no row and origin no longer in progress
W->>N: ROLLBACK PREPARED
end
- A crash at any point is resolved by
kingres.recover_prepared_transactions()and by the recovery background worker: a prepared transaction whose origin did not commit is rolled back, one whose decision is indtx_logis committed. - The name carries the origin group, not the node, so a standby that became the primary of the group resolves what the old primary started. For a transaction of an earlier timeline, a decision row means commit and no row means rollback; such a rollback is recorded in
kingres.dtx_incidentand shown bycheck_cluster()asprepared_rolled_back_after_failover(kept 30 days). - With a synchronous standby a distributed transaction commits or aborts on every node across a failover. With an asynchronous standby it can be half committed, and the extension says so afterwards.
- Distributed deadlocks (a cycle across nodes that no node sees) are found by the recovery worker of the map group primary every
kingres_shard.deadlock_check_intervalseconds; the youngest transaction of the cycle is cancelled with40P01. - Control calls such as
add_node,remove_node,rotate_secretandsync_catalogare themselves two-phase transactions over all nodes under one lock onkingres.map_version.
The unit is one bucket of one colocation group: the partitions of every table of the group move together. The extension has the primitive kingres.move_bucket(colocation_id, bucket, target_group); the control plane (internal/rebalance) decides which bucket moves and drives a rebalance as one task on the manager leader, one move at a time.
sequenceDiagram
participant K as kingresd on the leader
participant M as Map group primary
participant S as Source group
participant T as Target group
K->>M: SELECT kingres.move_bucket
M->>S: preconditions, then bucket set to moving on every node
M->>S: publication of the bucket and a logical slot
M->>T: standalone copies, subscription with initial copy
S-->>T: initial copy and changes
Note over M: catching_up until tables are ready and a marker row has arrived
M->>S: lock tables, try NOWAIT, insert marker row
M->>T: lock tables, try NOWAIT
Note over M,T: switching is one two-phase transaction over map group, source and target
M->>S: detach the partitions
M->>T: attach the copies
M-->>K: id of the move
Note over M,S: cleaning drops subscription, slot and publication, orphans after move_cleanup_delay
Phases, recorded in kingres.bucket_move.phase before the action they announce: preparing, copying, catching_up, switching, cleaning, done.
-
Completeness. The initial copy is complete when every published table is
readyinpg_subscription_rel. The subscriber has replayed up to the switch point when a marker row, inserted on the source after the bucket's tables are locked against writes, has arrived on the target; logical replication applies in commit order, so the marker arrives after every earlier write. -
What blocks. Only the switch, normally for tens of milliseconds. Writers of the group's tables on the source and on the target wait; readers go on. Locks are tried for with
NOWAIT, never queued for: a set that cannot be had abandons the attempt and the move goes back tocatching_upwith a pause that doubles from 0.2 s to 10 s, up tokingres_shard.move_switch_attemptsattempts. -
Stale map. A statement routed with the old map that reaches the source after the switch gets
KS001; a scan compares the placement and the partition identity before and after, so each bucket is read or written once, by its owner. -
Refused meanwhile. DDL on the tables of the group and the creation of a table in it are refused while a move is unfinished;
remove_node()refuses a group that takes part in a move. -
Control plane side. The rebalance task has the steps
Check that the cluster can rebalance,Compute the plan,Move bucketsandWrite the report; the plan comes fromkingres.rebalance_plan()and is made again before every move. State is inkingres_cp.rebalance_runandrebalance_move; every write proves the task's lease and epoch, so a leader that lost the lease records nothing and starts no move. A failed move is retried after 30 s times its failures, up to three tries. After a restart or a change of leader the new leader's engine claims the task under a new epoch and settles a half-done move throughresume_bucket_moves(). -
Stop.
stopRebalanceasks the extension to cancel the move in flight (before the switch it is undone; a switching move is not interrupted); the task is paused andstartRebalancecontinues it. - A failover during a move fails and undoes the move, because the slot is not on the standby; a failover is refused while a rebalance is pending or running.
Elasticity (phase 10) is built on top of this: the strategies by bucket count and by disk size, weights per server, an automatic mode (off by default), the drain of a server (which also hands the map group over by a planned switchover and moves the distributed schemas of the server), and the split of a bucket. A rebalance runs one move at a time by default (maxConcurrentMoves is accepted and recorded), and it is held back while a standby lags by more than maxStandbyLagBytes. A rebalance and a drain plan and move distributed schemas as items of the plan. A bucket move waits for long transactions at its switch.
- https://github.com/KingresDB/Kingres/blob/kingres-18/contrib/kingres_shard/README.md
- https://github.com/KingresDB/Kingres/blob/kingres-18/kingres/docs/design/shard-phase2b.md
- https://github.com/KingresDB/Kingres/blob/kingres-18/kingres/docs/design/shard-phase4.md
- https://github.com/KingresDB/Kingres/blob/kingres-18/kingres/control-plane/README.md
- https://github.com/KingresDB/Kingres/blob/kingres-18/kingres/docs/adr/0009-two-phase-commit-no-global-snapshot.md
- https://github.com/KingresDB/Kingres/blob/kingres-18/kingres/docs/adr/0022-the-complete-scan-stays.md
- https://github.com/KingresDB/Kingres/blob/kingres-18/kingres/README.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
- 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
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