Skip to content

Sharding

Mohammad Rasoul Kazemi edited this page Nov 28, 2026 · 4 revisions

Sharding

Sharding is provided by the extension kingres_shard (version 0.9, built on PostgreSQL 18.7 and 19.0 from one source). It is an extension, not a change to the PostgreSQL executor: it uses the planner, executor and utility hooks. This page explains the concepts and the day-to-day SQL. Reads that run in the shard groups are on Sharding Query Pushdown; changing a table's distribution is on Sharding Table Lifecycle; standbys and failover are on High Availability; moving buckets as an administrator is on Rebalancing.

Concepts

  • Node and shard group. A node is one PostgreSQL instance. Nodes are grouped into shard groups: a group has one primary and, optionally, standbys. A new primary added with add_node is a new group.
  • Bucket. A bucket is a hash partition. A distributed table is, on every node, an ordinary table partitioned BY HASH (<distribution column>) with one partition <table>_b<NNNN> per bucket. A node holds only the partitions of the buckets its group owns. The bucket of a key is compute_partition_hash_value(key) % bucket_count, the value PostgreSQL itself uses to store the row, so routing and storage cannot disagree (ADR 0007). The bucket count of a group is chosen at creation (a bucket can later be split, see below); the setting kingres_shard.default_bucket_count (default 128, range 1 to 4096) gives the count of a new group. The ADR text still mentions 1024 as the default (the ADR says so itself in a later note); the README of the extension is the reference for the code. After a split the bucket of a key is looked up in the layout of the group (each bucket is a hash partition (MODULUS m, REMAINDER r)), and kingres.bucket_for and every router use that lookup.
  • Colocation group. Tables of one colocation group have the same bucket count and the same placement, so rows with the same key are on the same group. A join of colocated tables on their distribution keys can be done inside each group.
  • Distributed table. Hash-distributed over the groups.
  • Distributed schema. A schema whose tables all live in one shard group (one tenant per schema); see below.
  • Reference table. An ordinary table that every node holds in full. Reads are local. A write runs on every node, node after node in node-id order, in one distributed transaction. A write is accepted only if every expression in it is a built-in immutable function or operator on built-in types (so now(), random(), nextval() and user functions are rejected).
  • Catalog. The tables kingres.node, colocation, dist_table, bucket_map, map_version and local_node are authoritative on the primary of the map group (group 0, node 1) and are copied to every other node (ADR 0008). Changes are made on all nodes in one two-phase transaction. Two node-local tables are not copied: kingres.dtx_log (commit decisions) and kingres.pending_node.

Quick start

From the README of the extension:

-- on the first node (it becomes the map group primary, node 1)
CREATE EXTENSION kingres_shard;
SELECT kingres.init_cluster('host1', 5432);

-- add nodes (each new primary is a new shard group)
SELECT kingres.add_node('host2', 5432);
SELECT kingres.add_node('host3', 5432);

-- distribute a table (empty or not), and keep a small one everywhere
CREATE TABLE users (id int, name text, PRIMARY KEY (id));
SELECT kingres.create_distributed_table('users', 'id');
CREATE TABLE countries (code text PRIMARY KEY, name text);
SELECT kingres.create_reference_table('countries');

-- from any node
INSERT INTO users VALUES (42, 'ada');
SELECT name FROM users WHERE id = 42;
SELECT count(*) FROM users;                       -- reads every group
EXPLAIN SELECT name FROM users WHERE id = 42;     -- shows where it runs

-- DDL goes through the map group primary (node 1) and reaches every node
ALTER TABLE users ADD COLUMN email text;
CREATE INDEX users_name_idx ON users (name);

The administration functions are for superusers only (EXECUTE is revoked from PUBLIC). kingres.bucket_for(relation, value) returns the bucket of a key. The views kingres.nodes and kingres.buckets show the topology.

How a statement is routed

