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.
| Kind | Declared with | Rows live | Use it for |
|---|---|---|---|
| Sharded | PARTITION BY HASH (key) | Spread over the shards by the key | Large tables that split by tenant, store, account, customer |
| Plain (global) | an ordinary CREATE TABLE | On the home shard only | Small tables that are not per tenant: settings, plans, lookup data that changes |
| Reference | an ordinary CREATE TABLE, then SHARD REFERENCE TABLE name on every shard | A full copy on every shard | Small, read-mostly tables joined with sharded ones: countries, currencies, product categories |
-- 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 = onin the gateway, every copy changes or none does. Without it, a write needsSET rdb.unrouted_writes = each_shard, and each shard's copy is changed in turn, not atomically. COPYinto a reference table loads every copy, and needstwo_phase = on.SHARD UNREFERENCE TABLE namemakes 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:
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:61182The 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) andUUID. The same value of the same kind lands on the same shard in every table, so an invoice and its lines with the samestore_idare on one shard, and a join onstore_idthat 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:
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
SERIALcolumn, or aDEFAULT 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:
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:61182shard 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 liftedWhat it does, in order:
- 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.
- Fences the named tables on every shard (
shard.ddl_fence). Until the change is done, a statement that touches them is refused with40001and the message that the schema changed. Clients should retry it. - 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. - Compares the schemas. Each named table's schema fingerprint must be the same on every shard.
- 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.
| Flag | Default | What it does |
|---|---|---|
--map MAP | required | The cluster map. |
--file FILE | required | The schema statement to apply. |
--table TABLE | required | A table the change creates or alters. Repeat it for each. |
--home SHARD | the lowest shard id | The shard applied first. |
--state STATE | FILE.state | Where progress is recorded, for resuming. |
--frontend ADDR | none | A front-end node to apply the change to once every shard has it. Repeatable. |
--frontend-only | off | Apply 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:
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:61182When 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:
./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:61182exec 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:
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
GRANTorREVOKEon 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 ddlorrdb-shard exec. - A schema change is not atomic across shards.
rdb-shard ddlmakes 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
SERIALcolumns are per shard. - An
INSERTinto a sharded table must give the shard key. - A key value never splits across shards.