NEW RasterizedDB 1.1.0 is out: sharding and the gateway, the message broker, roles and row-level security, compression, .NET on NuGet, and the enterprise edition. What's new ›
DOCS / SHARDING GATEWAY / ROUTING AND QUERIES

Routing and queries

What the gateway does with each statement: which run on one shard, which run on every shard and how their results are combined, how transactions, prepared statements and COPY behave, and what else the gateway speaks besides PostgreSQL.

How a statement finds its shard

For each statement the gateway decides, in this order:

  1. A pinned login. With per-user shards, a login locked to a shard sends everything there.
  2. An explicit route key. After SET rdb.route_key = ..., every statement goes to the shard that owns that key, without the SQL being looked at.
  3. The statement's shape. The gateway replaces the statement's literals with placeholders ($1, $2, ...) and asks the home shard once how that shape routes. The shard answers with its own parser and catalogue: which placeholder holds the shard key, or that the shape has none. The gateway remembers the answer for every later statement of the same shape, and routes each by hashing the value in that place. For a prepared statement the shape is its text, and the value is the bound parameter, in text or binary form.
  4. No key. A shape without a key is refused, run on every shard, or gathered, as described below.

The shards decide what is correct, not the gateway. Each shard refuses a statement that would read or write rows outside its own ranges. If the gateway's routing is out of date, a statement is refused and sent again; it never returns another shard's rows as its own.

Statements that run on one shard

A statement runs on one shard when the shard key's value can be read from it:

sql
SELECT * FROM invoices WHERE store_id = 7 AND id = 1001;
SELECT count(*) FROM invoices WHERE store_id = 7;
UPDATE invoices SET total = 12.50 WHERE store_id = 7 AND id = 1001;
DELETE FROM invoices WHERE store_id = 7 AND id = 1001;
INSERT INTO invoices (store_id, id, total, created_at) VALUES (7, 1001, 9.90, '2026-11-27 10:00:00');
SELECT i.id, l.sku FROM invoices i JOIN invoice_lines l ON l.store_id = i.store_id AND l.invoice_id = i.id
  WHERE i.store_id = 7;
  • The key may be compared with = or IN with one value.
  • A join, subquery or CTE over sharded tables that share the same kind of key runs on one shard when the key is compared with a value.
  • An INSERT must give the key value for its row: as a literal, or as a parameter.
  • A statement that names only plain tables, or no table at all (SELECT now(), SELECT nextval('s')), runs on the home shard.
  • Catalogue queries (pg_catalog, information_schema, \d in psql) run on the home shard, which holds the whole schema.

Choosing the shard yourself

SET rdb.route_key sends statements to the shard that owns a key, whatever they say:

sql
SET rdb.route_key = 42;            -- an integer key
SET rdb.route_key = 'u:6f1c3d2e-7a40-4b53-9a3e-1f2d3c4b5a69';   -- a UUID key
SET rdb.route_key = 't:store-7';   -- a text key
SET rdb.route_key = 'store-7';     -- also a text key
SHOW rdb.route_key;
RESET rdb.route_key;

SET LOCAL rdb.route_key sets it for the current transaction only. The shard still refuses any statement that reaches rows it does not own, so this is for statements whose rows are all on that key's shard but whose text does not show the key.

Statements without a key

A read that names a sharded table but no key value is refused by default:

text
ERROR:  statement needs a route key in cluster mode

With unrouted = fan_out in the gateway, or SET rdb.unrouted = fan_out in a session, it runs on every shard and the results are combined:

StatementHow the shards' results are combined
Rows with no ORDER BY, aggregate or DISTINCTEvery shard's rows, one after another, in no particular order.
SELECT count(*) aloneEach shard's count, summed.
Aggregates (count, sum, avg, min, max, array_agg, string_agg, bool_*, every, json_agg), GROUP BY, HAVINGCombined on the home shard by the engine's own aggregation.
SELECT DISTINCTDeduplicated across shards on the home shard.
ORDER BY columns [LIMIT n] [OFFSET m]Merged in order across shards, then the limit and offset applied once. Each sort key is a column or a select-list position (ORDER BY 2), with ASC, DESC, NULLS FIRST or NULLS LAST; a sort by an expression is gathered (below).
Subqueries, CTEs (WITH), joins of several sharded tables, joins with plain tablesBroadcast or gathered (below).
IN (...) lists whose values live on several shardsRun on every shard and combined, like any statement without one key.

