Skip to content

Sharding Query Pushdown

Mohammad Rasoul Kazemi edited this page Nov 30, 2026 · 6 revisions

Sharding Query Pushdown

Phase 2b of kingres_shard (now version 0.9) makes common statements fast by letting the shard groups do the work, while keeping one rule: the original row-moving scan answers every query that no faster path accepts. Phase 12 added the repartitioned join, MERGE and approximate count(DISTINCT) on top (below). See Sharding for the concepts.

The complete scan is permanent

A SELECT that spans groups is planned by PostgreSQL as if all the data were on the originating node. Each distributed table is read by a "Kingres Distributed Scan": the local buckets plus one cursor per other group, read in batches of kingres_shard.scan_fetch_size rows (default 1000). Only restrictions are sent; every restriction is applied again to the rows that come back. Joins, aggregates, sorts and subqueries run on the originating node.

ADR 0022 makes this permanent:

  1. A statement that no faster path accepts is answered by the scan.
  2. A faster path that cannot prove its conditions does not raise an error; it leaves the statement to the scan.
  3. Every faster path has a switch, and with all of them off the extension behaves as in phase 2a. Tests compare the answers of a faster path with the scan.
  4. A new table kind is readable through the scan before any pushdown exists for it.

The scan prunes groups: dist_col = <constant or parameter>, IN (...), = ANY (...) and an OR of such clauses leave out groups that cannot own the key. EXPLAIN shows Remote groups: 1 of 2 (pruned by id). It also checks the bucket placement before and after the cursors are opened and raises KS001 when a bucket moved meanwhile. Not supported on a statement that spans groups: row locking (FOR UPDATE) and system columns of a distributed table.

The faster paths

All are on by default and can be switched per session (USERSET). They choose among plans that give the same answer and grant nothing. The planner takes a path only when its cost is lower than the scan's.

Path Switch What the groups do
Closed query kingres_shard.enable_pushdown (master), enable_pushdown_closed Run the whole statement when every output row depends on one group only (a GROUP BY or DISTINCT that contains the distribution key, a join of colocated tables on their keys, with or without a reference table). The node concatenates and applies OFFSET and LIMIT.
Partial aggregation enable_partial_aggregation An aggregate or grouping that is not closed (SELECT count(*) FROM t): each group returns transition states and the node combines them (Finalize ... in EXPLAIN). Built-in aggregates that have a combine function (such as count, sum, avg, min, max, stddev, array_agg, string_agg) and the aggregates of kingres_sketch.
Sort and limit enable_pushdown_sort The groups sort and limit a closed query; the node merges the sorted streams. Only for built-in btree operators and the default or C collation.
Join rows enable_pushdown_join When the statement is not closed but its distributed tables are joined on their keys, the groups return the rows of the join and the node does the rest (window, aggregate, sort).
Objects of extensions shippable_extensions (all, none or a list of names) Functions, operators, types and aggregates of an extension on a list compiled into the library (today kingres_sketch, version 1.0) may be shipped. A function of a user is never shipped.

Example of narrowing: SET kingres_shard.shippable_extensions = 'none'; makes the node read the rows and run a sketch aggregate itself.

EXPLAIN shows Pushed:, Groups: 3 of 3 (local + 2 remote) and Remote SQL:. EXPLAIN (VERBOSE) of a scan says why a statement was not pushed (Pushdown: not used: ...).

Not shipped as a closed query (the scan, or partial aggregation, answers): a grouping or DISTINCT without the key, grouping sets, DISTINCT ON, a function that is not built in and immutable (now()), a sub-select, a CTE, a view, a local table, a table of another colocation group, row-level security, and statements that lock rows. Also answered by the scan: a FULL JOIN with a reference table, aggregates without a combine function in a query that is not closed (json_agg, jsonb_agg, range_agg, xmlagg and others), and DISTINCT or ORDER BY inside an aggregate call. FROM ONLY a distributed table and TABLESAMPLE of one are refused with an error on every path.

Using it

Nothing needs to be called: the planner picks a path by cost. What a user does is look and, when needed, switch. With the table users of Sharding distributed on id:

EXPLAIN SELECT count(*) FROM users;                  -- partial aggregation: a Finalize Aggregate over a Kingres Fragment Scan
EXPLAIN (VERBOSE) SELECT count(*) FROM users;        -- says why a statement was not pushed (Pushdown: not used: ...)
SET kingres_shard.enable_partial_aggregation = off;  -- back to the row-moving scan for this session
SET kingres_shard.enable_pushdown = off;             -- master switch: every faster path off
SET kingres_shard.shippable_extensions = 'none';     -- do not ship kingres_sketch functions

The README of the extension has a section for each path, with the statement shapes it accepts and the reasons it leaves a statement to the scan.

How a group trusts a fragment

