Moving data
How to move a tenant to another shard, rebalance the cluster, and add a shard, while clients keep working through the gateway.
How a move works
Every move between shards is run by rdb-shard and follows the same steps:
- The destination takes the range.
SHARD TAKE RANGEon the destination makes it ready to hold the moving blocks. They are not read there yet. - The rows are copied at one snapshot of the source, table by table, and verified: the row count and a checksum of every row must match on both sides.
- Online moves catch up. With
--online, the source keeps taking writes while the copy runs. Then up to eight rounds bring the destination up to date with what changed, until fewer than 256 rows change between two rounds. - The source is fenced (
SHARD FENCE RANGE): it refuses writes to the moving blocks. The tool waits for transactions already running on the source to end, copies what changed in a last round, and compares both sides again. With--onlinethis fence lasts only for the last round, and the tool reports how long writes were held. Without--onlinethe source is fenced for the whole copy. - The hand-off. The new map, one epoch up, is installed on the destination, then the source, then every other shard (
SHARD MAP INSTALL). The source gives the range up (SHARD GIVE RANGE) and its fence is lifted.
If anything fails before the hand-off, the tool undoes the move: the destination gives its copy back and the source is unfenced, so nothing has moved and you can run the command again. During the hand-off, every step is done only if it is not done already, so a hand-off that stopped is finished by running the same command again.
Gateways pick up the new map by themselves: a shard on the new map tells them, and they fetch it.
Before you move
- Identity rows. Every shard needs its identity row, written by
rdb-shard init(see Install and run). Moves rewrite the rows of the shards they touch. - Every sharded table. The hand-off gives the moved blocks up in every partitioned table of the source, so a move must carry every partitioned table. A move that leaves one out is refused before anything changes, and the message names it.
- The same schema. Each table must exist on the destination with the same schema fingerprint as on the source. Apply schema changes with
rdb-shard ddl(see Sharded tables). - Partitions. A partition on the source may not cover both moved and unmoved blocks. The move is refused before anything changes, and the message says what to run on the source:
ALTER TABLE ... ISOLATE KEY (...)for a tenant, or a partition split at the moved range's edges. - Access.
rdb-shardconnects to each shard's native port: pass--native ID=HOST:PORTfor every shard when the map's addresses are rshard listeners,--userwithRDB_PASSWORD, and--database.
The examples below use the cluster from Install and run, with these common flags:
export RDB_PASSWORD='change-me'
COMMON="--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"Move a tenant
Move every row of one key value to another shard. Find the shard that holds it, through the gateway:
SELECT rdb_shard_of('int', 5);The first argument is the shard key's type (int, bigint, text, varchar, uuid, ...). Say it answers 0. Give the tenant a partition of its own in every sharded table on that shard: connect to shard 0 directly and run, for each sharded table:
ALTER TABLE orders ISOLATE KEY (id = 5);Then move it, here to shard 2:
./rdb-shard move-tenant --map cluster.map --out cluster-2.map --state move-5.state \
--key-type int --key 5 --to 2 --table orders:id --online $COMMONorders: 1 rows copied and verified
online round 1: 0 rows brought up to date
fenced round: 0 rows, writes held 14 ms
moved to shard 2; map epoch 2 installed on both shards and written to cluster-2.map. Reload every router and gateway; the source's rows stay unread until it is restarted or retired.--key-typeisint(alsointeger,bigint),text(alsovarchar) oruuid;--keyis the value.--table TABLE:COLUMNnames each sharded table and its shard key column. Name every partitioned table.--outis where the new map is written;--stateis a new file that records the move.- The source keeps its old copy of the moved rows; they are no longer read.
A hand-off left half done
If the tool stops during the hand-off (killed, or a shard unreachable), the state file says status handing-off and the error says how to finish:
./rdb-shard resume --state move-5.state --out cluster-2.map $COMMONRunning the same move-tenant command again does the same. Until it is finished, the source stays fenced for the moved blocks: reads are exact, and writes there are refused with a retryable 57P03.
Between shards, a finished move is not rolled back with rdb-shard rollback. Move the tenant back with another move-tenant.
Rebalance
rdb-shard rebalance reads every shard's load (SHOW SHARD LOAD: the size of each partition) and plans range moves that bring every shard within a tolerance of the mean:
./rdb-shard rebalance --map cluster.map $COMMONshard 0: load 41.20% -> 33.10%
shard 1: load 30.05% -> 33.40%
shard 2: load 28.75% -> 33.50%
move blocks [0x2a0000000000, 0x2f0000000000) from shard 0 to shard 1 (1073741824 bytes)
(plan only; --apply --fenced runs it)To run the plan, online:
./rdb-shard rebalance --map cluster.map --apply --online \
--out cluster-2.map --state-dir ./rebalance-state $COMMONWithout --table, every partitioned table is moved by its shard key, and the tool prints each one. With --table TABLE:COLUMN:TYPE (for example orders:id:int) you name them yourself. Each move writes a state file in --state-dir; a later run first finishes any hand-off an earlier run left half done, then stops so you can plan again from the map it wrote.
| Flag | Default | What it does |
|---|---|---|
--tolerance F | 0.10 | How far from the mean load a shard may be before a move is planned. |
--max-moves N | 4 | The most moves in one round. |
--max-bytes N | 64 GiB | The most bytes moved in one round. |
--pin LO:HI | none | A block range that never moves. Repeatable. |
--exclude SHARD | none | A shard that receives no ranges. Repeatable. |
--apply | off | Run the plan instead of printing it. Needs --out and --state-dir. Add --online to keep writes flowing; without it each move fences its source for the whole copy. |
--every SECS | off | Plan (and with --apply, run) a round every SECS seconds, each from the map the last one wrote. Stops at the first failed round. |
Rebalancing from a client
The gateway can run the balancer itself, so an administrator can plan and start a rebalance over a normal PostgreSQL connection. Add to the gateway's configuration:
rebalance_tool = /opt/rdb-cluster/rdb-shard
rebalance_roles = rasterized
rebalance_user = rasterized
rebalance_password_env = RDB_PASSWORD
rebalance_native = 0=127.0.0.1:61180, 1=127.0.0.1:61181, 2=127.0.0.1:61182
rebalance_extra = --database postgres
config_dir = /var/lib/rasterizeddb-gatewayand start the gateway with the password in its environment (RDB_PASSWORD=... rasterizeddb-gateway --config gateway.conf). The gateway must read its map from a file (map, not map_from): a run writes the new map to that file.
Then, as a role named in rebalance_roles, outside a transaction:
SHOW REBALANCE PLAN;
REBALANCE CLUSTER MAX MOVES 1;
SHOW REBALANCE STATUS;| Statement | What it does |
|---|---|
SHOW REBALANCE PLAN | Every shard's load before and after (load rows), the planned move rows (from shard, to shard, block range, bytes), any split rows, or one balanced row. Columns: kind, shard, to_shard, lo_block, hi_block, bytes, load_before, load_after. |
REBALANCE CLUSTER [MAX MOVES n] | Starts rdb-shard rebalance --apply --online in the background, from the map the gateway holds now, writing the next map to the gateway's map file. Refused while another run is going. |
SHOW REBALANCE STATUS | state (idle, running, done or failed), started_at, finished_at, exit_code, command, then the tool's output as log rows. |
A run's state files go in <config_dir>/rebalance, or in the system's temporary directory without config_dir. A role not in rebalance_roles gets 42501.
Add a shard
Adding a shard is a split: a new, empty shard joins the map, and half of an existing shard's largest range moves onto it.
-
Start the new shard with the current map and a new id. A shard whose id the map does not list starts as a joining shard that owns nothing:
sh./rasterizeddb --location ./shard3 --protocol both \ --pg-port 5443 --rdb-port 61183 \ --role shard --cluster-map cluster.map --shard-id 3 \ --cluster-id 0123456789abcdef0123456789abcdef \ --shard-listen 127.0.0.1:7403 \ --shard-cert tls/shard3.pem --shard-key tls/shard3.key \ --gateway-ca tls/ca.pem --peer-ca tls/ca.pem > shard3.log 2>&1 &It needs a certificate signed by the cluster's CA, like the others.
-
Create the schema on it, with the same statements that made the other shards' tables, so the fingerprints match:
shpsql "postgresql://rasterized:change-me@127.0.0.1:5443/postgres?sslmode=require" \ -c "CREATE TABLE orders (id INT PRIMARY KEY, store INT NOT NULL, v INT NOT NULL) PARTITION BY HASH (id)" \ -c "CREATE TABLE stores (id INT PRIMARY KEY, name TEXT NOT NULL)" -
Split a shard's range onto it:
sh./rdb-shard split --map cluster.map --shard 1 --new-id 3 \ --new-addr 127.0.0.1:7403 --new-native 127.0.0.1:61183 \ --online --out cluster-2.map --state-dir ./split-state \ --table orders:id:int $COMMONtextshard 3 (127.0.0.1:7403) joined at map epoch 2; moving [0x7fffffffffff, 0xaaaaaaaaaaaa) to it move 0: orders: 98 rows copied and verified online round 1: 3 rows brought up to date fenced round: 0 rows, writes held 11 ms 1 moves applied; map epoch 3 written to cluster-2.map. Reload every router, then lift the fence. The source rows stay until `rdb-shard retire` of each state file in ./split-state.The last line's advice is written for plain servers. Between shards the source's fence is already lifted at the hand-off, and gateways follow the new map by themselves.
split writes the new shard's identity row, installs a map with the new shard (one epoch up) on every shard, then moves the upper half of --shard's largest range, or from --at BLOCK. --new-addr is the address the map gives the new shard (its rshard listener); --new-native is its native address for the tool. Clients writing through the gateway keep working while it runs.
To spread load further afterwards, run a rebalance.
Remove a shard
There is no command that empties a shard and takes it out of the map in this version. A shard that owns no ranges serves nothing, but stays in the map.
After a move: copy the new map
A move installs the new map on every running shard and the gateways fetch it, but no program rewrites the map files they were started with. A shard records the highest map epoch it has served and refuses to start with an older map file, and so does a gateway (<map>.epoch). So after every move:
- Copy the map the tool wrote (
--out) over the--cluster-mapfile of every shard and themapfile of every gateway. - Only then restart any of them.
To check which map a shard is serving, connect to it directly and run SHOW SHARDS: the row with this_shard true has its map_epoch. A gateway shows its own in SHOW GATEWAY (map_epoch). A gateway started with map_from fetches the current map from a shard instead of reading a file.
What clients see during a move
- Reads are exact throughout: every row is counted once, before, during and after the hand-off.
- Writes to the moving rows are refused while the source is fenced: during the last round of an online move (milliseconds to seconds), or the whole copy of an offline one. The refusal comes before any effect, so the gateway waits briefly and retries, up to
retriestimes (3 by default). A client sees57P03only when the fence outlasts the retries; retry the statement. A statement inside a transaction block is retried only when it is the transaction's first. - Other rows are not affected.
- After the hand-off, gateways route the moved keys to their new shard. A statement sent with the old map is refused by the source and retried by the gateway on the new map.
- Redis-protocol cache entries are not moved: a moved key starts empty on its new shard.
rdb-shard reference
The commands for clusters of shards. The commands shared with plain servers (init, show, exec, move-tenant with --fenced, rollback, retire) are also described in client-side sharding.
| Command | What it does |
|---|---|
init --map MAP | Writes every shard's identity row. Refuses a shard whose row names another cluster or id. |
show --map MAP | Prints the map's cluster, epoch, digest, and for each shard its share of the blocks and whether its identity row matches. |
move-tenant --map MAP --out NEW_MAP --state STATE --key-type TYPE --key VALUE --to SHARD --table TABLE:COLUMN [--table ...] [--online] | Moves one tenant. On shards, --online keeps writes flowing until the last round; without it the source is fenced for the whole copy. (--fenced is for plain servers.) |
resume --state STATE [--out MAP] | Finishes a hand-off a move left half done. |
rebalance --map MAP [flags] | Plans range moves from every shard's load; runs them with --apply. |
split --map MAP --shard HOT --new-id N --new-addr HOST:PORT [--new-native HOST:PORT] [--at BLOCK] [--online] --out NEW_MAP --state-dir DIR [--table TABLE:COLUMN:TYPE ...] | Adds shard N to the map and moves part of HOT's largest range to it. |
ddl --map MAP --file FILE --table TABLE [...] | Applies a schema change to every shard (see Sharded tables). |
exec --map MAP --sql SQL | Runs one statement on every shard in id order, each as its own transaction; stops at the first failure and names the shards already done. |
backup --map MAP --out MANIFEST [--snapshot] [--home SHARD] | A consistent backup of the whole cluster (see Administration). |
restore --manifest MANIFEST [--map MAP] | Checks every shard's archive still holds its restore point and prints the steps to restore. |
resolve --map MAP [--home SHARD] [--grace SECS] | Finishes two-phase transactions left prepared (see High availability). |
keygen --key FILE | Makes a map-signing key pair and prints the public key for --authority-key. |
sign --map MAP --key FILE | Writes MAP.sig. |
Common flags:
| Flag | Default | What it does |
|---|---|---|
--user U | none | Log in as U, with the password from the RDB_PASSWORD environment variable. |
--database NAME | the shard's default database | The database on every shard. |
--native ID=HOST:PORT | the map's address | Where shard ID's native port is. Repeatable. Needed when the map's addresses are rshard listeners. |
--ca PEM | none | Trust shards whose native certificate this CA signed. |
--pin SHA256 | none | Trust the shard certificate with this fingerprint. |
--accept-any | on when neither --ca nor --pin is given | Accept any certificate. |
--sign-key FILE | none | Sign every map the command writes (MAP.sig) with this authority key. |
The tool exits with status 0 on success, 1 on failure and 2 on bad arguments.
Limits
- Moves are run by an operator (or a gateway's
REBALANCE CLUSTER), never automatically, except withrebalance --every. - A move must carry every partitioned table, and the tenant or range must not share a partition with blocks that stay.
- Writes to the moving rows pause during the fenced round.
- No command removes a shard from the map.
- The source keeps its old copy of moved rows after a move between shards; reclaiming that space is not covered here.
- Map files are not updated on disk: copy the new map to every shard and gateway before restarting them.
- Cache entries in the Redis-protocol store do not move with their keys.