Sharding and data locality
Overview
Sharding divides rows across independent database nodes. A shard key identifies the destination; a replica instead copies data for redundancy. Choose a key that distributes load and keeps related records together. The tenant ID in this example is a routing key, not a globally unique order ID. SQLite views model placement; they are not independent servers.
First example
SELECT tenant,CASE WHEN tenant%2=1 THEN 'A' ELSE 'B' END FROM dd_customer ORDER BY tenant;Observed SQLite result (rows in JSON):
[ [ 1, "A" ], [ 2, "B" ], [ 3, "A" ], [ 4, "B" ]]How it works
Positive integer tenant IDs route by tenant % 2: odd to A, even to B. Order 1 exists under multiple tenants, so (tenant,id) identifies an order. A tenant-specific query can target one shard; a global query needs all relevant shards. Range keys can concentrate new writes in one shard; hashing can distribute distinct keys but not a single hot key. Consistent hashing maps keys and node tokens into a circular space to reduce remapping when membership changes; it still needs migration, balancing and routing coordination. The modulo demonstration is not consistent hashing.
Practical example
SELECT 'A',COUNT(*),SUM(amount) FROM dd_aUNION ALLSELECT 'B',COUNT(*),SUM(amount) FROM dd_bORDER BY 1;Observed SQLite result (rows in JSON):
[ [ "A", 3, 225 ], [ "B", 1, 200 ]]Practice and mistakes
Practice: route tenant 4 and tenant 5, then explain why joining only on id is unsafe. Hint 1: compute the remainder. Hint 2: inspect the composite key. Avoid equating sharding with local partitioning or replication.
PostgreSQL 17 example — NOT RUN
WITH tenants(tenant) AS (VALUES (1),(2),(3),(4)) SELECT tenant, mod(tenant,2) AS bucket FROM tenants ORDER BY tenant;Expected result, not executed: "Illustrative routing only, not native sharding. Buckets 1,0,1,0."