The planner hook looks at every statement. With no distributed tables, or a cluster with one shard group, nothing changes.

  • A statement restricted to one key (dist_column = constant or parameter in the top-level AND of the WHERE clause or of an inner join's ON, or the key of a single-row INSERT), with all keys in one colocation group and one bucket, belongs to the group that owns that bucket. If that is this node's group, PostgreSQL's planner runs; otherwise the statement is deparsed and run on the owner through the custom scan "Kingres Remote Statement".
  • A SELECT that spans groups is planned by PostgreSQL as if all the data were here, each distributed table being read by a "Kingres Distributed Scan". Every query shape is therefore correct. See Sharding Query Pushdown for the faster paths.
  • An UPDATE or DELETE of one distributed table that spans groups and can be shipped whole runs on every group that owns buckets of the table, in one two-phase transaction. An UPDATE that assigns the distribution column is refused. Otherwise the statement fails with "this UPDATE/DELETE spans shard groups and cannot be shipped".
  • A write to a reference table runs on every node.
  • An INSERT of rows that belong to several groups, and COPY ... FROM, go through the row router (see Sharding Query Pushdown).
  • A forwarded statement runs in a session with kingres_shard.forwarded = on and never forwards again. A node that finds it does not own a bucket raises KS001; the origin treats KS001 as a stale bucket map, reloads the catalog and retries once.

Guarantees and limits of transactions

  • Atomic commit across nodes. A transaction that writes on two or more nodes commits with two-phase commit: remote writers are prepared, the decision is written to kingres.dtx_log, and then the remote ones are committed. A crash is resolved by kingres.recover_prepared_transactions() and the recovery background worker. Every node needs max_prepared_transactions greater than zero.
  • No global snapshot. Each node commits at its own moment, and a reader can see a distributed transaction on one group before another. In READ COMMITTED a statement that scans two distributed tables can see the same node in two states. Every row read is committed. SERIALIZABLE is serializable per node only. This is ADR 0009: phase 8 (in design, not built) designs atomic visibility for covered read-only statements, which is not a global snapshot. A join of colocated tables on the key is routed to one group when one state of several tables is needed.
  • Distributed deadlocks are detected by the recovery worker of the map group primary and the youngest transaction is cancelled with SQLSTATE 40P01. Waits that are not lock waits are not seen; set lock_timeout for them.
  • Sequences are per node. A serial or identity column hands out numbers from the sequence of the node that runs the statement.
  • A foreign key to a reference table is supported (README of the extension, "Foreign keys that point at a reference table"); other foreign keys are subject to the rules in that README.

Distributed schemas

A database can be sharded by rows, by schemas, or both (kingres.set_sharding_mode; the control plane takes sharding.mode when a database is created). A distributed schema is placed on one shard group and moved as a unit: kingres.distribute_schema(schema, group_id), kingres.move_schema(schema, target_group) and kingres.undistribute_schema(schema); kingres.schema_inventory(schema) says what in a schema cannot be carried. A statement on a distributed schema is run whole on the group that holds it (kingres_shard.enable_schema_routing). The tables of the schema exist on every node, the rows only on the owner. A schema that holds a ledger table is pinned to its group and cannot move (SQLSTATE KS020). A rebalance and a drain plan and move schemas as items of the plan (Rebalancing). The view kingres.schemas lists them.

Moving buckets and rebalancing

The extension has the primitive that moves one bucket, a function that plans a rebalance and the elasticity functions of phase 10. Driving a whole rebalance (order, progress, stop and resume) is done by the control plane, see Rebalancing and Control Plane and REST API.

SELECT kingres.move_bucket(colocation_id, bucket, target_group);   -- returns the id of the move
SELECT * FROM kingres.rebalance_plan(10);                          -- the moves that even out the buckets per group
SELECT kingres.set_node_property(node_id, false);                  -- should_have_shards = false: the plan drains the group
SELECT kingres.cancel_bucket_move(move_id);
SELECT kingres.resume_bucket_moves();
SELECT * FROM kingres.check_cluster();                             -- one row per inconsistency
SELECT * FROM kingres.plan_rebalance('by_disk_size', 0.1);         -- a plan with a strategy, a threshold and weights
SELECT kingres.split_bucket(colocation_id, bucket, 2);             -- split a bucket into two (cannot be undone)
SELECT * FROM kingres.move_progress();                             -- unfinished moves with their percent

A move runs on the map group primary as a superuser in a READ COMMITTED session. Its phases are preparing, copying (a logical replication slot, publication and subscription, with an initial copy into standalone tables that are not attached), catching_up, switching (one two-phase transaction) and cleaning (the old tables are kept for kingres_shard.move_cleanup_delay, 10 minutes by default). All tables of the colocation group move together; reference tables do not move.

Only the switch blocks. On the source node, writers of the tables of the colocation group wait while the switch runs; readers go on. The locks are tried for, never queued for: if a table cannot be locked, the attempt is abandoned and retried after a pause, up to kingres_shard.move_switch_attempts (20), and then the move fails and names the sessions in the way. A scan or a fan-out write that meets a switch in the middle fails with KS001 and the client repeats it.

Requirements: wal_level = logical on every node, room in max_replication_slots, max_wal_senders and max_logical_replication_workers, a primary key or REPLICA IDENTITY FULL on every table of the group, the same PostgreSQL major on source and target, and no DDL on the group during the move (DDL on the tables of a group that is being moved is refused).

Limits: one bucket per call. A move does not change the bucket count (alter_distributed_table does, see Sharding Table Lifecycle). Moves of different buckets can run together in the extension, but the control plane runs one move at a time (Rebalancing). A move does not drop an old copy that objects of its owner depend on (a view, a foreign key, a function on its row type): the copy stays, check_cluster() reports orphan_blocked, and the next cleanup finishes the move after the dependents are dropped.

Phase 10 in the extension. kingres.set_node_property(node_id, should_have_shards, weight) sets a weight (above 0, at most 1000). kingres.plan_rebalance(strategy, threshold, ...) plans by_bucket_count or by_disk_size and knows weights and drains; kingres.group_load() shows the load per group; kingres.drain_status() says when a group is drained. kingres.split_bucket(colocation_id, bucket, parts, verify) splits one bucket into several (refused for a table without a primary key and for a colocation group with a columnar table; cancel_bucket_split, resume_bucket_splits and cleanup_bucket_splits go with it). kingres.move_progress() gives the percent of each unfinished move.

SQL function reference

Functions of kingres_shard 0.9 in schema kingres, from the install script and the "SQL interface" section of the README. Names that start with internal_ are used by the extension and the control plane and are not listed. Unless a row says otherwise, a function is for superusers and runs on the map group primary. Functions of the table lifecycle are in the table on Sharding Table Lifecycle.

Function Arguments Purpose
version none The KingresDB product version (text).
init_cluster host text, port int Registers this node as node 1 of group 0.
add_node host text, port int, group_id int DEFAULT NULL, role text DEFAULT 'primary' Registers a node (a new group when group_id is null) and copies the catalog and tables to it in one two-phase transaction; a standby is only registered and must name the group of its primary. Returns the node id.
remove_node node_id int Unregisters a node whose group owns no buckets (a primary that has standbys: not before them).
sync_catalog none Pushes the catalog to every active primary node, atomically.
create_distributed_table relation regclass, dist_column name, colocate_with regclass DEFAULT NULL, bucket_count int DEFAULT NULL Distributes a table, empty or not.
create_reference_table relation regclass Makes a table a reference table on every node.
bucket_for relation regclass, value anyelement or colocation_id int, value anyelement The bucket of a key (int).
set_node_property node_id int, should_have_shards bool Whether a node accepts buckets; false makes the rebalance plan drain its group.
rebalance_plan max_moves int DEFAULT NULL The moves that even out the buckets per shard group, in order; changes nothing.
move_bucket colocation_id int, bucket int, target_group int Moves one bucket with logical replication; returns the id of the move.
resume_bucket_moves none Undoes moves interrupted before the switch and finishes those that switched; returns how many it resolved.
cancel_bucket_move move_id bigint Stops a move that has not reached the switch and undoes it.
cleanup_moved_buckets force bool DEFAULT false Drops the old tables of moves whose move_cleanup_delay is over (all with force).
check_cluster p_prepared_older_than interval DEFAULT '5 minutes' One row per inconsistency of the cluster (catalogs, partitions against the bucket map, leftovers of moves and table operations, old prepared transactions); no row when consistent.
recover_prepared_transactions none Commits or rolls back the prepared transactions this node originated; returns how many. Not on a standby.
detect_distributed_deadlocks none One pass of the deadlock detector (the recovery worker runs it); returns the number of transactions cancelled.
rotate_secret none Replaces the secret behind the tokens of node-to-node sessions on every active primary; refused while a distributed transaction is prepared.
create_restore_point name text A restore point on every primary with no distributed transaction half way through its commit.
promote_node node_id int After a standby was promoted in PostgreSQL, makes it the primary of its group in the catalog; returns jsonb. See High Availability.
promote_map_group_without_majority node_id int, acknowledgement text The operator's way out when the majority rule refuses for ever; needs an exact acknowledgement text given in the README. See High Availability.
standby_status, standby_name_matches, switchover_mark, switchover_replayed, switchover_verify see the README Standby state and the proof of a planned switchover. See High Availability.
forget_dropped_tables none Removes catalog rows of dropped distributed tables.
plan_rebalance, group_load, drain_status, move_progress, bucket_range see the README Plans with strategy, threshold and weights; load per group; whether a group is drained; progress of moves; the modulus and remainder of a bucket.
split_bucket, cancel_bucket_split, resume_bucket_splits, cleanup_bucket_splits see the README Split a bucket into several and manage the split.
set_sharding_mode, distribute_schema, undistribute_schema, alter_distributed_schema, move_schema, schema_inventory, schemas_on_group see the README Distributed schemas.
create_partition, drop_partition, detach_partition, attach_partition, partition_leaves, partition_leaf_budget, partition_leaf_storage, begin_leaf_conversion, renew_leaf_conversion, end_leaf_conversion see the README Partitions of a user-partitioned distributed table; the leaf budget and the claim used by kingres_timepart. See Sharding Table Lifecycle and Analytics Extensions.

Views: kingres.nodes (the node table plus is_local), kingres.buckets (every bucket with its group, owning node, state and partition size), kingres.bucket_move_status, kingres.catalog_status (catalog term and whether this node was superseded), kingres.partitions, kingres.table_operations, kingres.schemas.

Error codes (SQLSTATE)

The error codes of the extension are in the class KS. The README table gives the action of the caller for each; the main ones:

SQLSTATE Meaning What to do
KS001 stale bucket map (also a failover of a group during a read) Repeat the statement.
KS002 the sender's catalog is superseded by a newer catalog term Stop sending from that node; sync_catalog() brings it up to date.
KS004 a bucket move gave up waiting for its switch The move goes back to catching up by itself.
KS005 a participant could not get its own standby to confirm durability Fix that node's standby list or standby, repeat; nothing was committed.
KS006 a planned switchover cannot be proven loss-free Treat the promotion as a failover.
KS007 a node accepted the session and did not answer one statement within node_timeout Do not repeat against that node: probe it, fence or restart it.
KS008 another call that changes the catalog is running on this node Nothing was changed; repeat later.
KS009 the node cannot commit: its synchronous standbys do not confirm Fix the list or the standby, repeat.
KS010 the call went to the wrong node (not the map group primary, a superseded one, and so on) Send it where the message says.
KS011 the node to promote is still in recovery Promote it in PostgreSQL first, repeat.
KS012 promoting would not be safe (a newer catalog term, or only a minority reachable) Not a retry: a decision of the operator.
KS013 distributed transactions are in doubt Run recovery, wait until check_cluster() shows none, repeat.
KS014 two nodes hold cluster secrets that do not match Not a retry; the README says how to tell which node is behind.
KS015 the call took longer than kingres_shard.control_call_timeout as a whole Repeat with a longer or no limit; it does not say a node is dead.
KS016 the table is a ledger table (or the history table of one): refused by create_distributed_table, create_reference_table and their online variants Keep it an ordinary table.
KS017 no shard group may receive buckets Register a node or set should_have_shards.
KS018 the sizes of the buckets of a group cannot be read, so a plan by disk size does not guess Repeat later.
KS019 the bucket or its colocation group is busy for a split Wait for the other operation, repeat.
KS020 the schema holds a ledger table and is pinned to its group Not a retry.
KS021 the verification of a table operation failed; the old copy is kept Not a retry.
KS022 a function that changes the catalog was called on a node that is not the map group primary Call it on the map group primary.

KS003 is raised only inside a cancelled bucket move and no caller sees it. A distributed deadlock victim gets 40P01. A split of a table without a primary key is refused with 0A000. kingresd decides on KS017 to KS022 by the code, not by the wording. See Troubleshooting.

Settings

Settings that exist in the source (prefix kingres_shard.; the README of the extension gives the meaning of each):

Setting Default
default_bucket_count 128
enable_routing (superuser only) on
enable_distributed_scan on
scan_fetch_size 1000
move_catchup_threshold 1MB
move_switch_timeout, move_switch_attempts, move_cleanup_delay 10s, 20, 10min
recovery_interval 30s (0 disables the recovery worker)
deadlock_check_interval, deadlock_confirm_delay 2s, 200ms
decision_retention 300s
node_conninfo, node_connect_timeout, node_timeout empty, 5s, 60s
control_call_timeout 0 (no limit)
enable_schema_routing on
max_distributed_schemas 10000
max_partition_leaves 8192
min_bucket_cost 1MB

The settings of the pushdown paths, the row router and the table lifecycle are on their own pages. See also Configuration.

Status

Built, in kingres_shard 0.9 (see Status and Roadmap for the state of every phase):

  • Phases 0 to 2 (sharding MVP, distributed DML and DDL, two-phase commit, reference tables).
  • Phase 2b (query pushdown, row router, colocated joins): Sharding Query Pushdown.
  • Phase 4 (bucket movement and rebalancing) and phase 10 (elasticity: strategies, weights, drain, bucket split): Rebalancing.
  • Phase 5 (high availability): High Availability.
  • Phase 9 (table lifecycle): Sharding Table Lifecycle.
  • Phase 11 (distributed schemas) and the sharding part of phase 12 (repartitioned joins, MERGE, columnar and time-partitioned distributed tables, approximate count(DISTINCT)): Sharding Query Pushdown and Analytics Extensions.

Not built: a global snapshot across shard groups (phase 8, in design, not built). The limits that still hold are on Limitations and Known Issues.

Sources

Clone this wiki locally