Write a window function (... OVER (...)), UNION, INTERSECT or EXCEPT over a sharded table inside a subquery or a CTE, so that the statement is gathered and computed over every shard's rows:

sql
SELECT max(r) FROM (SELECT row_number() OVER (ORDER BY id) AS r FROM invoices) w;

A LIMIT without ORDER BY is applied by each shard, not once: a keyless SELECT * FROM invoices LIMIT 10 can return up to 10 rows from every shard. Add an ORDER BY to get one limit across the cluster.

sql
SET rdb.unrouted = fan_out;
SELECT count(*) FROM invoices;
SELECT store_id, sum(total) FROM invoices GROUP BY store_id ORDER BY store_id;
SELECT id, total FROM invoices ORDER BY total DESC LIMIT 10;
SELECT DISTINCT store_id FROM invoices;

A shape whose results cannot be combined exactly is refused rather than answered approximately. SELECT ... FOR UPDATE without a key is refused.

Broadcast and gather

  • A sharded table inner-joined with small plain tables. Outside a transaction block, the gateway copies the plain tables to every shard for the statement (up to broadcast_max_bytes each, 16 MiB by default), runs the join on every shard, and combines the results as the table above says. SHOW GATEWAY counts these in broadcasts.
  • A sharded table joined with a reference table. Runs on every shard as is: every shard has the reference table.
  • Everything else that no single shard can answer: outer joins with plain tables, joins of several sharded tables, subqueries and CTEs over sharded tables (where window functions belong), sorts by an expression, plain tables too large to copy. The gateway gathers every sharded table the statement names from every shard onto the home shard, into temporary tables, and runs the statement there. The whole tables are copied, not only matching rows, up to gather_max_bytes (256 MiB) in total; past it the statement fails with 54000. Turn gathering off with gather = off.

A prepared statement that broadcasts or gathers must be alone in its batch (Parse, Bind, Describe, Execute, Sync).

Consistency of reads across shards

Outside a transaction block, each shard reads at its own snapshot:

  • A transaction that committed on several shards at once may show on some and not yet on others. The gateway waits (up to 5 seconds) for a two-phase commit it is finishing before it starts a fan-out, so its own commits are not seen half done.
  • SET rdb.consistent_fanout = on makes a fan-out take one snapshot across the shards, so every multi-shard commit is seen wholly or not at all.

Inside a two-phase transaction block, a fan-out sees the block's own writes on every shard.

Writes without a key

An UPDATE or DELETE that names a sharded table but no key value:

  • With two_phase = on and fan-out allowed (unrouted = fan_out), it runs on every shard as one transaction: all shards change or none do.
  • Otherwise it is refused unless the session sets SET rdb.unrouted_writes = each_shard. Then it runs on each shard in turn, each as its own transaction, and the row counts are summed. If a shard fails, the error names the shards where the write already applied; it is not undone there.

RETURNING returns the rows from every shard.

Multi-row INSERT

An INSERT ... VALUES (...), (...) whose rows belong to several shards is split: each row goes to its key's shard. This needs two_phase = on; every shard's part commits together, and a failing row (a duplicate key, say) inserts none of them. RETURNING works. Without two-phase commit it is refused with a message saying so; send one INSERT per shard instead.

A prepared multi-row INSERT is split the same way, each row by its own bound parameters.

Transactions

BEGIN is answered by the gateway and sent to a shard with the transaction's first statement.

Without two-phase commit (the default)

  • A transaction writes on one shard: the shard of its first statement.
  • A plain read of rows on another shard (a SELECT without FOR UPDATE) runs there, outside the block, as a READ COMMITTED read would.
  • A write, or a locking read, that reaches another shard is refused with 0A000 and a message naming two_phase.
  • A statement without a key cannot fan out inside a block (aggregates combined on the home shard excepted, while the block has run nowhere else).
  • SET LOCAL rdb.route_key to a key on another shard than the block's is refused.