A fragment is a text with a marker (kingres:query-fragment, kingres:partial-fragment). The group parses it and checks it against its own rules again. A forged text or a marker the statement does not fit is refused with 0A000; a stale placement or a different extension version is KS001. A fragment runs with the rights of the session role (never the node's), and a table with row-level security is not shipped.

Bulk writes and colocated INSERT ... SELECT

  • Row router (steps 3 and 4). An INSERT whose rows belong to several groups (a multi-row VALUES, an INSERT ... SELECT that is not colocated, a single row with a computed key) and COPY ... FROM are run by the "Kingres Row Router". Each row goes to the group that owns its bucket, in batches, in bounded memory (about two batches per group), in one distributed transaction. Switches: enable_bulk_routing and enable_copy_routing; batch size: insert_batch_rows (default 1000) and insert_batch_bytes (default 1MB). With a switch off the statement is refused.
  • Colocated INSERT ... SELECT (step 5). When the target and the sources are placed together and joined on the key, the statement is shipped whole to every group, which reads and writes its own buckets. Switch: enable_colocated_insert_select. ON CONFLICT DO UPDATE is allowed there.

Still refused: an UPDATE that changes the distribution column, UPDATE ... FROM and DELETE ... USING that read a distributed table and write another table (in 0.1.0 and 0.1.1; from 0.2.0 they run on the groups, see below), and a write that uses a function that is not built in. An INSERT ... SELECT, CREATE TABLE AS and a MERGE into a local table can write an ordinary table from a distributed one.

Repartitioned joins (phase 12)

A join of distributed tables on columns other than their distribution column cannot run on the groups as it stands, because the rows that meet are on different groups. The scan answers it by bringing every row to the node. The repartitioned join moves less: one table is read by the node and its rows are sent to the groups that can join them with their own rows of the other tables, either routed (each row to the group that owns the bucket of the joined column) or broadcast (every row to every asked group). EXPLAIN shows a line such as Repartition: o by cust -> placement of colocation 1 or Repartition: o broadcast (to 3 groups); EXPLAIN (VERBOSE) of a candidate that was not repartitioned says Repartition: not used: <reason>. Switches: kingres_shard.enable_repartition_join (off, on by cost, force for tests) and repartition_max_bytes (default 64 MB, at most 512 MB; a statement that would hold more fails). The scan stays the fallback. In 0.1.0 and 0.1.1 not built, and answered by the scan: a preserved side of a LEFT JOIN that would move, two moved tables, a closed whole-statement fragment above the repartitioned join, and extension objects in the text of a repartitioned join.

Joins and writes in 0.2.0

kingres_shard 0.10 (released in 0.2.0, 2026-11-30) extends this:

  • More shipped tables. A repartitioned join ships up to three tables in one statement, each routed by its join column or sent whole. A table that an outer join preserves can be the one shipped (LEFT, RIGHT and FULL JOIN): the rows go to the group of their key, a NULL key (which joins nothing) goes to exactly one group, so the null-extended row is emitted once. When either side could be shipped, the candidate that ships a nullable table, then the one that moves fewer rows, is tried first. EXPLAIN names every shipped table.
  • Two colocation groups. A join of tables of two colocation groups on their distribution keys, which the scan answered in 0.9, is a repartitioned join: the table of the other group is routed to the placement of the first.
  • Closed statements. When the statement groups or removes duplicates by a distribution key (count(DISTINCT x), aggregates that cannot be split), the groups run all of it above the join.
  • UPDATE ... FROM and DELETE ... USING. Of a distributed table they run on the groups: the tables of its colocation group joined to it on the keys, and reference tables, stay; every other relation is read by the node that runs the statement and sent to the group of its key or to every group, in one distributed transaction, within kingres_shard.write_from_max_source_bytes (default 64MB). kingres_shard.enable_write_from (on by default) turns it off. EXPLAIN shows the path. Of a local table that reads distributed tables, they run on that node and read each distributed table through the distributed scan. RETURNING and parameters work. READ COMMITTED waits for a changed row and re-checks it on its group; REPEATABLE READ fails with 40001.
  • The arm rule. An outer join whose arm has two or more distributed tables that no equality holding for every row of the arm pairs on their keys is not pushed down (the scan answers); the ON clause of the join itself never counts. This replaces the narrower patch of 0.1.1.
  • One version across the cluster. A group still on 0.9 refuses a routed shipped table and the text of a write join; run ALTER EXTENSION kingres_shard UPDATE on every group before relying on these paths, or set enable_repartition_join and enable_write_from to off meanwhile.

Limits are on Limitations and Known Issues.

MERGE on distributed tables (phase 12)

A MERGE runs on the groups in one of five ways, by what its target and its USING clause are: colocated (the whole statement on every group that owns a bucket of the target), a routed source (the node reads the source and sends each row to the group that owns its bucket), a reference-table target, and a local target that reads distributed tables. Every other shape is refused, with the condition named, before any group has run anything. Refused among others: a WITH clause, a sub-select in an expression, a target with a trigger, a rule or row-level security, a MERGE through a view, a volatile value (a sequence, an identity column, random()), and a source that is a join (put the join in a sub-select). Switch: enable_distributed_merge; merge_max_source_bytes (default 64 MB) bounds the source rows the node holds. The statement is atomic across the groups.

Approximate count(DISTINCT)

With kingres_shard.count_distinct_mode = 'approximate' (default exact; count_distinct_error_rate default 0.01) a count(DISTINCT x) over a hash-distributed table is rewritten to kingres_sketch.approx_count_distinct, which takes the partial-aggregation path, so each group returns one sketch instead of its rows. EXPLAIN shows approx_count_distinct(...). It needs kingres_sketch (Analytics Extensions) and a role that may use it. The console turns the setting on per database.

Limitations

The README lists these differences from a single node that pushdown makes visible:

  • A cursor declared without SCROLL over a pushed ordered statement cannot scan backward. Declare it SCROLL.
  • A pushed statement can fail with KS001 where the scan would have answered; the client repeats it.
  • A floating point aggregate can differ in the last digits and between runs; array_agg and string_agg without ORDER BY give an order SQL leaves open.
  • After SET ROLE to a role that cannot log in, a read that spans groups fails (the scan has the same limit).
  • No global snapshot: the groups of a pushed statement read their own snapshots.

Status

Phase 2b (all thirteen steps) is built, and so are the repartitioned join, MERGE and the approximate count(DISTINCT) of phase 12, all in kingres_shard 0.9. The complete scan stays the fallback for every statement (ADR 0022). A global snapshot is not built (phase 8, in design, not built). See Status and Roadmap and Limitations and Known Issues.

Sources

Clone this wiki locally