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 / SHARDED TABLES

Sharded tables

How to lay out a schema for a sharded cluster: which tables to shard, how to choose the shard key, and how to change the schema on every shard.

Three kinds of tables

Every shard holds the whole schema. What differs is where the rows live.

KindDeclared withRows liveUse it for
ShardedPARTITION BY HASH (key)Spread over the shards by the keyLarge tables that split by tenant, store, account, customer
Plain (global)an ordinary CREATE TABLEOn the home shard onlySmall tables that are not per tenant: settings, plans, lookup data that changes
Referencean ordinary CREATE TABLE, then SHARD REFERENCE TABLE name on every shardA full copy on every shardSmall, read-mostly tables joined with sharded ones: countries, currencies, product categories
sql
-- sharded by store_id
CREATE TABLE invoices (
  store_id BIGINT NOT NULL,
  id BIGINT NOT NULL,
  total NUMERIC(12,2) NOT NULL,
  created_at TIMESTAMP NOT NULL,
  PRIMARY KEY (store_id, id)
) PARTITION BY HASH (store_id);

-- plain: lives on the home shard
CREATE TABLE plans (id INT PRIMARY KEY, name TEXT NOT NULL, monthly_price NUMERIC(8,2) NOT NULL);

-- reference: a copy on every shard
CREATE TABLE currencies (code TEXT PRIMARY KEY, name TEXT NOT NULL);
SHARD REFERENCE TABLE currencies;

These statements run on each shard, not through the gateway: see Changing the schema.

Sharded tables

A partitioned table is a sharded table. The first column of its PARTITION BY HASH (...) list is its shard key. Each shard splits its own share of the table into partitions as any partitioned table does; see Partitioning.

  • A statement that names one key value (WHERE store_id = 7, INSERT ... VALUES (7, ...)) runs on the one shard that owns it.
  • A statement that names none runs on every shard, when the gateway allows it.

Plain tables

A table that is not partitioned lives on the home shard (home_shard, by default the lowest shard id). The other shards have the table, empty: through the gateway every read and write of it goes to the home shard.

A statement that joins a plain table with a sharded table cannot run on one shard, since only the home shard has the plain table's rows. The gateway answers such reads by copying a small plain table to every shard for the statement, or by gathering the sharded rows onto the home shard; a write that mixes them is refused. If a plain table is joined with sharded ones often, make it a reference table.

Reference tables

A reference table has a full copy on every shard, so a keyed statement can join it on whatever shard its key routes to.

  • Reads of a reference table are answered by one shard.
  • Writes go to every shard. With two_phase = on in the gateway, every copy changes or none does. Without it, a write needs SET rdb.unrouted_writes = each_shard, and each shard's copy is changed in turn, not atomically.
  • COPY into a reference table loads every copy, and needs two_phase = on.
  • SHARD UNREFERENCE TABLE name makes it a plain table again.

Mark a table as a reference table on every shard right after creating it, before any statement for it goes through a gateway:

sh
export RDB_PASSWORD='change-me'
./rdb-shard exec --map cluster.map --sql "SHARD REFERENCE TABLE currencies" \
  --user rasterized --database postgres \
  --native 0=127.0.0.1:61180 --native 1=127.0.0.1:61181 --native 2=127.0.0.1:61182

The gateway remembers how each statement shape routes. If a gateway has already routed statements for a table that you then mark or unmark as a reference table, restart that gateway so it forgets them.

Choosing the shard key

The shard key decides which statements run on one shard and which have to visit them all.

  • Pick the column almost every statement names. In a multi-tenant application that is the tenant id. A statement without it costs a visit to every shard.
  • Use one key, of one kind, across the tables of a tenant. Keys hash by kind: integer types (SMALLINT, INT, BIGINT), text (TEXT, VARCHAR) and UUID. The same value of the same kind lands on the same shard in every table, so an invoice and its lines with the same store_id are on one shard, and a join on store_id that names one store runs there.
  • Expect one key value to stay on one shard. A key value is one block of the key space, and a block is never split between shards. A tenant that outgrows a shard cannot be spread further by the shard key.
  • Spread the load. Many key values with similar sizes spread well. A handful of huge tenants make shards uneven; you can move a big tenant onto a shard of its own (see Moving data).
  • Do not use a column that changes. A row's shard follows its key value; give it a value that stays.

Supplying the key on every write

Every INSERT into a sharded table must give the shard key's value, as a literal or a bound parameter, so the gateway knows where the row goes. An INSERT that leaves the key to a default (SERIAL, DEFAULT nextval(...)) or takes it from INSERT ... SELECT is refused with 0A000 statement needs a route key in cluster mode.