With two_phase = on

  • A transaction may read and write on any number of shards.
  • At COMMIT, every shard the transaction wrote on prepares; the decision is recorded on the home shard; then every shard commits. A shard that only read ends at the prepare step. If any shard fails to prepare, all roll back.
  • Keyless reads, aggregates, top-N and joins inside the block see the block's own writes.
  • Every part runs with lock_timeout set to two_phase_lock_timeout_ms (5 s). The gateway also checks every deadlock_check_ms (1 s) for lock cycles across shards and ends the youngest transaction in one with 40P01.
  • If the gateway or a shard fails between the decision and the last commit, the transaction stays prepared on some shards. rdb-shard resolve finishes it from the recorded decision: see High availability.

The shards must be built with the sharding_2pc feature.

Prepared statements

  • Parse, Bind, Describe, Execute and Close are passed on unchanged. A statement prepared on one shard is prepared again on another the first time it runs there; the gateway does this itself.
  • Each Bind is routed by the parameter that holds the shard key.
  • All Binds in one batch (up to a Sync) must reach the same shard. A batch that would reach two is refused with 0A000: put a Sync between them.
  • A prepared statement that fans out or gathers must be alone in its batch: Parse, Bind, Describe, Execute, Sync.
  • Describe goes to the shard the session used last, or the home shard.

COPY

  • COPY ... FROM STDIN into a sharded table is split by row: the gateway reads each row's key field and sends the row to its shard. Text and CSV formats are split (DELIMITER, NULL, HEADER, QUOTE, ESCAPE); binary is refused. With two_phase = on the whole load is one transaction, so a bad row anywhere loads nothing. Without it, SET rdb.split_bulk_writes = on allows the split in autocommit, each shard's part committed on its own, and a failure names the shards that loaded.
  • Into a plain table, it runs on the home shard.
  • Into a reference table, every shard's copy takes every row. Needs two_phase = on.
  • COPY ... TO STDOUT runs where a statement on that table would: a plain table on the home shard. A sharded table cannot be copied out through the gateway; read it with SELECT.
sh
psql "postgresql://rasterized:change-me@127.0.0.1:6432/postgres" \
  -c "\copy invoices (store_id, id, total, created_at) FROM 'invoices.csv' WITH (FORMAT csv, HEADER true)"

Sessions

  • A session-level SET (and RESET, DISCARD ALL) runs on the home shard and on every shard the session has a session on, and is replayed on each shard it reaches later.
  • SET LOCAL and SET TRANSACTION belong to the transaction and go with it.
  • A query string holding several statements separated by ; is sent whole to one shard, routed as a whole. Send statements one at a time.
  • A cancel request (Ctrl+C in psql) is passed to every shard running a statement for the session.

LISTEN and NOTIFY

LISTEN and UNLISTEN are answered by the gateway. NOTIFY runs on whatever shard its transaction runs on and is sent at commit there. The gateway reads every shard's notifications about every 100 ms and delivers each to the sessions listening on its channel in that database, while they are idle, as one server would.

sql
LISTEN jobs;
-- in another session, through any route:
NOTIFY jobs, 'hello';

DISCARD ALL also stops listening.

Cluster-wide SHOW statements

Outside a transaction block, the gateway asks every shard and combines the answers for:

StatementCombined how
SHOW TABLESSizes and row counts of sharded tables summed across shards.
SHOW STORAGE LOCATIONS, SHOW STORAGE PLACEMENTS, SHOW SHARD LOADEvery shard's rows, with a shard column added.
SHOW STORAGE STATS, SHOW DATABASE STATSAmounts summed; figures that differ shown per shard; a shards row added.
SHOW TABLE STATS nameFor a sharded table, summed as above; for a plain table, the home shard's.

SHOW GATEWAY describes the gateway itself (see Administration). Any other SHOW goes to the home shard.

The native protocol

With native_listen set, the gateway also accepts native-protocol (rastcp) clients. Each request goes to the shard named by a route= option among its simple-query options:

