Client-side sharding
Spread an application's tenants over several ordinary RasterizedDB servers, with the routing done inside your Rust program: each tenant lives whole on one server, and the client sends every call to the right one.
When to use it
Client-side sharding fits when:
- the application is written in Rust and talks to the database through
rasterizeddb_client; - its data splits by a tenant column (a store, an account, a customer), and almost every query names one tenant;
- each server is an ordinary RasterizedDB server. Nothing on the servers changes, and the router adds no extra network hop: it hands you the tenant's server's own
Client.
The sharding gateway is the other way to shard. It sits between PostgreSQL clients (any language, any driver) and servers run as shards. Use the gateway when clients other than this Rust client must reach sharded data. Use client-side sharding when the Rust application is the only client, and you want plain servers with no gateway in between.
How it works:
- A shard map lists the servers (shards) and gives each one ranges of a hash space.
- A tenant's shard key value (
store_id = 'store-7') hashes to one point in that space, so one shard holds all of a tenant's rows. - Models marked with
#[rdb(shard_by = "…")]are routed by that column. Queries are routed by the key their filter names, or sent to every shard and merged. - Every shard holds an identity row that names its cluster and shard id. The router checks it when it connects, so a wrong server behind an address fails the connect and never receives misrouted writes.
- The
rdb-shardtool writes the identity rows, shows the cluster, and moves a tenant from one shard to another.
Install
Sharding is the sharding Cargo feature of rasterizeddb_client. It is on by default from rasterizeddb_client 1.1.0, and it does nothing until you build a Router:
[dependencies]
rasterizeddb_client = "1.1"
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }If you turn the default features off, name the ones you need:
[dependencies]
rasterizeddb_client = { version = "1.1", default-features = false, features = ["derive", "sharding"] }The rdb-shard tool is a binary of the same crate. Install it with Cargo:
cargo install rasterizeddb_client --bin rdb-shardSet up a cluster
1. Start one server per shard
Start an ordinary RasterizedDB server for each shard. The router connects to each one's native protocol listener (port 61170 by default). Every shard needs the same tables. The router creates them on every shard for you (see Tables and migrations).
2. Write the shard map
The shard map is a text file:
rasterizeddb shard map
format 1
cluster 0f1e2d3c4b5a69788796a5b4c3d2e1f0
epoch 1
route_v 1
# shard ID PRIMARY [STANDBY ...]
shard 0 10.0.0.1:61170 10.0.1.1:61170
shard 1 10.0.0.2:61170
# range FIRST_BLOCK SHARD
range 0x0 0
range 0x800000000000 1| Line | Meaning |
|---|---|
rasterizeddb shard map | Required first line. |
format 1 | The file format version. Optional; 1 is the only one. |
cluster HEX | The cluster's id: 32 hex digits, the same in every map of this cluster. Pick a random one once, for example with openssl rand -hex 16. |
epoch N | The map's version, at least 1. Every change to the map raises it. |
route_v 1 | The hash function's version. Optional; 1 is the only one. |
shard ID ADDR [STANDBY ...] | A shard: its id, its primary's address (host:port), then optional standby addresses, tried in order when the primary cannot be reached at connect. Addresses may not contain spaces or commas. |
range BLOCK SHARD | Shard SHARD owns the blocks from BLOCK up to the next range line's block. The first range starts at 0x0. Blocks are decimal or 0x hex, and the space has 2⁴⁸ blocks (0x0 to 0xffffffffffff). |
digest HEX | Optional checksum of the content, 16 hex digits. When it is present it must match, so after editing a map by hand, delete the line (or write the map again from code). |
# starts a comment, and blank lines are ignored.
A shard key value always falls in exactly one block, so a tenant is never split between shards. A shard can own several ranges.
To lay out equal ranges for any number of shards, build the map in code and write it out. The written file includes a correct digest line:
use rasterizeddb_client::shard::{ShardInfo, ShardMap};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let shards = vec![
ShardInfo { id: 0, addr: "10.0.0.1:61170".into(), standbys: vec!["10.0.1.1:61170".into()] },
ShardInfo { id: 1, addr: "10.0.0.2:61170".into(), standbys: vec![] },
ShardInfo { id: 2, addr: "10.0.0.3:61170".into(), standbys: vec![] },
];
// Epoch 1, each shard owning one equal range.
let map = ShardMap::initial(0x0f1e2d3c4b5a69788796a5b4c3d2e1f0, shards)?;
std::fs::write("shards.map", map.to_text())?;
Ok(())
}3. Write each shard's identity row
rdb-shard init --map shards.mapshard 0 (10.0.0.1:61170): identity written at epoch 1
shard 1 (10.0.0.2:61170): identity written at epoch 1init creates a table named rdb_shard_identity on every shard and writes one row to it: the cluster id, the shard's id, and the map's epoch and digest. It refuses to touch a server whose row already names another cluster or another shard id. The row lives in an ordinary table, so backups, restores and replicas carry it with the data.
Check the cluster at any time:
rdb-shard show --map shards.mapcluster 0f1e2d3c4b5a69788796a5b4c3d2e1f0 epoch 1 digest 3f9c2a71d04be855 2 shards, 2 ranges
shard 0 10.0.0.1:61170 50.00% of blocks ok, identity at epoch 1
shard 1 10.0.0.2:61170 50.00% of blocks ok, identity at epoch 1The last column says unreachable: …, no identity row (run init), or WRONG identity: … when a shard is not right.
Connect a router
use rasterizeddb_client::prelude::*;
use rasterizeddb_client::shard::ShardMap;
#[tokio::main]
async fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {
let map = ShardMap::from_text(&std::fs::read_to_string("shards.map")?)?;
let router = Router::connect(map, Options::default()).await?;
println!("connected; home shard is {}", router.home_id());
Ok(())
}Router::connect(map, options) opens a Client to every shard in the map with the same Options (login, database, TLS, timeouts). It tries each shard's primary, then its standbys in order. Then it reads every shard's identity row and refuses a shard that:
- has no identity row (
Error::IdentityMismatch, unlessrequire_identityis off); - names another cluster or another shard id (
Error::IdentityMismatch); - has taken part in a newer map than the one given (
Error::MapStale: connect again with the newest map); - names another map at the same epoch (
Error::IdentityMismatch).
Every shard must be reachable when the router connects. A shard whose primary and standbys all fail is Error::ShardDown.
Router is not Clone. To share one across tasks, put it in an Arc.
Router options
Router::connect_with(map, options, router_options) takes a RouterOptions (from rasterizeddb_client::shard):
| Field | Default | What it does |
|---|---|---|
home | None (the lowest shard id in the map) | The home shard, which holds global tables and global key/value keys. Must be in the map. |
require_identity | true | Refuse a shard that has no identity row. Turn it off only for servers that never ran rdb-shard init. |
health_interval | 2 s | How often each shard is probed with SELECT 1. |
health_max_backoff | 30 s | The longest wait between probes of a shard that is down. |
health_timeout | 2 s | How long a probe may take before it counts as a failure. |
spare_shards | 64 | Room for shards that a reloaded map may add beyond the first map's. |
use std::time::Duration;
use rasterizeddb_client::prelude::*;
use rasterizeddb_client::shard::{RouterOptions, ShardMap};
#[tokio::main]
async fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {
let map = ShardMap::from_text(&std::fs::read_to_string("shards.map")?)?;
let router = Router::connect_with(
map,
Options::default(),
RouterOptions {
health_interval: Duration::from_secs(1),
..RouterOptions::default()
},
)
.await?;
let _ = router;
Ok(())
}Health checks
From the moment it connects, the router probes every shard in the background with SELECT 1. When a probe fails or takes longer than health_timeout, the shard is marked down. Calls routed to a down shard then fail at once with Error::ShardDown, and nothing is sent to it. A down shard is probed again at a doubling interval, up to health_max_backoff. Once it answers, it is up again. router.is_up(id) reports a shard's state.
Reloading the map
let next = ShardMap::from_text(&std::fs::read_to_string("shards.map")?)?;
router.reload(next).await?;reload replaces the map in force while the router keeps working. The new map must:
- belong to the same cluster (otherwise
Error::IdentityMismatch); - have a higher epoch (otherwise
Error::MapStale); - keep the address of every shard that both maps share (otherwise
Error::Unsupported; connect a new router instead).
Shards that are new in the map are connected and their identity rows checked before the new map takes effect. Shards the new map drops stay connected but receive nothing. If anything fails, the old map stays in force.
A running router never notices a new map by itself. After a tenant moves, your application must call reload on every router (see Move a tenant).
Mark models as sharded
Where a model's rows live is set on the struct:
use rasterizeddb_client::prelude::*;
/// Spread over the shards by store_id.
#[derive(Model, Debug, Clone)]
#[rdb(table = "invoices", shard_by = "store_id")]
struct Invoice {
#[rdb(primary_key)]
store_id: String,
#[rdb(primary_key)]
invoice_no: i64,
total: i64,
}
/// Reference data: rows on the home shard only.
#[derive(Model, Debug, Clone)]
#[rdb(table = "stores", shard = "global")]
struct Store {
#[rdb(primary_key)]
id: String,
name: String,
}| Struct attribute | Where the rows live |
|---|---|
shard_by = "column" | Spread over the shards by that column's value. |
neither shard_by nor partition_by | Global: on the home shard only. |
partition_by = "a, b" without shard_by | Sharded by the leading partition column (a), when that column follows the rules below. When it does not, the model still compiles, but a router refuses it with the reason (Error::Unsupported). Add shard_by to have the rules checked at compile time, or shard = "global". |
shard = "global" | On the home shard only. Every shard has the table, but only the home shard has rows. |
shard = "unsharded" | A router refuses the model outright. Use it when sending a forgotten model through the router should be an error. |
shard_by and shard = "…" cannot be used together.
With shard_by, these rules are checked at compile time:
- The column is a field of the model.
- Its type is an integer (
i8toi128,u8tou64), aString, or a UUID (rasterizeddb_client::Uuid, oruuid::Uuidwith theuuidfeature). It is not anOption, and it has nojson,textorsql_typeattribute. - When the model has a primary key, the key contains the shard column.
- No other field is
unique. A unique constraint is enforced on each shard separately, so it holds across the cluster only when it includes the shard column. - No field is
serial. A sequence counts on each shard separately, so its values would collide across shards. Use UUIDs (v7) or ids your application assigns.
All of a tenant's tables should use the same shard column (the same column name). Related rows then live on the same shard, and relations between them load there (see Relations).
Routed calls
ShardedModelExt, in the prelude with Router, gives the router the same row calls a Client has (see The ORM). Each call goes to the row's shard:
use rasterizeddb_client::prelude::*;
use rasterizeddb_client::shard::ShardMap;
#[derive(Model, Debug, Clone)]
#[rdb(table = "invoices", shard_by = "store_id")]
struct Invoice {
#[rdb(primary_key)]
store_id: String,
#[rdb(primary_key)]
invoice_no: i64,
total: i64,
}
#[tokio::main]
async fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {
let map = ShardMap::from_text(&std::fs::read_to_string("shards.map")?)?;
let router = Router::connect(map, Options::default()).await?;
// The table on every shard, home first.
router.create_table::<Invoice>().await?;
// On store-7's shard.
let mut inv = router
.insert(&Invoice { store_id: "store-7".into(), invoice_no: 1, total: 1250 })
.await?;
// The primary key holds the shard column, so a key lookup routes too.
let found: Option<Invoice> = router.find_by_key::<Invoice>(params!["store-7", 1i64]).await?;
println!("{found:?}");
// `Router` has its own `update` (for query updates), so call the row update by its trait.
inv.total = 1300;
let inv = ShardedModelExt::update(&router, &inv).await?;
router.delete(&inv).await?;
Ok(())
}| Call | Where it goes |
|---|---|
create_table::<M>() | Every shard, home first. Every shard has every model's table, so schemas stay identical. |
drop_table::<M>() | Every shard at once. A failure on some shards is Error::FanOutPartial. |
insert(&row), upsert(&row), delete(&row), force_delete(&row), restore(&row) | The row's shard, by its shard key. A global model's rows go to the home shard. |
ShardedModelExt::update(&router, &row) | The row's shard. Write it this way: router.update(…) is the query update below. |
insert_many(&rows) | One transaction per shard. Rows of more than one shard need .split_across_shards(), or the call fails with Error::CrossShard before anything is sent. With it, each shard's rows commit on their own, and a failure on some shards is Error::FanOutPartial. Await it directly, or call .run(). The rows come back in the order given. |
update_many(&rows) | One shard only. Rows of several shards are Error::CrossShard. |
find::<M>(key) | The key's shard. For a single-column primary key that is the shard column. |
find_by_key::<M>(key) | The key's shard. The values go in primary key column order (field order), and they include the shard column. |
ShardedModelExt::all::<M>(&router) | Every row of the table: the home shard's for a global model, every shard's concatenated for a sharded one. router.all() is a different method: it lists the shards. |
Errors from a shard name it: a server error from shard 1 reads shard 1: ….
The shard's own client
For plain SQL, admin calls or the key/value store, take the shard's Client and use it as usual:
| Call | Returns |
|---|---|
router.for_key(key) | The Client of the shard that holds key: router.for_key("store-7")?. Pass the Rust type of the shard column (i64 for BIGINT, &str or String for text). |
router.for_shard(id) | Shard id's Client; Error::ShardDown while it is down. |
router.for_model(&row) | The Client of the row's shard. |
router.home() | The home shard's Client. |
router.all() | Every shard as (id, &Client), in id order, up or not. |
router.shard_of(key), router.shard_for(&row), router.shard_for_key::<M>(key) | The shard id only. |
router.map(), router.home_id() | The map in force, and the home shard's id. |
To check that the client and a server hash a key the same way, compare rasterizeddb_client::shard::block_of_key with the server's rdb_route_block function:
use rasterizeddb_client::orm::{ShardFamily, ShardKey};
use rasterizeddb_client::shard::block_of_key;
fn main() -> rasterizeddb_client::Result<()> {
let block = block_of_key(&ShardKey::from("store-7"), ShardFamily::Text)?;
println!("{block}");
Ok(())
}SELECT rdb_route_block('text', 'store-7');Routed queries
Pass a query to router.select(&query), then run it with one of all, first, one, count, exists, page, delete, force_delete or delete_returning. The router decides where it goes from the query's filter. The examples from here on use the Invoice model from Mark models as sharded.
use rasterizeddb_client::prelude::*;
async fn reports(router: &Router) -> rasterizeddb_client::Result<()> {
// Pinned by the filter: one shard.
let recent = router
.select(
&Invoice::query()
.filter(Invoice::store_id.eq("store-7"))
.order_by(Invoice::invoice_no.desc())
.limit(20),
)
.all()
.await?;
// Two tenants: the shards that hold them, merged.
let both = router
.select(&Invoice::query().filter(Invoice::store_id.is_in(["store-7", "store-9"])))
.count()
.await?;
// Every shard, merged in order, then cut to the limit.
let biggest = router
.select(&Invoice::query().order_by(Invoice::total.desc()).limit(10).all_shards())
.all()
.await?;
println!("{} {} {}", recent.len(), both, biggest.len());
Ok(())
}How a query is routed:
Column::eq(value)andColumn::is_in(values)on the model's shard column pin the query to the shards those values live on.- Combining filters with
and(or several.filter(…)calls) keeps the pins. When the pins can match no shard (two different keys underand), nothing is sent: reads return nothing and counts return 0. or,notandExpr::rawdrop the pins.- A query on a sharded model that pins nothing fails with
Error::NeedsRouteKey, unless it says where to go:.on_shard(key)runs it on the shard ofkey, whatever the filter says..all_shards()runs it on every shard and merges the answers.
- A query on a global model always runs on the home shard.
When a query reaches several shards (by is_in or all_shards):
allasks each shard forlimit + offsetrows, merges the answers in the query'sorder_byorder, then applies the offset and limit. Withoutorder_by, the rows come in shard order.- The merge compares column values: integers and
NUMERICby value, text by its bytes, NULLs placed as the query's order says. A merged query can order by the model's columns only; anorder_byexpression isError::Unsupported. - Keyset reads (
after,before) merge the same way.pagereads one shard only, and on several it isError::Unsupported. countadds the shards' counts;existsis true when any shard has a row.- If any shard fails (or is down), the whole read fails with that shard's error.
Writes by query
delete, force_delete and delete_returning on router.select(&query) go to the pinned shards. A query update goes through router.update(&update):
use rasterizeddb_client::prelude::*;
async fn cleanup(router: &Router) -> rasterizeddb_client::Result<()> {
// One tenant: one shard.
let zeroed = Invoice::query()
.filter(Invoice::store_id.eq("store-7"))
.update()
.set(Invoice::total, 0);
router.update(&zeroed).run().await?;
// Every shard: allowed only with split_across_shards().
let removed = router
.select(&Invoice::query().filter(Invoice::total.lt(0)).all_shards().split_across_shards())
.delete()
.await?;
println!("{removed} removed");
Ok(())
}A write by query that reaches more than one shard fails with Error::CrossShard before anything is sent, unless the query says .split_across_shards(). With it, each shard's part commits on its own. If some shards fail after others committed, the error is Error::FanOutPartial, which lists both.
Relations
Relations (with, with_count, where_has) work through the router when the related rows live on the same shard as the parent:
- a child with the same shard column as the parent loads from the parent's shard;
- a global child of a sharded parent loads
withandwith_countfrom the home shard.where_hason a global child works only when the query itself runs on the home shard; - any other pairing (a different shard column, or a sharded child of a global parent) is
Error::CrossShard.
Running your own code on every shard
router.fan_out runs a closure on every shard at once and returns each shard's answer in shard id order. A shard that is down answers Error::ShardDown, and the closure does not run for it. Merging the answers is up to you:
use rasterizeddb_client::prelude::*;
async fn invoice_counts(router: &Router) -> rasterizeddb_client::Result<i64> {
let answers = router
.fan_out(|_id, client| async move {
client.fetch_scalar::<i64>("SELECT count(*) FROM invoices", params![]).await
})
.await;
let mut total = 0;
for (id, answer) in answers {
match answer {
Ok(n) => total += n,
Err(e) => eprintln!("shard {id}: {e}"),
}
}
Ok(total)
}Transactions
A transaction runs on one shard: the shard of a key you name.
use rasterizeddb_client::prelude::*;
async fn bill(router: &Router) -> rasterizeddb_client::Result<()> {
let tx = router.begin_for("store-7").await?;
tx.insert(&Invoice { store_id: "store-7".into(), invoice_no: 2, total: 400 }).await?;
tx.insert(&Invoice { store_id: "store-7".into(), invoice_no: 3, total: 900 }).await?;
tx.commit().await?;
// With retries on serialization failures and deadlocks, as Client::transaction does.
let first = Invoice { store_id: "store-7".into(), invoice_no: 4, total: 100 };
router
.transaction_for("store-7", |tx| {
let row = first.clone();
Box::pin(async move {
tx.insert(&row).await?;
Ok(())
})
})
.await?;
Ok(())
}router.begin_for(key)begins a transaction on the shard ofkeyand returns an ordinaryTransaction.router.transaction_for(key, body)isClient::transactionon that shard: it commits onOk, rolls back onErr, and runs the body again after a serialization failure or deadlock. The closure may run more than once.- Inside either, every ORM row write (
insert,insert_many,upsert,update,update_many,delete,force_delete,restore) checks that the row lives on the transaction's shard before anything is sent. A row of another shard isError::CrossShard, never a write in the wrong place. Plain SQL sent through the transaction is not checked.
Tables and migrations
When Options::migrations holds a Migrator, the router does not run it on each shard's connection. Router::connect runs it once over the whole cluster, as Options::auto_migrate says:
AutoMigrate::Apply(the default): the home shard first, then every other shard in id order. Each shard keeps its own migration ledger.AutoMigrate::Verify: checks every shard, and fails when one has pending migrations.AutoMigrate::Off: nothing at connect.
router.migrate(&migrator) does the same by hand and returns each shard's MigrationReport as (shard_id, report). A failure stops at the shard it names. The shards before it stay migrated, and the next run resumes from each shard's ledger. Nothing is undone, because schema changes are not transactional.
Every model's table is made on every shard. A global model's table stays empty off the home shard.
Key/value data and caching
| Call | What it does |
|---|---|
router.kv_for(key) | The key/value store on the shard of key. Keep tenant keys on the tenant's shard and start them with the tenant (store-7:…). |
router.home()?.kv() | The home shard's store, for global keys. |
router.cached::<M>(ttl) | The ORM's read-through cache, routed: each entry lives on its row's shard, so a write and the cache entry it invalidates are on the same server. Takes find, find_by_key, insert, update, upsert, delete, force_delete, restore and invalidate, and .with_prefix(prefix). |
router.kv_repo::<M>() | Models kept as key/value entries, routed the same way: save, save_with_ttl, get, delete, delete_key, exists, and all (every shard, one after another). |
Listing keys across the cluster is a fan-out: run it on each shard with router.fan_out.
Move a tenant
rdb-shard move-tenant moves one tenant's rows to another shard while the tenant is offline:
-
Fence the tenant. Stop your application from writing the tenant's rows, for example with a flag your code checks, or by disabling the tenant's own login role. The tool cannot see your writers, and it refuses to run on ordinary servers without
--fenced, which is your word that nothing writes the tenant until the move is done. -
Run the move, naming every sharded table with its shard column:
shrdb-shard move-tenant --map shards.map --out shards-2.map --state move-store-7.state \ --key-type text --key store-7 --to 1 \ --table invoices:store_id --table invoice_lines:store_id \ --fencedtextinvoices: 1830 rows copied and verified invoice_lines: 9204 rows copied and verified moved to shard 1; map epoch 2 written to shards-2.map. Reload every router, then lift the fence. The source rows stay until `rdb-shard retire`. -
Reload every router with the new map (
router.reload(…)), then lift the fence. -
Retire the old copy once the move has proven itself (after 24 hours by default):
shrdb-shard retire --map shards-2.map --state move-store-7.state
What move-tenant does:
- It checks that both shards' identity rows match the map, and that every named table exists on the destination.
- It reads each table's rows of the tenant at one snapshot of the source (a repeatable-read, read-only transaction). It refuses a destination that already holds rows of the tenant.
- It inserts them on the destination in transactions of 10,000 rows, then reads them back and compares the row count and a checksum of every row with the source. Any difference stops the move.
- If any step fails, it deletes the rows it copied to the destination, so nothing has moved and you can retry.
- On success it writes the new map to
--out, one epoch up, with the tenant's block on the destination. It also updates both shards' identity rows to the new epoch and records the move in the state file. A router that later connects to either shard with the old map getsError::MapStale. - The source keeps its copy of the tenant's rows until
retire.
Roll a move back
Until it is retired, a move can be undone:
rdb-shard rollback --map shards-2.map --out shards-3.map --state move-store-7.stateinvoices: 1830 copied rows removed from shard 1
invoice_lines: 9204 copied rows removed from shard 1
the moved rows are back on shard 0; map epoch 3 written to shards-3.map. Reload every router.rollback takes the map the move wrote (--map), writes a map with the tenant back on its old shard (--out, one more epoch up), updates both identity rows, and deletes the copied rows from the destination. The tenant's rows on the source are the ones copied at the move, so writes made on the new shard since the move are lost. Fence the tenant again before rolling back, then reload every router.
Retire a move
retire deletes the tenant's old rows from the source shard. It refuses while the move is younger than the retention period, and it refuses when the map you give does not have the tenant on its new shard. After retire, the move can no longer be rolled back.
The move state file
--state names a new file for each move. move-tenant refuses a state file that already exists. The state file records the tenant, both shards, the tables, the time of the move, and its status: moved, rolled_back or retired. Keep it until the move is retired, because rollback and retire read the tables and shards from it.
Add a server
To add a shard, add its shard line to the map, raise the epoch, delete the digest line, and run rdb-shard init with the new map. Then reload every router: the router connects the new shard and checks its identity. The new shard owns no ranges yet. Move tenants onto it with move-tenant --to <its id>.
rdb-shard reference
| Command | What it does |
|---|---|
init --map MAP | Writes every shard's identity row for MAP. Refuses a server whose row names another cluster or shard id. |
show --map MAP | Prints the map's cluster, epoch, digest, each shard's 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 …] --fenced | Moves one tenant (see Move a tenant). |
rollback --map NEW_MAP --out MAP --state STATE | Puts a moved, unretired tenant back on its old shard. |
retire --map NEW_MAP --state STATE [--retention-hours N] [--force] | Deletes the moved tenant's rows from the old shard. |
exec --map MAP --sql SQL | Runs one statement on every shard in id order, each as its own transaction, and prints each shard's row count and the total. It stops at the first shard that fails and names the shards that already applied it. |
| Flag | Default | What it does |
|---|---|---|
--key-type | — | The shard column's type in move-tenant: int (also integer, bigint), text (also varchar) or uuid. |
--key | — | The tenant's shard key value, as text: 42, store-7, or a UUID. |
--to | — | The destination shard's id. |
--table TABLE:COLUMN | — | A table to move and its shard column. Repeat it for every table that holds the tenant's rows. |
--fenced | off | Confirms the application has stopped writing the tenant. Required on ordinary servers. |
--retention-hours | 24 | How old a move must be before retire deletes the source rows. |
--force | off | Lets retire run inside the retention period. |
--user U | no login (trust) | Logs in as U with the password from the RDB_PASSWORD environment variable. |
--database NAME | the server's default database | The database on every shard. |
--ca PEM | — | Trusts servers whose certificate chains to this CA file. |
--pin SHA256 | — | Trusts the server certificate with this fingerprint. |
--accept-any | on | Accepts any server certificate. This is what happens when neither --ca nor --pin is given. |
The tool connects to every shard at the address in the map, with the same login and TLS settings for every shard. It exits with status 0 on success, 1 on failure and 2 on bad arguments.
The tool's other commands (rebalance, split, resume, ddl, backup, restore, resolve, keygen, sign, and move-tenant --online) are for servers run as shards behind the gateway. See Moving data.
Errors
Sharding adds these variants to rasterizeddb_client::Error (see Errors):
| Variant | When | What to do |
|---|---|---|
ShardDown { shard, message } | The shard's health check is failing, or the shard could not be reached when the router connected (its primary and every standby). Nothing was sent to it. | Retry later, or serve that shard's tenants as unavailable. router.is_up(shard) tells you when it is back. |
MapStale(message) | At connect or reload: a shard has taken part in a newer map than the router's (a tenant has moved), or reload was given a map whose epoch is not higher than the current one. | Read the newest map and reload (or connect) with it. |
IdentityMismatch(message) | The server at a shard's address is not that shard: its identity row names another cluster or shard id, or another map at the same epoch, or it has no identity row at all. Also returned when reload is given another cluster's map. | Fix the address in the map, or run rdb-shard init on a new server. Nothing is routed to that server. |
FanOutPartial { applied, failed } | A write sent to several shards (insert_many with split_across_shards, a split query delete or update, drop_table) failed on some shards after committing on others. applied lists the shards that committed; failed lists (shard, reason). | Retry the failed shards' part, or repair by hand. The committed parts stay committed. |
CrossShard(message) | The call would touch more than one shard, or models that do not live on one shard together: rows of several shards without split_across_shards, update_many over several shards, a write query reaching several shards without split_across_shards, a relation between models on different shards, or a row of another shard inside begin_for/transaction_for. Nothing was sent. | Split the work per shard, add split_across_shards() where it is allowed, or fix the key. |
NeedsRouteKey(message) | A query on a sharded model does not filter its shard column with eq or is_in. Nothing was sent. | Add the filter, or say .on_shard(key) or .all_shards(). |
Other errors the router returns:
Error::Unsupported: a model markedshard = "unsharded"or one that cannot be sharded,pageover several shards, a mergedorder_bythat is not a model column, a reloaded map that changes a shard's address, or a map with more new shards thanspare_shardsleaves room for.Error::Param: a key that has no form in the shard column's type (the text"abc"for an integer column), or a home shard that is not in the map.
Error is #[non_exhaustive], so keep a catch-all arm:
use rasterizeddb_client::prelude::*;
async fn load(router: &Router, store: &str) -> rasterizeddb_client::Result<Vec<Invoice>> {
match router.select(&Invoice::query().filter(Invoice::store_id.eq(store))).all().await {
Ok(rows) => Ok(rows),
Err(Error::ShardDown { shard, message }) => {
eprintln!("shard {shard} is down: {message}");
Ok(Vec::new())
}
Err(e) => Err(e),
}
}Limits
- No transaction or join spans shards. A transaction runs on one shard, and a write that reaches several shards commits on each separately.
- A read sent to several shards fails as a whole if any one of them fails or is down.
- Merged results are ordered by model columns only, and text is compared by its bytes, which can differ from the server's collation order.
- Tenant moves are offline: your application must stop writing the tenant, and must reload every router before it lifts the fence. A running router does not notice a new map on its own.
- Between a move and its
retire, the old shard still holds the tenant's rows. Reads that go to every shard (all_shards,ShardedModelExt::all,fan_out,rdb-shard exec) see those rows twice until the move is retired. - A rollback discards writes made on the new shard since the move.
- Every shard must be reachable when a router connects. Standby addresses are tried only then. After that there is no automatic failover: a shard whose primary fails is down until it answers again, or until you connect a new router with a map that lists a different address.
- A shard's address cannot change through
reload. Connect a new router instead. - Sharded models cannot have
serialcolumns, and their primary and unique keys must include the shard column. - Global models have rows on the home shard only. The other shards have the table, empty.
- Only ORM row writes inside
begin_forandtransaction_forare checked against the transaction's shard. Plain SQL is not.