Generate keys in the application: a UUID, or an id your application already owns (the tenant's id).

Unique keys

Each shard checks PRIMARY KEY and UNIQUE constraints over its own rows. A constraint that includes the shard key is unique across the cluster, because equal keys land on the same shard. One that does not include it can be broken across shards without an error. Put the shard key first in every primary key and unique constraint of a sharded table:

sql
CREATE TABLE invoice_lines (
  store_id BIGINT NOT NULL,
  invoice_id BIGINT NOT NULL,
  line_no INT NOT NULL,
  sku TEXT NOT NULL,
  qty INT NOT NULL,
  PRIMARY KEY (store_id, invoice_id, line_no)
) PARTITION BY HASH (store_id);

Sequences

A sequence belongs to the shard that uses it:

  • SELECT nextval('invoice_numbers') through the gateway runs on the home shard, so standalone calls share one sequence.
  • A SERIAL column, or a DEFAULT nextval(...), on a sharded table is filled in by the shard that stores the row, from that shard's own sequence. Values are unique on each shard but repeat across shards.

Do not rely on a sequence for ids that must be unique across the cluster. Use UUIDs, or pair the value with the shard key (PRIMARY KEY (store_id, id)).

Changing the schema

Schema statements (CREATE, ALTER, DROP, TRUNCATE, CREATE INDEX and the like) do not go through the gateway: it refuses them with 0A000 statement needs a route key in cluster mode. Apply them to every shard with rdb-shard ddl.

rdb-shard ddl

Write the change to a file, and name every table it changes with --table:

sh
cat > add-discount.sql <<'EOF'
ALTER TABLE invoices ADD COLUMN discount NUMERIC(12,2)
EOF

export RDB_PASSWORD='change-me'
./rdb-shard ddl --map cluster.map --file add-discount.sql --table invoices \
  --user rasterized --database postgres \
  --native 0=127.0.0.1:61180 --native 1=127.0.0.1:61181 --native 2=127.0.0.1:61182
text
shard 0: applied
shard 1: applied
shard 2: applied
invoices: one fingerprint on every shard
schema epoch 2 on every shard; the fence on invoices is lifted

What it does, in order:

  1. Tries the change on every shard inside a transaction it rolls back. If any shard would refuse it, it stops and no shard is changed. A statement that cannot run inside a transaction is applied without this dry run, and the tool says so.
  2. Fences the named tables on every shard (shard.ddl_fence). Until the change is done, a statement that touches them is refused with 40001 and the message that the schema changed. Clients should retry it.
  3. Applies the change on the home shard first (--home, by default the lowest shard id), then on every other shard in id order, recording each shard in a state file as it goes.
  4. Compares the schemas. Each named table's schema fingerprint must be the same on every shard.
  5. Raises the schema epoch on every shard, so gateways stop using what they remembered about the old schema, and lifts the fence.

If a shard fails in step 3, the tool stops, names the shard and the shards that already have the change, and keeps the state file (--state, by default the DDL file's name plus .state). Fix the cause and run the same command again: it resumes, skipping the shards already done. If the fingerprints differ in step 4, it stops with PARTIAL: <table> has fingerprint ... on shard ... but ... on shard ...; the tables stay fenced until you make the shards agree and run it again.

FlagDefaultWhat it does
--map MAPrequiredThe cluster map.
--file FILErequiredThe schema statement to apply.
--table TABLErequiredA table the change creates or alters. Repeat it for each.
--home SHARDthe lowest shard idThe shard applied first.
--state STATEFILE.stateWhere progress is recorded, for resuming.
--frontend ADDRnoneA front-end node to apply the change to once every shard has it. Repeatable.
--frontend-onlyoffApply the file to the --frontend nodes only (a new front-end node).

It also takes the common rdb-shard flags (--user, --database, --native, --ca, --pin, --accept-any): see the rdb-shard reference.

New tables

Create a new table the same way. Name it with --table:

sh
cat > create-items.sql <<'EOF'
CREATE TABLE items (store_id BIGINT NOT NULL, id BIGINT NOT NULL, name TEXT NOT NULL, PRIMARY KEY (store_id, id)) PARTITION BY HASH (store_id)
EOF
./rdb-shard ddl --map cluster.map --file create-items.sql --table items \
  --user rasterized --database postgres \
  --native 0=127.0.0.1:61180 --native 1=127.0.0.1:61181 --native 2=127.0.0.1:61182

When a cluster is first set up and nothing uses the tables yet, you can also create them by connecting to each shard in turn, as in Install and run.

Dropping a table

rdb-shard ddl checks the named tables' schemas after the change, which a dropped table no longer has. Drop a table on every shard with rdb-shard exec instead, after the application has stopped using it:

sh
./rdb-shard exec --map cluster.map --sql "DROP TABLE old_invoices" \
  --user rasterized --database postgres \
  --native 0=127.0.0.1:61180 --native 1=127.0.0.1:61181 --native 2=127.0.0.1:61182

exec runs the statement on each shard in id order, each as its own transaction, and stops at the first shard that fails, naming the shards that already ran it.

Roles and privileges

Role and privilege statements do go through the gateway. It runs them on every shard, the home shard first:

sql
CREATE ROLE app LOGIN PASSWORD 'app-password-123';
GRANT SELECT, INSERT, UPDATE ON invoices TO app;
ALTER ROLE app PASSWORD 'new-password-456';
REVOKE UPDATE ON invoices FROM app;
DROP ROLE app;

This covers CREATE, ALTER and DROP ROLE, USER or GROUP, GRANT, REVOKE, ALTER DEFAULT PRIVILEGES and COMMENT ON ROLE.

  • Run each one on its own, outside a transaction block. Inside one it is refused with 25001.
  • If the home shard refuses the statement, nothing changes. If a later shard refuses it, the error names the shards where it already took effect; fix that shard and run the statement again.
  • A GRANT or REVOKE on a plain table that only the home shard has is skipped on shards where the table does not exist.
  • A new or changed password counts at once: the gateway forgets the role keys it cached.

Every shard checks privileges again on every statement, so a role needs its grants on every shard, which this gives it.

Limits

  • Schema statements are refused through the gateway; use rdb-shard ddl or rdb-shard exec.
  • A schema change is not atomic across shards. rdb-shard ddl makes a partial change visible (PARTIAL) and resumable, and fences the tables meanwhile.
  • Uniqueness is per shard unless the constraint includes the shard key.
  • Sequences and SERIAL columns are per shard.
  • An INSERT into a sharded table must give the shard key.
  • A key value never splits across shards.
✓ page rendered in 185 µs axum + tera + htmx · no other javascript