OptionKey
route=i<decimal>an integer key, for example route=i42
route=u<32 hex digits>a UUID key
route=t<hex of the UTF-8 text>a text key, for example route=t73746f72652d37 for store-7

A request without the option goes to the home shard.

  • The native front end needs auth = trust and runs every request as native_role in native_database.
  • Every request is its own autocommit statement: there are no transactions through it.
  • rasterizeddb_client does not add a route= option, so its requests through the gateway all reach the home shard. A Rust application can route itself instead: see client-side sharding.

Redis clients

With kv_listen and kv_shards set, the gateway accepts Redis-protocol clients and sends each command to the shard its key hashes to (the key's bytes, hashed as a text key). Each shard must serve the Redis protocol with --kv-port; see KV cache.

text
kv_listen = 0.0.0.0:6380
kv_shards = 0=127.0.0.1:6390,1=127.0.0.1:6391,2=127.0.0.1:6392
  • Commands on one key (GET, SET, INCR, EXPIRE, TTL, hashes, lists, sets, sorted sets) go to that key's shard.
  • DEL, UNLINK, EXISTS, MGET, TOUCH, MSET and MSETNX go to one shard when all their keys are there; keys on several shards get -CROSSSLOT.
  • PING, ECHO and QUIT are answered by the gateway. AUTH, HELLO, SELECT and CLIENT are replayed on each shard connection.
  • Commands that read or change a whole server (KEYS, SCAN, FLUSHALL, INFO, CONFIG, publish/subscribe, MULTI) are refused: they would answer for one shard only.
  • Moving a range between shards does not move cache entries: a moved key starts empty on its new shard.

MySQL and SQL Server clients

The gateway speaks PostgreSQL only. To let MySQL or SQL Server clients use the cluster, run a front-end node: a server started with --frontend-upstream <gateway host:port> and its MySQL and SQL Server ports. It sends each client's session to the gateway, logged in as the client's own role, and keeps a copy of the cluster's schema without rows. MySQL logins to it need TLS.

sh
./rasterizeddb --location ./frontend --protocol both --pg-port 5450 --rdb-port 61190 \
  --pg-cert tls/gateway.pem --pg-key tls/gateway.key \
  --mysql-port 3306 --mssql-port 1433 \
  --frontend-upstream 127.0.0.1:6432

The front-end node needs the cluster's tables in its own catalogue. Seed a new node with rdb-shard ddl --map cluster.map --file schema.sql --frontend 127.0.0.1:61190 --frontend-only (plus --user), and pass --frontend 127.0.0.1:61190 to every later rdb-shard ddl so it gets each change after the shards: see Changing the schema. See MySQL and SQL Server for those protocols.

Errors the gateway returns

SQLSTATEWhen
0A000No shard key where one is needed; a batch or block that would reach two shards; a feature not available through the gateway (schema statements, the function-call protocol, replication connections). The message says which.
42501A pinned login tried to change its routing, or a role not in rebalance_roles ran a rebalance statement.
08006A shard is down, or the home shard is down so the statement could not be classified. Nothing was sent.
08007The connection to a shard was lost after the statement was sent: its outcome is unknown, and it is not retried. Inside a transaction the client connection is closed too.
57P03The statement kept being refused while its range moved, past retries. Try again.
40001A table is fenced for a schema change, or a two-phase commit decision could not be recorded. Try again.
40P01Ended to break a deadlock across shards.
54000A fan-out or gather passed gather_max_bytes, or a pipelined batch passed max_batch_bytes.
53300max_sessions reached.
57P01The gateway is shutting down.
25001A role, privilege or rebalance statement inside a transaction block.
22023A bad value for an rdb.* session setting.
28P01Wrong password or unknown role.

Refusals a shard makes before a statement has any effect (its range is not owned there, has moved, or is fenced for a move) are retried by the gateway up to retries times, in autocommit or on a transaction's first statement, after refreshing its map. The client sees them only when the retries run out.

Limits

See Limits for everything the gateway does not do.

✓ page rendered in 221 µs axum + tera + htmx · no other javascript