Sharding at System Level: Partition Keys, Hot Partitions, Rebalancing, Cross-Shard Queries
"Horizontal sharding was an order of magnitude more complex than our previous scaling efforts." — Sammy Steele, How Figma's databases team lived to tell the scale, Figma engineering blog
Summary: Sharding splits one dataset over many databases so that writes, storage and maintenance scale with the number of machines; the price is that every query, transaction, index, id and schema change must now know where its data lives, and the system must keep working while data moves. Focus: when to shard (the last-resort checklist), partition strategies (range, hash, fixed logical partitions, consistent hashing with virtual nodes, directory/lookup service, composite and geo), choosing the partition key (cardinality, frequency, monotonic keys, hot keys, the celebrity problem, tenant skew, salting), hot partitions (detection, splitting, DynamoDB adaptive capacity, Cassandra wide partitions), rebalancing and resharding online (backfill, catch-up, dual write, verify, cutover; Vitess, Citus, MongoDB balancer, Redis Cluster slot migration), routing (client-side, vtgate, mongos, Citus coordinator, lookup tables), cross-shard queries (scatter-gather and fan-out cost, local versus global secondary indexes, denormalisation, materialised views, CQRS), cross-shard transactions (2PC, sagas, aggregate per shard), global ids, schema changes and multi-tenancy, with Go and Laravel 13 code and four published resharding stories. Learning goal: Given a workload, decide whether to shard at all, pick a partition key and a strategy with a written reason, predict the hot spots and the cross-shard queries before they happen, and plan a resharding that adds capacity without downtime.
This chapter sits in the Consistency & Distributed Data group, after Replication Topologies (copies of the same data) and before Choosing a Database. Replication copies data for availability and read scale; sharding splits it for write scale and size. This page owns the system-level decision, the numbers and the trade-off tables. The mechanics live with their owners: PostgreSQL declarative partitioning, partition pruning and the Citus/FDW mechanics in Partitioning & Sharding in PostgreSQL; the ring, rendezvous and jump hash internals in Consistent Hashing; the vertical-versus-horizontal ladder in Storage & Data Scaling; 2PC and consensus in Distributed SQL, Consensus & 2PC; id schemes in ID Generation at Scale; tenancy models in Multi-Tenancy Strategies; sagas in Saga Pattern; and the fan-out tail in Latency Budgets & Tail Latency.
Page map
| If you are looking for | Go to |
|---|---|
| The whole page in three tables | Everything in one minute |
| Why split a database at all, and when not to | Why it exists, When to shard |
| Sources: DynamoDB, MongoDB, Vitess, Citus, Redis, Cassandra, Notion, Figma, Instagram, Pinterest | Where it comes from |
| What a partition key is and how to choose one | Partition key |
| Range, hash, fixed partitions, ring, directory, composite, geo | Range, Hash, Fixed partitions, Consistent hashing, Directory, Composite keys, Geo sharding |
| One key or one tenant takes all the traffic | Hot partitions, Time keys and salting |
| Adding shards without downtime | Rebalancing, Online moves |
| Who decides which shard a query goes to | Routing |
| Queries without the shard key, secondary indexes, joins | Cross-shard queries, Secondary indexes |
| Transactions across shards | Cross-shard transactions |
| Ids, schema changes, tenants | Global ids, Schema changes, Multi-tenancy |
| Exact knobs, limits and error messages | Mechanics |
| Code | Go, Laravel |
| Celebrity key, time hotspot, whale tenant, global search | Solving the classic problems |
| Notion, Figma, Instagram, Pinterest | Resharding war stories |
| Which strategy for which workload | Choosing |
| Monolith to distributed system | In architecture |
| Measured move cost and drills | Lab |
| Wrong beliefs, summary, quiz, terms | Misconceptions, Cheat sheet, Self-check, Glossary |
Everything in one minute
The strategies.
| Strategy | In plain words | Tiny example | Good at | Bad at |
|---|---|---|---|---|
| Range partitioning | Sorted key ranges, each owned by a shard | a..f on shard 0, g..m on shard 1 | Range scans, ordered reads | Sequential keys pile onto the last range (write hotspot) |
| Hash partitioning | Shard is a function of the key's hash | hash(user_id) mod 4 | Even spread of distinct keys | Range scans touch every shard; mod N moves most keys when N changes |
| Fixed partitions (logical shards) | Hash into P partitions that never change; map partitions to hosts | 1024 partitions on 4 hosts | Cheap, exact rebalancing by moving whole partitions | P must be chosen up front |
| Consistent hashing + virtual nodes | Keys and nodes on a ring; a key belongs to the next node clockwise | 256 vnodes per Cassandra node | Adding a node moves about 1/(N+1) of keys | Load is only statistically even; no range scans |
| Directory / lookup service | A table says where each key or tenant lives | tenant 93 -> shard 7 | Any placement, per-tenant moves, whale isolation | One more lookup, one more thing to keep available and cached |
| Composite / hierarchical key | Route on a prefix, keep the full key unique | route on tenant_id, key (tenant_id, order_id) | Co-location: one tenant's rows on one shard | The prefix's skew is your skew |
| Geo sharding | Place data by region | EU users on EU shards | Latency, data residency | Users who travel or move; cross-region queries |
The problems and their first fix.
| Problem | Symptom | First fix | Section |
|---|---|---|---|
| Hot key / celebrity | One shard at 100% CPU, the others idle | Salt the key, cache the reads, split the entity | Hot partitions |
| Monotonic key | All inserts go to the newest range | Hash the key, or prefix a bucket | Salting |
| Whale tenant | One tenant outgrows its shard | Directory entry: tenant on its own shard | Directory |
| Adding capacity | mod N would move 80% of data | Fixed partitions or a ring; move partitions online | Rebalancing |
| Query without shard key | Every request hits every shard | Global secondary index, lookup table, denormalised copy | Cross-shard queries |
| Two rows on two shards in one transaction | Partial commits | Co-locate by design; saga; 2PC only if you must | Cross-shard transactions |
| Unique ids | Two shards mint the same id = 42 | Snowflake-style ids that embed the shard | Global ids |
Numbers to keep in your head. Each one is from the cited documentation or a published post (see References).
| Fact | Value | Source |
|---|---|---|
| DynamoDB per-partition ceiling | 3,000 read units and 1,000 write units per second | DynamoDB partition key design |
| DynamoDB item collection with an LSI | 10 GB per partition key value | DynamoDB LSI docs |
| MongoDB default chunk (range) size | 128 MB; balancer migrates when shards differ by 3x that (384 MB) | MongoDB balancer docs |
| MongoDB migrations in parallel | One per shard; at most n/2 for n shards | MongoDB balancer docs |
MongoDB reshardCollection write block | Two seconds by default | MongoDB resharding docs |
| Redis Cluster slots | 16384, HASH_SLOT = CRC16(key) mod 16384 | Redis Cluster spec |
| Citus default shards per distributed table | citus.shard_count = 32 | Citus configuration reference |
| Cassandra hard limit per partition | 2 billion cells, "performance issues before reaching that limit" | Cassandra data modelling docs |
| Vitess resharding cutover | "a few seconds of read-only downtime" | Vitess sharding docs |
| Notion 2021 | 480 logical shards on 32 databases (15 per host) | Notion engineering blog |
| Notion 2023 | 32 to 96 hosts, 5 logical shards per host, no downtime | Notion engineering blog |
| Fan-out arithmetic (estimate) | One shard slow 1% of the time: a 100-shard fan-out is slow 1 - 0.99^100, about 63% | Back-of-envelope, see tail latency |
The four panels are the four placement functions you will meet in every product: sorted ranges (cheap range scans, hot last range), a hash (even spread, scattered ranges), a fixed set of hashed logical partitions with an assignment table (the shape behind Redis Cluster slots, Notion's 480 schemas and Instagram's logical shards), and a directory that can place any tenant anywhere.
Why it exists
A single database primary has a ceiling on everything that cannot be offloaded to replicas: write throughput, WAL volume, disk IOPS, table size, connection count, and the time maintenance jobs need. Replicas multiply reads, not writes. Caches remove reads, not writes. Vertical scaling buys time until the largest instance is full. Notion reached that point when "the Postgres VACUUM process began to stall consistently" and transaction ID wraparound became "an existential threat"; Figma's highest-write tables "would soon exceed the maximum IO operations per second (IOPS) supported by Amazon's Relational Database Service". Sharding is the move that makes write capacity and storage grow with the number of machines.
| One database (or primary plus replicas) | Sharded |
|---|---|
| Every query can join, sort and filter over all data | Fast queries name the shard key; the rest fan out |
| One ACID transaction covers any rows | Atomic only within one shard (or with 2PC) |
| Unique and foreign-key constraints enforced by the engine | Enforced only within a shard, or by the application |
| Auto-increment ids are unique | Ids need a global scheme |
| One schema migration | N migrations that must all succeed |
| Capacity ends at the largest machine | Capacity grows with shards, until one key is hot |
| Simple operations, one backup | N backups, N failovers, a routing layer, a topology store |
One analogy, reused through the page: a library with many branches. One building cannot hold every book or serve every reader, so the city opens branches. Each book lives in exactly one branch (a row on one shard). The rule that decides which branch holds a book is the partition key and the strategy: by the first letter of the author (range; the "S" branch is mobbed), by a number derived from the title (hash; even, but "all books from 1990" means visiting every branch), or by a central catalogue that lists each book's branch (directory). A best-seller that everyone wants is a hot key: copies help reading, not returning. Opening a new branch means moving shelves while readers keep borrowing (online rebalancing). A question like "which books mention Tehran?" means asking every branch and merging the answers (scatter-gather). Lending two books from two branches as one atomic loan is a cross-shard transaction.
Three common misunderstandings, up front
- "Sharding is how you scale a database." It is the last way. Indexes, query fixes, caching, read replicas, vertical scaling, archiving and vertical partitioning (splitting tables into separate databases, as Figma did first) are cheaper and reversible. Notion's footnote warns that premature sharding "can constrain the product model before it has been well-defined on the business side."
- "Hashing the key gives an even load." It gives an even spread of distinct keys. One key that receives 20% of the traffic still lands on one shard; the DynamoDB docs say plainly that a single item key can reach at most "3,000 RCUs and 1,000 WCUs".
- "We can choose the key later." The partition key decides which queries are cheap, which transactions are possible and what moves when you rebalance; changing it later is a full data migration (MongoDB's
reshardCollection, VitessReshardto a new vindex, a Notion-style backfill).
Where it comes from
The word and the techniques come from products and teams that had to do it. Every quotation below was read on the saved page.
| Source | What it states | Why it matters here |
|---|---|---|
| Notion, Herding elephants (2021) | Sharded by workspace ID into "480 logical shards evenly distributed across 32 physical databases"; "480 is divisible by a lot of numbers"; migration as "Double-write", "Backfill", "Verification", "Switch-over" | Fixed logical shards, factor-rich counts, the generic migration recipe |
| Notion, The Great Re-shard (2023) | Went "from 32 to 96 machines", "from having 15 schemas per shard to 5", using Postgres logical replication, dark reads and a PgBouncer cutover with reverse replication | What rebalancing fixed partitions looks like in production |
| Figma, How Figma's databases team lived to tell the scale (2024) | "colos" share a sharding key; "we decided to use the hash of the sharding key for routing"; logical sharding through Postgres views before physical sharding; DBProxy does "scatter-gather"; "only ten seconds of partial availability" | Key choice, hashing to avoid hot spots, separating logical from physical sharding |
| Instagram, Sharding & IDs at Instagram (2012) | "several thousand 'logical' shards that are mapped in code to far fewer physical shards"; ids with "13 bits that represent the logical shard ID" | Logical shards and ids that carry their shard |
| Pinterest, Sharding Pinterest (2015) | "once a piece of data lands in a shard, it never moves outside that shard"; a 64-bit id with "The shard ID is 16 bits" | Immutable placement; shards move between hosts, data does not move between shards |
| DynamoDB developer guide | Per-partition 3,000 RCU / 1,000 WCU; adaptive capacity; write sharding with suffixes "2014-07-09.1" to ".200"; GSIs updated "in an eventually consistent fashion" | Managed hash partitioning and its hot-key limits |
| MongoDB manual | Choose a shard key by "cardinality", "frequency" and "whether a potential shard key grows monotonically"; mongos "broadcast" operations; "A single shard can only participate in one chunk migration at a time" | The shard-key checklist and the balancer |
| Vitess docs | Key ranges and keyspace IDs; "Resharding ... with only a few seconds of read-only downtime"; Primary Vindex values "cannot be updated after insertion" | Proxy routing, range-based shards, online resharding workflow |
| Citus docs | "Choosing the distribution column for each table is one of the most important modeling decisions"; "Do not choose a timestamp as the distribution column"; citus_rebalance_start | Co-location and distributed PostgreSQL |
| Redis Cluster spec | 16384 slots, CRC16(key) mod 16384, hash tags, MIGRATING/IMPORTING, -MOVED and -ASK | Fixed partitions with client-side routing and live slot migration |
| Cassandra docs | Vnodes from the Dynamo paper; "Cassandra's hard limit is 2 billion cells per partition"; bucketing to break up large partitions | Wide partitions and the ring |
| Karger et al. (1997), Dynamo (2007) | Consistent hashing; virtual nodes | The theory behind ring placement; details in Consistent Hashing |
| Kleppmann, Designing Data-Intensive Applications | Chapter 6, Partitioning: key-range and hash partitioning, skew and hot spots, secondary indexes by document and by term, rebalancing, request routing | The standard conceptual reference; not quoted here (the author's page does not reproduce chapter text) |
The concept catalogue
Each block follows the same order: plain words, the usual wrong belief, a definition, a sequence, real scenarios, how products provide it, and how to use it.
When to shard: the last-resort checklist Must-know
In plain words: shard when one primary cannot take the writes, the data or the maintenance any more, and every cheaper move has been made or measured.
Common misunderstanding: "We will need it eventually, so do it now." Sharding early fixes a partition key before the product knows its own access patterns. Notion's footnote: "if a team shards by user and subsequently pivots to a team-focused product strategy, the architectural impedance mismatch can cause significant technical pain". The opposite mistake is waiting until the database is on fire: Notion's lesson was "Shard earlier", because a saturated primary leaves no headroom for the migration itself.
Definition: sharding (horizontal partitioning across databases) is justified when a measured limit of a single primary will be reached within your migration lead time (months), and the limit is one that replicas, caches and bigger hardware do not move.
Limit you measure Cheaper move first Shard when
1 Read QPS / CPU from reads Indexes, caching, read replicas Never for reads alone
2 Write QPS, WAL volume, IOPS Batching, vertical scaling, archiving Projected growth crosses the largest instance
3 Table size (vacuum, index builds) Partition the table on one host Maintenance windows stop fitting
4 One tenant or table dominates Vertical partitioning (own database) That one table still does not fit
5 Data residency per region Separate regional deployments Users in several regions share one productReal scenario: Notion's VACUUM stalls and TXID wraparound risk; Figma's IOPS ceiling on RDS after a dozen vertical partitions; a SaaS whose largest tenants need isolation for noisy-neighbour reasons; an analytics event table growing by terabytes per month.
The checklist, with who owns the detail:
| Step | Question | If yes | Owner page |
|---|---|---|---|
| 1 | Is the bottleneck reads? | Replicas and caching, not shards | Replication Topologies, Caching |
| 2 | Are queries and indexes already tuned? | Fix them first; a bad plan scales badly on N shards too | Query Planning |
| 3 | Is one table huge but the workload on one host fine? | Partition the table on one database | Partitioning & Sharding in PostgreSQL |
| 4 | Can whole tables move to their own database? | Vertical partitioning | Storage & Data Scaling |
| 5 | Can you buy one more instance size? | Buy time, plan the shard | Scaling Strategies |
| 6 | Is there a key that most queries and transactions already include? | You can shard with few cross-shard queries | Partition key |
| 7 | Would a distributed SQL database or a managed service do it for you? | Compare Vitess, Citus, CockroachDB, Spanner, DynamoDB before building | Choosing |
How to use it: write the limit as a number with a date ("primary IOPS at 70% of the instance maximum by Q3"), estimate with the method in Capacity Estimation, and start the shard project with at least one doubling of headroom left.
Partition key (shard key) Must-know
In plain words: the column whose value decides which shard a row lives on. MongoDB calls it the shard key, Citus the distribution column, Vitess the column behind the Primary Vindex, DynamoDB and Cassandra the partition key.
Common misunderstanding: "Pick the primary key." The primary key is unique, which gives perfect spread, but most queries are not by primary key: "all orders of tenant 7" would scatter over every shard. The right key is the one your queries and transactions group by.
Definition: a partition key is a field (or prefix of fields) present in every row of a sharded table, used by the placement function, and ideally present in every frequent query and every transaction. MongoDB's manual lists three properties: "the cardinality of the shard key", "the frequency with which shard key values occur", and "whether a potential shard key grows monotonically".
Candidate key Cardinality Frequency skew Monotonic Queries that include it Verdict
1 order_id very high none yes (seq) few (by tenant mostly) scatter for tenant pages
2 created_at very high all writes are "now" yes reports only write hotspot
3 country ~200 huge (US, IN, ...) no some too few, too skewed
4 tenant_id high a few whales no almost all good, plan for whales
5 hash(tenant_id) high whales still whales no almost all good spread, no tenant rangesReal scenario: Notion chose workspace ID because "users typically query data within a single workspace at a time"; Figma chose "a handful of sharding keys like UserID, FileID, or OrgID"; Citus recommends tenant ID for multi-tenant apps and entity ID (user, host, device) for real-time analytics; a chat system keys messages by channel.
What each product calls it and what it enforces:
| Product | Name | Can it change later? | Notes |
|---|---|---|---|
| MongoDB | Shard key (ranged or hashed, compound allowed) | refineCollectionShardKey adds suffix fields; reshardCollection changes it (copies the collection) | analyzeShardKey (7.0+) measures cardinality, frequency and monotonicity from sampled queries |
| Vitess | Primary Vindex column | Values "cannot be updated after insertion"; a new vindex means a Reshard/MoveTables | Secondary and lookup vindexes route other columns |
| Citus | Distribution column | alter_distributed_table rewrites the table | "Include distribution column in keys" |
| DynamoDB | Partition key (+ optional sort key) | No; create a new table and copy | Key design is the capacity plan |
| Cassandra | Partition key (first part of the primary key) | No; new table | Clustering columns sort rows inside the partition |
| Redis Cluster | The key, or the {hash tag} inside it | Rename the key | Only the tag is hashed |
How to use it: list the top queries and transactions by frequency; choose the key that appears in nearly all of them; check cardinality (many more distinct values than shards), frequency (no value with a large share) and monotonicity (no "now" or sequence prefix); write down the queries that will scatter and how each one is served instead.
Range partitioning Must-know
In plain words: keep keys sorted and give each shard a contiguous slice.
Common misunderstanding: "Ranges are balanced if I split them evenly." Even key space is not even data or traffic: names cluster on common letters and time-ordered keys put every new write in the last range.
Definition: the placement function finds the range [lower, upper) that contains the key. Vitess uses this on the keyspace ID ("A key falls inside the range if it is equal to or greater than the start value and strictly less than the end value"); MongoDB ranged sharding, HBase, Bigtable and Spanner split ranges as they grow.
Inserts with key = created_at (monotonic)
1 shard A [.., 2026-01) idle
2 shard B [2026-01, 2026-06) idle
3 shard C [2026-06, ..) every insert, every index update, every lock
4 range C splits at 2026-11; the new upper half is again the only one receiving insertsReal scenario: time-series reads "last 24 hours" (one range), alphabetical directories, Bigtable-style row keys like reversed_domain#path, MongoDB collections sharded by { region: 1, date: 1 } with zones per region.
Where it helps and hurts:
| Product | Range mechanism | Hotspot help |
|---|---|---|
| MongoDB | Ranged sharding, chunks of 128 MB default, zones on key ranges | "If your data model requires sharding on a key that changes monotonically, consider using Hashed Sharding." |
| Vitess | Shards are keyspace ID ranges (-80, 80-); the vindex decides whether keyspace IDs are hashed | Use the hash or xxhash vindex for sequential ids |
| HBase / Bigtable | Regions or tablets split by size | Salt or reverse the row key prefix |
| Spanner, CockroachDB | Automatic range splits by size and load | Avoid monotonically increasing primary keys |
How to use it: use range partitioning when range scans on the key dominate and writes are not monotonic, or when the range is a coarse bucket (tenant, region) and the time part comes after it.
Hash partitioning Must-know
In plain words: hash the key and let the hash pick the shard, so neighbouring keys land far apart.
Common misunderstanding: "hash(key) % N is hash partitioning." It is the worst version of it: when N changes from 4 to 5 about 80% of keys change shard (measured in the Lab). Real systems hash into a fixed number of partitions or onto a ring.
Definition: shard = f(hash(key)). The hash must be stable across processes, languages and versions (Redis Cluster specifies CRC16; this chapter's Go and PHP code share CRC-32). Figma "decided to use the hash of the sharding key for routing" because their keys "used auto-incrementing or Snowflake timestamp-prefixed IDs", accepting that "range-scans on shard keys are less efficient".
Real scenario: user ids, device ids, session ids, any key with high cardinality and point lookups; DynamoDB and Cassandra partition keys; MongoDB { _id: "hashed" } for ObjectId values; Citus distributed tables.
Products:
| Product | Hash | What you control |
|---|---|---|
| DynamoDB | Internal hash of the partition key | Only the key design |
| Cassandra | Murmur3Partitioner tokens on a ring | Partition key, num_tokens |
| MongoDB | Hashed shard key (compound hashed allowed) | Which field is hashed |
| Citus | Hash of the distribution column into citus.shard_count shards | Distribution column, shard count, co-location |
| Vitess | hash / xxhash vindex to a keyspace ID, then ranges | Vindex type and shard ranges |
| Redis Cluster | CRC16 into 16384 slots | Hash tags |
How to use it: never mod N over physical shards; hash into fixed partitions or a ring; keep the hash function in one shared library (and its test vector, see Go) because changing it moves every row.
Fixed partitions and logical shards Must-know
In plain words: decide once that there are, say, 1024 partitions; hash every key into one of them; then keep a small table that says which host holds which partitions. Growing the cluster moves whole partitions and edits the table.
Common misunderstanding: "More partitions than hosts is waste." Each partition is cheap (a schema, a slot, a vBucket); having many is what lets you move a little data at a time and keep shards even. Too few is the real risk: Notion picked 480 because "480 is divisible by a lot of numbers", while "Any power of 2 would require us to double the number of physical hosts to upscale".
Definition: a two-level map: key -> partition (fixed function, never changes) and partition -> host (a table, changes on rebalance). This is the fixed-number-of-partitions rebalancing strategy in DDIA and the shape of Redis Cluster's 16384 slots, Couchbase vBuckets, Instagram's "several thousand 'logical' shards", Pinterest's 4096 initial shards and Notion's 480 schemas.
Notion 2021 -> 2023 (from the published posts)
1 480 logical shards (Postgres schemas schema001..schema480) on 32 hosts, 15 per host
2 logical replication: 3 publications per old host, 5 schemas each
3 96 new hosts subscribe; each receives 5 schemas
4 PgBouncer mapping flips per host; reverse replication back to the old host for rollback
5 result: 96 hosts x 5 schemas = 480, no key changed partitionReal scenario: Notion's space shards; Instagram's PL/pgSQL id function per schema; Pinterest's db00000 to dbNNNNN databases; Redis Cluster resharding with redis-cli --cluster reshard.
Choosing P:
| P | Example | Pro | Con |
|---|---|---|---|
| Equal to hosts | mod 4 | Simple | Every resize remaps almost everything |
| Factor-rich | 480 (Notion) | Even splits at 32, 40, 48, 60, 80, 96 hosts | A partition is 1/480 of data; fine-grained moves need more |
| Large power of two | 1024, 4096 (Pinterest), 16384 (Redis) | Fine-grained moves, easy bit arithmetic | More metadata, many tiny schemas if each is a database object |
| Unbounded / dynamic | MongoDB chunks, HBase regions | Grows with data | Needs a splitter and a balancer |
How to use it: pick P at least 10x to 100x the largest host count you can imagine, factor-rich if partitions are heavy objects (schemas, databases); store the partition table in one place with a version; generate moves with a planner (Go shows one) instead of by hand.
Consistent hashing and virtual nodes Important
In plain words: put both keys and nodes on a circle of hash values; each key belongs to the next node clockwise. Give each node many points (virtual nodes) so the slices even out.
Common misunderstanding: "Consistent hashing means no data moves when you add a node." About 1/(N+1) of the keys move, all of them to the new node, which is the minimum; with one point per node the load is badly uneven (the Lab measured a 62x spread between the busiest and quietest of five shards).
Definition: the technique of Karger et al. (1997) used by Dynamo and Cassandra; vnodes were introduced because, in the Cassandra docs' words, single-token hashing with few nodes makes "token selections" for even growth impossible. Rendezvous and jump hashing are alternatives; all internals are in Consistent Hashing.
Real scenario: Cassandra and ScyllaDB clusters (num_tokens), Amazon Dynamo, memcached client libraries such as ketama, Envoy's ring-hash and Maglev load balancing for sticky upstreams.
| Placement | Keys moved when 4 -> 5 nodes | Load spread at 5 nodes (max/min) | Used by |
|---|---|---|---|
mod N | about 80% | about 1.0 | Naive code |
| Ring, 1 point per node | about 20% to 40% | very uneven | Early Dynamo-style rings |
| Ring, 256 vnodes per node | about 20% | about 1.3 | Cassandra (older default), Riak |
| Fixed partitions + planner | exactly the planned partitions (about 20%) | 1.0 by construction | Redis Cluster, Notion, Couchbase |
How to use it: use a ring when membership changes often and no central table is wanted (caches, peer-to-peer stores); use fixed partitions with a table when you want exact control and auditable moves (databases).
Directory-based sharding (lookup service) Important
In plain words: a table says where each key, tenant or partition lives; ask it before you query.
Common misunderstanding: "A lookup on every request is too slow." The directory is small, read-mostly and cached on every app server with a short TTL; the cost is one cache hit. The real costs are availability (it must be as available as the shards) and staleness during moves.
Definition: directory-based partitioning ("using an intermediate lookup table to route all reads and writes", as Notion's footnote puts it) maps keys to shards explicitly, usually with a fallback function for keys without an entry. Vitess lookup vindexes are a sharded directory ("Lookup Vindexes are sometimes also informally referred to as cross-shard indexes"); Pinterest's "mod shard" maps arbitrary inputs such as Facebook IDs and emails to shards.
Request for tenant 93 Directory (cached 30 s) Shards
1 resolve(93) -> cache miss
2 SELECT connection FROM shard_directory WHERE tenant_id = '93' -> no row
3 fallback: crc32('93') % 1024 = partition p -> map -> shard_2
4 cache (93 -> shard_2), query shard_2
5 later: ops pins whale tenant 7 to shard_9 (row written, version + 1, cache forgotten)Real scenario: a B2B SaaS that moves a large customer to dedicated hardware; per-tenant data residency (tenant 41 must stay in Frankfurt); "where is email x" for login before the user id is known; Figma's topology library mapping tables to shard keys and logical shard IDs to physical databases.
| Product | Directory form |
|---|---|
| Vitess | lookup, consistent_lookup, consistent_lookup_unique vindexes; the topo server holds the shard map |
| MongoDB | Config servers hold the chunk-to-shard map; mongos caches it |
| Citus | pg_dist_shard and pg_dist_placement metadata on the coordinator; isolate_tenant_to_new_shard |
| Redis Cluster | Each node knows the slot map; clients cache it and follow -MOVED |
| Application | A shard_directory table plus a cache (the Laravel resolver) |
How to use it: keep the directory tiny (tenants or partitions, not rows), replicated, cached with a TTL shorter than your freeze window, versioned, and with a state column (active, moving) so moves can freeze writes for one tenant.
Composite keys, hierarchical keys and co-location Must-know
In plain words: route on the first part of a key (the tenant), keep the full key unique (tenant plus order), and give every related table the same first part so they all land on the same shard.
Common misunderstanding: "Co-location means duplicating data." It means choosing the same partition key for tables that are joined or written together, so their rows are on the same shard without copying.
Definition: a composite (compound) key routes on a prefix and orders or identifies within it. Co-location, in the Citus docs' words, is when "all tables in the database have a common distribution column and are sharded across machines in the same way, such that rows with the same distribution column value are always on the same machine, even across different tables". Figma's colos are the same idea: "Tables within a colo support cross-table joins and full transactions when restricted to a single sharding key". DDD gives the rule of thumb: shard by the aggregate root, one aggregate per shard.
tables key shard for tenant 7
1 tenants (tenant_id) shard_2
2 orders (tenant_id, order_id) shard_2
3 order_lines (tenant_id, order_id, line) shard_2
4 JOIN orders/order_lines WHERE tenant_id = 7 -> one shard, one ACID transaction
5 countries reference table copied to every shard (Citus create_reference_table)Real scenario: Notion sharded "all tables reachable from the block table via some kind of foreign key relationship" and regretted keeping id and space_id separate ("we could've combined both keys into a single new column"); DynamoDB single-table design with PK = TENANT#7, SK = ORDER#9; Cassandra PRIMARY KEY ((tenant_id), created_at, order_id).
How to use it: put the partition key in every primary key and unique index of sharded tables (Citus: "Include distribution column in keys"; Figma: unique indexes "only supported on indexes including the sharding key"); replicate small shared tables to every shard as reference tables; name the few relations that cross aggregates and serve them asynchronously.
-- Citus: co-located distributed tables plus a reference table.
SELECT create_distributed_table('tenants', 'tenant_id');
SELECT create_distributed_table('orders', 'tenant_id', colocate_with => 'tenants');
SELECT create_distributed_table('order_lines', 'tenant_id', colocate_with => 'orders');
SELECT create_reference_table('countries');
-- Router query: one shard, full SQL, joins pushed down.
SELECT o.order_id, sum(l.price_cents)
FROM orders o JOIN order_lines l USING (tenant_id, order_id)
WHERE o.tenant_id = 7 GROUP BY o.order_id;Geo sharding Good to know
In plain words: keep each user's data in the region they live in, for latency and for law.
Common misunderstanding: "Geo sharding is a CDN for the database." Data has one home; a user who travels reads across regions, and a query over all users crosses every region.
Definition: placement by a region attribute (country, home region, tenant's chosen region), usually as the leading component of a composite key or a directory entry. MongoDB zone sharding pins key ranges to shards in a region; CockroachDB and Spanner offer regional placement; DynamoDB global tables replicate rather than shard.
Real scenario: EU customer data that must stay in the EU (GDPR data-residency commitments); ride-hailing trips stored in the city's region; a game with regional servers (the Ultima Online origin of the word "shard" that Notion's post mentions).
How to use it: make region part of the routing key or directory; assign the home region at sign-up and support explicit moves; keep global data (accounts, billing) separate; never assume "nearby" for queries that cross regions.
Hot partitions, hot keys, skew and the celebrity problem Must-know
In plain words: one partition or one key gets far more traffic than the rest, so one shard is overloaded while the others are idle.
Common misunderstanding: "Adding shards fixes a hot partition." Adding shards spreads other keys; the hot key still maps to exactly one shard. You have to split the key, cache it, or change the access pattern.
Definition: skew is uneven data or load across partitions; a hot partition is one that receives disproportionate traffic; a hot key is a single key responsible for it. The celebrity problem is the social-network version: one account with tens of millions of followers whose reads (and fan-out writes) dwarf everyone else's. Wide partitions are the size version: Cassandra partitions that grow towards "2 billion cells per partition"; DynamoDB item collections limited to 10 GB when the table has an LSI (ItemCollectionSizeLimitExceededException).
t writes/s for key "celebrity" partition P7 (limit 1,000 WCU) others
1 09:00 200 20% 20%
2 09:05 (viral post) 4,000 burst capacity absorbs a few seconds
3 09:06 4,000 throttled: ProvisionedThroughputExceededException
4 09:07 adaptive capacity isolates the item on its own partition: still 1,000 WCU max
5 09:10 app salts the key into 8 sub-keys: 8 partitions x 500 = OKReal scenario: a celebrity's follower list or like counter; a flash-sale product row; one enterprise tenant that "generates more load than many average personal workspaces combined" (Notion); a status = 'pending' partition key in a job table; the "today" partition of a time-keyed table; Notion's 2023 note that more hosts "reveals outliers in database consumption".
Detection and response by product:
| Product | How you see it | Built-in help | You still need |
|---|---|---|---|
| DynamoDB | CloudWatch throttling metrics, Contributor Insights top keys | Burst capacity (up to 300 s of unused capacity), adaptive capacity, split for heat | Salting for anything above 1,000 WCU / 3,000 RCU per key |
| Cassandra / ScyllaDB | nodetool tablestats large partition warnings, nodetool toppartitions | None for one key | Bucketing the partition key |
| MongoDB | sh.status(), $collStats, jumbo chunk flags, analyzeShardKey frequency | Chunk splits and balancer (cannot split one key) | Compound shard key with a high-cardinality suffix |
| Redis Cluster | redis-cli --hotkeys (LFU policy), slot load per node | None | Split the value, read replicas, client-side cache |
| Vitess / Citus | Per-shard QPS and CPU; Citus citus_stat_tenants | Citus isolate_tenant_to_new_shard | A directory entry or tenant isolation |
How to use it: measure top keys continuously (a Space-Saving detector is in Go, the broader algorithms in Top-K & Heavy Hitters); cache hot reads; salt hot writes (next block); isolate whale tenants with a directory; for counters, use sharded counters.
Time-based keys, write hotspots and key salting Must-know
In plain words: if the partition key is "now", every write goes to the same place; add a suffix (salt) so the same logical key is spread over several partitions, and make reads ask all of them.
Common misunderstanding: "A random suffix makes reads impossible." Point reads can use a calculated suffix (hash of another attribute you know at read time); only "all items of this key" needs to query every suffix and merge.
Definition: key salting (write sharding, suffixing) expands one hot partition key into N sub-keys. DynamoDB's guide: "You can add a random number to the partition key values to distribute the items among partitions. Or you can use a number that is calculated based on something that you're querying on", with the example 2014-07-09.1 through 2014-07-09.200, and the cost: "to read all the items for a given day, you would have to query the items for all the suffixes and then merge the results". Cassandra calls the same move bucketing ("adding a month column to the partition key"). Citus says "Do not choose a timestamp as the distribution column."
Write path (random salt, N = 8) Read path ("all events of 2026-11-26")
1 key = "2026-11-26" for s in 0..7:
2 s = rand(0..7) Query("2026-11-26#s") -> 8 parallel queries
3 put("2026-11-26#" + s, event) merge, sort by time
4 8 partitions share the day's writes cost: 8 reads instead of 1Real scenario: IoT readings keyed by date; a leaderboard keyed by game; DynamoDB sales events keyed by day; Kafka-style ingestion into a table keyed by hour; MongoDB { day: 1, _id: "hashed" } compound hashed keys.
| Choice | How to pick the suffix | Point read | Full read |
|---|---|---|---|
| Random salt | rand(0..N-1) | Must query all N | Query all N and merge |
| Calculated salt | hash(order_id) mod N | One query (recompute the suffix) | Query all N and merge |
| Time bucket in the key | (sensor_id, month) | One partition per bucket | One query per bucket |
| Hash the time key | Hashed shard key on _id | Fine by id | Range by time scatters |
How to use it: size N from the rate and the per-partition limit (SaltFactor in Go: 4,000 writes/s against 1,000 WCU at 70% target is 8); salt only the keys that are hot (a directory of hot keys, or apply salting to the time-bucket key type only); keep N fixed for a key once written, or record it with the key.
Rebalancing and resharding Must-know
In plain words: rebalancing moves partitions between existing or new shards to even out load; resharding changes the number of shards or the key itself. Both must happen while the application keeps reading and writing.
Common misunderstanding: "Rebalancing is a background job you turn on." Every move copies data, adds load to a shard that is often already the busiest, and ends with a cutover that must not lose writes. MongoDB restricts "a shard to at most one migration at any given time" for exactly this reason.
Definition: the three classic strategies (DDIA chapter 6): a fixed number of partitions moved whole between nodes (Redis Cluster, Couchbase, Notion); dynamic splitting where a partition that grows past a size splits and halves migrate (MongoDB chunks, HBase regions, Spanner and CockroachDB ranges); and partitioning proportional to nodes on a ring with vnodes (Cassandra). Resharding a key or changing the shard count in place uses product workflows: Vitess Reshard, MongoDB reshardCollection, Citus citus_rebalance_start and alter_distributed_table.
MongoDB range migration (from the manual's procedure)
1 balancer sends moveRange to the source shard
2 source keeps serving all reads and writes for the range
3 destination builds indexes, then copies the documents
4 destination applies changes that happened during the copy
5 source updates the config servers with the new owner (cutover)
6 source deletes its copy once no cursors use the range (range deleter, asynchronous)Real scenario: adding a host for the new-year traffic spike (Notion, "tripling the number of instances in our fleet from 32 to 96"); splitting customer/0 into -80 and 80- in Vitess; moving a hot tenant to its own shard in Citus; draining a node before decommissioning it.
Per-product rebalancing:
| Product | Unit moved | Trigger | Throttle | Cutover |
|---|---|---|---|---|
| MongoDB | Range (chunk), 128 MB default | Balancer when shards differ by 3x range size | One migration per shard, at most n/2 in parallel; balancing window | Metadata update on config servers; reshardCollection blocks writes up to two seconds |
| Vitess | Shard key range via VReplication | Operator: Reshard ... create | VReplication throttler | SwitchTraffic (replica then primary), ReverseTraffic to roll back, complete |
| Citus | Shard (and its co-located group) | Operator: citus_rebalance_start() | citus.max_background_task_executors_per_node (default 1); co-located shards move sequentially | Non-blocking since Citus 11.0 (logical replication) |
| Redis Cluster | Hash slot | Operator: redis-cli --cluster reshard / rebalance | Keys moved with MIGRATE in batches | CLUSTER SETSLOT <slot> NODE; clients follow -ASK during, -MOVED after |
| Cassandra | Token ranges | Node joins or leaves (bootstrap, decommission) | stream_throughput_outbound | Gossip of the new token ownership |
| DynamoDB | Partitions | Automatic on throughput or size, split for heat | Not exposed | Transparent |
How to use it: prefer a strategy where the key-to-partition function never changes; plan moves with a tool that computes the minimum set and schedules waves within a per-shard limit (rebalance.Compute and rebalance.Waves in Go); run the heaviest shards' moves first; watch replication lag and p99 during the copy; keep a rollback path until the grace period ends.
Moving data online: dual write, backfill, catch-up, verify, cutover Must-know
In plain words: copy the old data, keep copying new changes, check the copy, stop writes for a moment, flip the routing, and keep a way back.
Common misunderstanding: "Dual writes from the application are the simple way." Two independent writes can each fail; Notion rejected "Write directly to both databases" as "too flaky for critical-path production datastores", and Figma wanted "to avoid complex solutions like double-writes". A replication stream (binlog, WAL logical replication, CDC, an audit log) is the reliable catch-up mechanism.
Definition: an online move has phases: backfill (copy a snapshot), catch-up (apply changes made since the snapshot, from a change stream), verify (counts, checksums, dark reads), freeze (block writes for the moving key range for seconds), cutover (flip routing, bump the topology version), rollback window (reverse replication from the new owner to the old), cleanup (delete the old copy). Notion's framework was "Double-write", "Backfill", "Verification", "Switch-over"; Vitess runs it as VReplication, VDiff and SwitchTraffic.
Vitess Reshard customer/0 -> -80, 80- (commands from the Vitess user guide)
1 vtctldclient Reshard --target-keyspace customer --workflow cust2cust create --source-shards '0' --target-shards '-80,80-'
2 (VReplication copies rows, then streams the binlog)
3 vtctldclient VDiff --target-keyspace customer --workflow cust2cust create
4 vtctldclient Reshard --target-keyspace customer --workflow cust2cust SwitchTraffic --tablet-types=rdonly,replica
5 vtctldclient Reshard --target-keyspace customer --workflow cust2cust SwitchTraffic
6 vtctldclient Reshard --target-keyspace customer --workflow cust2cust complete
7 vtctldclient DeleteShards --recursive customer/0Real scenario: Notion's 2021 audit-log catch-up (chosen because logical replication "struggled to keep up with block table write volume during the initial snapshot step") and three-day backfill on 96 CPUs; Notion 2023 skipping indexes during the copy ("Total time to synchronize the machines decreased from 3 days to 12 hours!"); Figma's "Full logical replication" with reads and writes restricted to each shard's subset; Redis MIGRATING/IMPORTING slots where new keys go to the target immediately.
| Catch-up mechanism | Pro | Con | Used by |
|---|---|---|---|
| Application dual write | No database feature needed | Partial failures diverge the copies; ordering issues | Avoided by Notion and Figma |
| Database log (binlog, WAL logical replication) | Complete, ordered, transactional | Snapshot can lag on very hot tables; schema must match | Vitess VReplication, Notion 2023, Citus 11+ |
| CDC to a stream (Debezium) | Decoupled, replayable, transformable | One more system; at-least-once | Change Data Capture |
| Audit log table plus catch-up script | Can transform rows (add the partition key) | Write amplification on the source | Notion 2021 |
| Version-checked backfill | Idempotent, order-independent with catch-up | Needs a version or updated_at column | Notion: "compare record versions before writing old data" |
How to use it: never cut over without verification by a different implementation (Notion: "the migration and verification logic were implemented by different people"); make backfill idempotent (upsert by primary key, skip newer versions); freeze per key range, not globally; make every router reject or refresh on a stale topology version; keep reverse replication until the grace period ends.
Routing: client-side, proxy and lookup Important
In plain words: something has to turn "tenant 17" into "connect to shard 2". It can be a library in the application, a proxy in front of the shards, or a lookup service the application asks first.
Common misunderstanding: "A proxy makes sharding invisible." A proxy hides where data is; it cannot make a query without the shard key cheap, or a cross-shard join free. Figma's DBProxy supports "the most common 90% of queries" for that reason.
Definition: request routing (DDIA's term) is the component that knows the partition map and sends each request to the right shard, or to many. Vitess: "VTGate is a lightweight proxy server that routes traffic to the correct VTTablet servers and returns consolidated results back to the client." MongoDB's mongos routes "queries to only the shards that contain the relevant data if the queries contain the shard key", otherwise broadcasts. The Citus coordinator plans router (single-shard) and multi-shard queries. Redis Cluster clients route themselves and follow redirections.
Redis Cluster slot migration seen by a client (from the cluster spec)
1 CLUSTER SETSLOT 8 IMPORTING A (sent to B)
2 CLUSTER SETSLOT 8 MIGRATING B (sent to A)
3 client GET k (slot 8) -> A: key still on A -> value
4 client GET k2 (slot 8) -> A: key already moved -> -ASK 8 <B>
5 client -> B: ASKING, GET k2 -> value (one-off redirect, map unchanged)
6 migration done: CLUSTER SETSLOT 8 NODE B; next request to A -> -MOVED 8 <B>; client updates its mapReal scenario: a Go service using a sharding library with a cached map; PlanetScale or self-hosted Vitess behind vtgate speaking the MySQL protocol; MongoDB drivers talking only to mongos; PgBouncer as Notion's routing point during cutover; Laravel resolving a connection per tenant.
| Router | Where it runs | Knows the map from | Handles a query without the key |
|---|---|---|---|
| Application library | In each app process | Config, directory table, or topology service | Your code does scatter-gather |
| Vitess vtgate | Stateless proxy tier | Topo server (etcd, ZooKeeper, Consul) | Scatter, with vindex help; olap workload for analytics |
| MongoDB mongos | Stateless router tier | Config server replica set | Broadcast operation, merges results |
| Citus coordinator | PostgreSQL node with metadata | pg_dist_* catalogs | Multi-shard query, parallel over workers |
| Redis Cluster client | In each app process | CLUSTER SHARDS / CLUSTER SLOTS, -MOVED | Not allowed across slots (CROSSSLOT) |
| Figma DBProxy | Go service before PgBouncer | Topology library | Its own scatter-gather engine |
How to use it: version the partition map; make routers refuse or refresh on version mismatch during cutovers (-MOVED is Redis's way); keep the router stateless and horizontally scaled; log which queries scatter so you can remove them.
Cross-shard queries: scatter-gather and fan-out Must-know
In plain words: a query that does not name the shard key must ask every shard and merge the answers; that costs N times the work and waits for the slowest shard.
Common misunderstanding: "Scatter-gather is fine because shards answer in parallel." Total work grows with N, so throughput does not scale with shards for those queries, and latency is the maximum of N latencies: the tail of the slowest shard becomes your median (see Latency Budgets & Tail Latency).
Definition: a scatter-gather (broadcast, fan-out) query is sent to every shard (scatter) and the partial results are combined (gather): concatenation, k-way merge for ORDER BY, re-applied LIMIT (mongos "passes that limit to the shards and then re-applies the limit"), additive aggregates (COUNT, SUM), and decomposed ones (AVG = sum of sums / sum of counts). MongoDB: "Queries that involve multiple shards for each request are less efficient and do not scale linearly". Figma: "having too many scatter-gathers would impact horizontal sharding scalability."
"Newest 20 orders for customer email x", 4 shards, no shard key
1 router -> shard 0..3: SELECT ... WHERE email = x ORDER BY created_at DESC LIMIT 20
2 shard 0: 20 rows in 4 ms; shard 1: 3 rows in 5 ms; shard 2: 0 rows in 6 ms
3 shard 3: 20 rows in 180 ms (vacuum running)
4 router: k-way merge of 43 rows, keep 20, respond at ~180 ms
5 with OFFSET 1000: every shard must return 1020 rows -> deep pagination is O(N x offset)Real scenario: support tools searching by email or phone; admin dashboards with global counts; "trending" across all users; analytics scans (where MongoDB notes scatter-gather "can be a useful approach that allows the query to run in parallel on all shards").
How to serve the query without scattering:
| Technique | How | Cost | Products |
|---|---|---|---|
| Put the key in the query | Pass tenant or user id from the session | Application changes | Figma "shadow application readiness" to find violators |
| Global secondary index | An index partitioned by the other attribute | Asynchronous, eventual consistency, write amplification | DynamoDB GSI, Vitess lookup vindex |
| Lookup table | email -> user_id -> shard | One more write per insert, one more read | Pinterest mod shard, Vitess consistent_lookup_unique |
| Denormalisation | Copy the field onto the queried table | Update fan-out when the source changes | Cassandra query-first tables, customer_email on orders |
| Materialised view / read model | A separate store built from events or CDC | Staleness, a pipeline to run | Cassandra materialised views (experimental), Event Sourcing & CQRS, Elasticsearch |
| Scatter with limits | Bounded concurrency, per-shard deadline, partial results flag | N x work; tail latency | Go ScatterGather, Laravel Concurrency::run |
| Offline analytics | Ship all shards to a warehouse | Hours of delay | CDC to a lake, Figma's Snowflake for query-plan analysis |
How to use it: keep scatter-gather to admin paths, with a per-shard deadline and an explicit partial-results policy; each shard must return its own top LIMIT (not LIMIT / N); use keyset pagination rather than OFFSET; move hot non-key lookups to a global index or a lookup table.
Secondary indexes: local versus global Important
In plain words: a local index lives next to the data on each shard (cheap to write, but a lookup asks every shard); a global index is itself partitioned by the indexed value (one lookup, but every write updates another partition, asynchronously).
Common misunderstanding: "A secondary index on a sharded table works like on one database." A local index is document-partitioned (DDIA): each shard indexes only its rows, so "find by email" still scatters. A global index is term-partitioned: fast to read, but kept up to date across shards, usually asynchronously.
Definition: DynamoDB names both. A local secondary index (LSI) "is organized by the same partition key as the base table", supports strongly consistent reads, must be created with the table ("Local secondary indexes on a table are created when the table is created") and caps an item collection at 10 GB. A global secondary index (GSI) has its own partition key; it is updated "asynchronously, using an eventually consistent model", supports only eventually consistent reads, and can throttle the base table: writes "can be throttled if the GSI activity resulting from writes to the base table exceeds the GSI's provisioned write capacity".
T base table (PK = user_id) GSI (PK = email)
1 T1 PutItem user 7, email a@example.com
2 T1 write acknowledged
3 T2 Query GSI email = a@example.com -> not found yet (asynchronous)
4 T3 GSI updated a@example.com -> user 7
5 T4 Query GSI -> user 7Real scenario: login by email in a table partitioned by user id; "orders by status" for an operations screen; uniqueness of usernames across shards (a global index or lookup table with a unique key, because a local unique index only guarantees uniqueness inside one shard).
| Product | Local index | Global index |
|---|---|---|
| DynamoDB | LSI: same partition key, strong reads, 10 GB per key value, at creation only | GSI: own key, eventual, separate capacity, back-pressure on base writes |
| Cassandra | Secondary indexes / SAI are local to each node; queries without the partition key fan out | No built-in global index; denormalised tables or materialised views |
| MongoDB | Every index is local to its shard; non-shard-key queries broadcast | No global index; unique indexes must include the shard key prefix |
| Vitess | MySQL indexes per shard | Lookup vindexes (consistent_lookup_unique for global uniqueness without 2PC) |
| Citus | Indexes on each shard | None; unique constraints must include the distribution column |
| Elasticsearch | Index per shard | A separate global search index fed by CDC |
How to use it: for "find by X then load", use a global index or lookup table; for strict global uniqueness use a unique lookup keyed by the value (written in the same transaction where the product supports it, or with a reservation step and cleanup); accept the staleness of GSIs in the UI ("your change may take a moment to appear").
Cross-shard transactions: 2PC, sagas and avoiding them by design Must-know
In plain words: one database can commit two rows atomically; two databases cannot without a coordinator. Either keep things that must change together on one shard, or accept a multi-step process that can undo itself.
Common misunderstanding: "Our ORM's transaction() still protects us." It opens a transaction on one connection. Writes to a second shard inside the closure are a second, independent transaction; Figma calls the result "partial commit failures" and gives the example "imagine moving a team between two organizations, only to find half their data was missing!".
Definition: a cross-shard transaction touches rows on more than one shard. Options: avoid by design (aggregate per shard, co-location); two-phase commit (prepare on every participant, then commit; PostgreSQL PREPARE TRANSACTION, MySQL XA, Vitess atomic distributed transactions, Citus, Spanner and CockroachDB do it internally; details in Distributed SQL, Consensus & 2PC); saga (a sequence of local transactions with compensations, see Saga Pattern); and idempotent, retried steps with an outbox (Transactional Outbox).
Transfer 100 credits from tenant 3 (shard 0) to tenant 9 (shard 2), saga
1 shard 0: BEGIN; UPDATE credits SET balance = balance - 100 WHERE tenant_id = 3; INSERT outbox(TransferDebited); COMMIT
2 relay publishes TransferDebited(transfer_id = t-1)
3 shard 2: BEGIN; INSERT applied(t-1) ON CONFLICT DO NOTHING; UPDATE credits ... + 100; COMMIT
4 if step 3 fails permanently: shard 0 runs the compensation (+100, TransferReversed)
5 between 1 and 3 the money is "in flight": visible as a pending transfer, not lostReal scenario: moving a team between organisations (Figma's example); transferring credits between tenants on different shards; renaming a username that is indexed in a global lookup; an order whose customer and inventory live on different shards.
| Approach | Atomicity | Cost | Products |
|---|---|---|---|
| Co-locate (aggregate per shard) | Full ACID, one shard | Constrains the key choice | Citus co-location, Figma colos, Vitess same keyspace ID |
| 2PC by the database | Atomic across shards | Coordinator latency, locks held during prepare, in-doubt transactions | Citus, Spanner, CockroachDB, Vitess atomic distributed transactions, MySQL XA |
| 2PC by the application | Atomic if you build a transaction manager | PostgreSQL: "you probably shouldn't be using PREPARE TRANSACTION" unless writing one | PostgreSQL max_prepared_transactions (0 by default in the recommended setting) |
| Saga with compensation | Eventually consistent, semantically atomic | Intermediate states visible; compensation logic | Any database plus a broker |
| Design the operation away | Not needed | Product change | Pinterest: "updates will generally be best effort" |
How to use it: choose the partition key so that every frequent transaction is single-shard (this is the most important use of the key); make the rare cross-shard operation a saga with idempotent steps and a visible pending state; use 2PC only through a product that implements recovery of in-doubt transactions.
-- PostgreSQL participant side of 2PC (what a transaction manager does on each shard).
BEGIN;
UPDATE credits SET balance = balance - 100 WHERE tenant_id = 3;
PREPARE TRANSACTION 'transfer-t-1'; -- fails with "prepared transactions are disabled" if max_prepared_transactions = 0
-- after every participant prepared:
COMMIT PREPARED 'transfer-t-1'; -- or ROLLBACK PREPARED 'transfer-t-1'
SELECT gid, prepared FROM pg_prepared_xacts; -- in-doubt transactions hold locks and block VACUUMGlobally unique ids across shards Important
In plain words: each shard's auto-increment starts at 1, so two shards will both create order 42; use ids generated so they cannot collide, ideally carrying the shard.
Common misunderstanding: "UUIDs solve it, done." Random UUIDv4 values are unique but 128 bits, unordered and bad for B-tree locality; time-ordered ids (Snowflake, UUIDv7, ULID) sort by creation time; ids that embed the logical shard let any service route by id alone.
Definition: a global unique id scheme generates ids without cross-shard coordination. Twitter's Snowflake: "time - 41 bits (millisecond precision w/ a custom epoch gives us 69 years)", a machine id and a "sequence number - 12 bits". Instagram's in-database variant: "41 bits for time in milliseconds", "13 bits that represent the logical shard ID", "10 bits that represent an auto-incrementing sequence, modulus 1024". Pinterest: shard 16 bits, type 10 bits, local id 36 bits. The full menu is in ID Generation at Scale.
Real scenario: Figma lists "Globally unique ID generation for horizontally sharded primary keys" as remaining work; Instagram's next_id() function per schema; a Snowflake id service shared by all shards; Vitess sequences in an unsharded keyspace.
| Scheme | Size | Sortable | Carries the shard | Coordination |
|---|---|---|---|---|
| Auto-increment per shard | 64 | Per shard | No | None, but collides across shards |
Auto-increment with offsets (auto_increment_increment) | 64 | Roughly | Implicitly | Configuration per shard |
| UUIDv4 | 128 | No | No | None |
| UUIDv7 / ULID | 128 | Yes (ms) | No | None |
| Snowflake | 64 | Yes (ms) | Machine, not shard | Worker id assignment |
| Instagram / Pinterest style | 64 | Yes / per shard | Yes | Shard id is the worker id |
| Vitess sequence | 64 | Yes | No | Central sequence table, cached blocks |
How to use it: pick a scheme before sharding (Notion regretted the separate id plus space_id); prefer time-ordered 64-bit ids that embed a logical shard when ids are used for routing; never reuse the shard bits for a physical host number, because logical shards move.
Schema changes across shards Good to know
In plain words: a migration now runs N times, on N databases that may be at different points, so it must be safe to have half the shards changed and half not.
Common misunderstanding: "Run the migration in a loop." If shard 37 fails halfway, the fleet has two schemas; the application must work with both, and the loop must be resumable.
Definition: fleet-wide schema change applies expand/contract migrations (Zero-Downtime Schema Migrations) to every shard with tracking per shard. Figma: "Schema changes must be coordinated across all shards to ensure the databases stay in sync." Vitess ApplySchema and online DDL apply to all shards of a keyspace; Citus propagates DDL from the coordinator to every shard; MongoDB has no schema, so the problem moves to the application (Pinterest's JSON blob approach: "we've probably performed one ALTER in the last three years").
Real scenario: adding customer_email to orders on 96 shards; adding the partition key column to every table before sharding (Notion's missing workspace ID); a new unique index that must include the shard key.
How to use it: expand first (nullable columns, new tables), deploy code that handles both shapes, contract last; record the applied version per shard; run with limited concurrency and stop on the first failure.
Multi-tenancy and shard per tenant Important
In plain words: in a SaaS, tenants are the natural shard key; small tenants share shards, big ones may get their own.
Common misunderstanding: "Database per tenant is the scalable option." It isolates well but thousands of databases multiply migrations, connections and backups; most fleets share shards among many tenants and isolate only whales.
Definition: the tenancy models (shared table with tenant_id, schema per tenant, database per tenant) are in Multi-Tenancy Strategies. At system level, the choice is how tenants map to shards: hash of tenant id (even spread, no control), directory (place each tenant, move it later), or shard per tenant for the largest. Citus supports all three: tenant id as distribution column, isolate_tenant_to_new_shard, and moving that shard to its own node.
Real scenario: Notion's workspace-partitioned shards where one enterprise customer outweighs many personal workspaces; Citus isolate_tenant_to_new_shard('lineitem', 135, 'CASCADE'); a regulated customer contractually on dedicated hardware in one region.
| Model | Placement | Whale handling | Cost |
|---|---|---|---|
| Shared shards, hashed tenant | hash(tenant_id) | Salting or isolation later | Lowest |
| Shared shards plus directory | Directory, hash fallback | Pin whale to its own shard | One directory |
| Shard per tenant | Directory only | Natural | Per-tenant migrations, connections, backups |
| Cell / deployment per tenant group | Routing at the edge | Natural | Whole stacks per cell |
How to use it: shard by tenant id with a directory override; watch per-tenant load (Citus citus_stat_tenants, your own metrics); isolate a tenant when it exceeds a stated share of a shard (for example 30%); never let one tenant's query plan scatter over other tenants' shards.
Mechanics
Knobs and limits, per product
| Product | Knob or limit | Value / default | What it controls |
|---|---|---|---|
| DynamoDB | Per-partition throughput | 3,000 RCU, 1,000 WCU | Hot key ceiling, even after adaptive capacity |
| DynamoDB | Burst capacity | Up to 300 s of unused capacity | Short spikes |
| DynamoDB | LSI item collection | 10 GB per partition key value | ItemCollectionSizeLimitExceededException |
| MongoDB | chunkSize (range size) | 128 MB | Split and migration granularity |
| MongoDB | Migration threshold | Difference of 3 x range size (384 MB default) | When the balancer starts |
| MongoDB | Balancing window | sh.updateBalancerConfig / config settings | When migrations may run |
| MongoDB | reshardCollection | Blocks writes up to two seconds at the end; needs about 1.2 TB per shard in the docs' 2 TB example | Changing the shard key online |
| Citus | citus.shard_count | 32 | Shards per new distributed table |
| Citus | citus.max_background_task_executors_per_node | 1 | Parallel shard moves |
| Redis Cluster | Hash slots | 16384, CRC16 | Partition count, fixed |
| Redis Cluster | Suggested cluster size | "on the order of ~ 1000 nodes" | Gossip overhead |
| Cassandra | Cells per partition | 2 billion hard limit | Wide partition ceiling |
| Cassandra | num_tokens | 16 in the current cassandra.yaml (older releases shipped 256) | Vnodes per node |
| Vitess | Shard names | Hex key ranges such as -80, 80-c0, c0- | Placement by keyspace ID |
| PostgreSQL | max_prepared_transactions | 0 (disabled) unless set | Whether 2PC participants can prepare |
What goes wrong, verbatim
| Product | Message | Meaning | What to do |
|---|---|---|---|
| Redis Cluster | -MOVED 3999 127.0.0.1:6381 | Slot 3999 is owned by another node permanently | Update the slot map, retry there |
| Redis Cluster | -ASK 3999 127.0.0.1:6381 | Slot is migrating; this key is already on the target | Send ASKING then the command to the target, do not update the map |
| Redis Cluster | -CROSSSLOT Keys in request don't hash to the same slot | Multi-key command across slots | Use a {hash tag} or split the command |
| DynamoDB | ProvisionedThroughputExceededException / ThrottlingException | Partition or table throughput exceeded | Back off with jitter; salt the hot key |
| DynamoDB | ItemCollectionSizeLimitExceededException | 10 GB item collection limit with an LSI | Change the key, drop the LSI, archive |
| MongoDB | Chunk flagged jumbo | A range larger than the chunk size that cannot be split (often one shard key value) | Refine the shard key; forceJumbo to move it |
| PostgreSQL | ERROR: prepared transactions are disabled | PREPARE TRANSACTION with max_prepared_transactions = 0 | Do not use 2PC by hand; use a product or a saga |
The cost of a move, measured
The Go program cmd/movecost (in the Lab) placed 200,000 keys on 4 shards, then on 5, and counted the keys that changed shard:
| Strategy (4 -> 5 shards) | Keys moved | Max/min load at 5 shards |
|---|---|---|
hash mod N | 80.1% | 1.01 |
| Ring, 1 vnode per shard | 37.7% | 61.89 |
| Ring, 16 vnodes per shard | 22.4% | 1.79 |
| Ring, 256 vnodes per shard | 17.8% | 1.27 |
| 1024 fixed partitions + planner | 19.9% | 1.00 |
The ideal for adding one shard to four is 20%. mod N moves four times that; one point per shard on a ring moves less data but leaves one shard with sixty times the keys of another; vnodes and fixed partitions get close to the ideal, and only the planner gives an exact and auditable list of moves.
Go
Before
The shard number is fnv32(user_id) % N, computed inline, and the connection string is derived from it. Correct on day one; on the day N changes it moves 80% of the keys, and every query without the key is written by hand.
// Before: the shard is hash(key) % N, computed inline wherever a query is
// built. It works on day one. On the day N changes, almost every key moves,
// nothing records where a key used to live, and cross-shard reads are
// written by hand in every handler.
package main
import (
"fmt"
"hash/fnv"
)
// shardFor is copied into every service that talks to the database.
func shardFor(userID string, shards int) int {
h := fnv.New32a()
h.Write([]byte(userID))
return int(h.Sum32()) % shards
}
func dsn(shard int) string {
// Connection strings are derived from the shard number, so the number of
// shards is baked into configuration, code and data placement at once.
return fmt.Sprintf("postgres://app@db-%d.internal:5432/app", shard)
}
func main() {
moved := 0
const keys = 100_000
for i := 0; i < keys; i++ {
id := fmt.Sprintf("user-%d", i)
if shardFor(id, 4) != shardFor(id, 5) {
moved++
}
}
// Going from 4 to 5 shards moves about 80% of keys: (N-1)/N of the data
// must be copied while the system is live.
fmt.Printf("4 -> 5 shards: %d of %d keys change shard (%.1f%%)\n",
moved, keys, 100*float64(moved)/keys)
fmt.Println("user-42 lives on", dsn(shardFor("user-42", 4)))
// "Show the newest 20 orders for support" now means: open N connections,
// run the query N times, merge by hand, and hope no shard is slow.
}After
Four small packages with tests, standard library only. router holds the stable hash and four strategies behind one interface (range with range-query targeting, fixed partitions with a CRC-32 contract shared with PHP, a ring with virtual nodes, and a directory with a write freeze for cutovers), plus compound keys:
// Package router maps a partition key to a shard with one of four
// strategies (range, fixed hash partitions, consistent-hash ring with
// virtual nodes, and a directory with a fallback), and fans a query out
// to many shards with bounded concurrency and a per-shard deadline.
package router
import "hash/fnv"
// ShardID names a physical shard (a database, a Vitess shard, a Citus worker).
type ShardID string
// Hash64 is a stable 64-bit hash: FNV-1a followed by the SplitMix64
// finalizer, so that similar keys ("user-1", "user-2") land far apart.
// It must never change once data is placed with it.
func Hash64(key string) uint64 {
h := fnv.New64a()
h.Write([]byte(key))
return mix64(h.Sum64())
}
func mix64(z uint64) uint64 {
z ^= z >> 30
z *= 0xbf58476d1ce4e5b9
z ^= z >> 27
z *= 0x94d049bb133111eb
z ^= z >> 31
return z
}package router
import (
"errors"
"fmt"
"hash/crc32"
"slices"
"sort"
"strings"
"sync"
)
// Strategy is the only thing application code calls: key in, shard out.
type Strategy interface {
Name() string
Shard(key string) (ShardID, error)
}
// ErrNoShard is returned when a strategy has no shard for a key.
var ErrNoShard = errors.New("router: no shard for key")
// ---------------------------------------------------------------- range
// Range is one contiguous key range [Lower, next Lower) owned by a shard.
type Range struct {
Lower string
Shard ShardID
}
// RangeStrategy keeps sorted ranges, like MongoDB ranged chunks or an
// HBase/Bigtable region map. Range scans touch few shards; sequential keys
// all land on the last range (the write hotspot).
type RangeStrategy struct{ ranges []Range }
// NewRange validates that ranges start at "" and are strictly increasing.
func NewRange(ranges []Range) (*RangeStrategy, error) {
if len(ranges) == 0 || ranges[0].Lower != "" {
return nil, errors.New("router: first range must start at the empty key")
}
for i := 1; i < len(ranges); i++ {
if ranges[i].Lower <= ranges[i-1].Lower {
return nil, fmt.Errorf("router: range %d is not after range %d", i, i-1)
}
}
return &RangeStrategy{ranges: slices.Clone(ranges)}, nil
}
func (r *RangeStrategy) Name() string { return "range" }
func (r *RangeStrategy) index(key string) int {
// Last range whose Lower <= key.
return sort.Search(len(r.ranges), func(i int) bool { return r.ranges[i].Lower > key }) - 1
}
func (r *RangeStrategy) Shard(key string) (ShardID, error) {
return r.ranges[r.index(key)].Shard, nil
}
// ShardsFor returns the shards a range query [from, to) must visit, in order.
// This is the property hash partitioning gives up.
func (r *RangeStrategy) ShardsFor(from, to string) []ShardID {
var out []ShardID
for i := r.index(from); i < len(r.ranges); i++ {
if i > r.index(from) && r.ranges[i].Lower >= to {
break
}
if !slices.Contains(out, r.ranges[i].Shard) {
out = append(out, r.ranges[i].Shard)
}
}
return out
}
// ----------------------------------------------------- fixed partitions
// FixedPartitions hashes a key into one of P logical partitions (P is fixed
// for the life of the data, e.g. 1024) and maps partitions to shards with
// an assignment table. Rebalancing moves whole partitions and edits the
// table; the key-to-partition function never changes. Redis Cluster
// (16384 slots), Couchbase vBuckets and Vitess keyspace ranges are this idea.
type FixedPartitions struct {
assign []ShardID // index = partition
}
// NewFixedPartitions assigns P partitions round-robin over shards.
func NewFixedPartitions(partitions int, shards []ShardID) (*FixedPartitions, error) {
if partitions <= 0 || len(shards) == 0 || partitions < len(shards) {
return nil, errors.New("router: need partitions >= shards > 0")
}
a := make([]ShardID, partitions)
for p := range a {
a[p] = shards[p%len(shards)]
}
return &FixedPartitions{assign: a}, nil
}
// FromAssignment builds a strategy from a stored partition table.
func FromAssignment(assign []ShardID) *FixedPartitions {
return &FixedPartitions{assign: slices.Clone(assign)}
}
func (f *FixedPartitions) Name() string { return "fixed-partitions" }
// Partition is stable for a given P: it does not depend on the shard count.
func (f *FixedPartitions) Partition(key string) int { return PartitionOf(key, len(f.assign)) }
// PartitionOf is CRC-32 (IEEE) of the key modulo P. It is the routing
// contract shared by every language that routes: PHP's crc32() returns the
// same value, so the Go service and the Laravel app agree on placement.
func PartitionOf(key string, partitions int) int {
return int(crc32.ChecksumIEEE([]byte(key)) % uint32(partitions))
}
func (f *FixedPartitions) Shard(key string) (ShardID, error) {
return f.assign[f.Partition(key)], nil
}
// Assignment returns a copy of the partition table.
func (f *FixedPartitions) Assignment() []ShardID { return slices.Clone(f.assign) }
// ------------------------------------------------- consistent-hash ring
// Ring is a consistent-hash ring with virtual nodes (Karger et al. 1997;
// Dynamo; Cassandra vnodes). Adding a shard takes about 1/(N+1) of the keys,
// all from existing shards. See /database/consistent-hashing for internals.
type Ring struct {
points []uint64
owners []ShardID
}
// NewRing places vnodes points per shard on a 64-bit ring.
func NewRing(shards []ShardID, vnodes int) (*Ring, error) {
if len(shards) == 0 || vnodes <= 0 {
return nil, errors.New("router: need shards and vnodes > 0")
}
type pt struct {
h uint64
s ShardID
}
pts := make([]pt, 0, len(shards)*vnodes)
for _, s := range shards {
for i := 0; i < vnodes; i++ {
pts = append(pts, pt{Hash64(fmt.Sprintf("%s#%d", s, i)), s})
}
}
sort.Slice(pts, func(i, j int) bool { return pts[i].h < pts[j].h })
r := &Ring{points: make([]uint64, len(pts)), owners: make([]ShardID, len(pts))}
for i, p := range pts {
r.points[i], r.owners[i] = p.h, p.s
}
return r, nil
}
func (r *Ring) Name() string { return "ring" }
// Shard walks clockwise to the first point at or after the key's hash.
func (r *Ring) Shard(key string) (ShardID, error) {
h := Hash64(key)
i := sort.Search(len(r.points), func(i int) bool { return r.points[i] >= h })
if i == len(r.points) {
i = 0
}
return r.owners[i], nil
}
// ------------------------------------------------------------ directory
// State of a directory entry. Moving entries reject writes during cutover.
type State int
const (
Active State = iota
Moving
)
// ErrMoving tells the caller to retry shortly: the key's data is being
// cut over to a new shard and writes are briefly frozen.
var ErrMoving = errors.New("router: key is moving, retry")
// Entry is one row of the lookup table.
type Entry struct {
Shard ShardID
State State
}
// Directory is a lookup service: explicit placements (a big tenant on its
// own shard) override a fallback strategy. Every change bumps Version so
// caches of the table can detect staleness.
type Directory struct {
mu sync.RWMutex
entries map[string]Entry
fallback Strategy
version uint64
}
// NewDirectory returns a directory that falls back to s for unknown keys.
func NewDirectory(fallback Strategy) *Directory {
return &Directory{entries: map[string]Entry{}, fallback: fallback}
}
func (d *Directory) Name() string { return "directory+" + d.fallback.Name() }
// Shard is for reads: a Moving key is still served by its old shard.
func (d *Directory) Shard(key string) (ShardID, error) {
d.mu.RLock()
e, ok := d.entries[key]
d.mu.RUnlock()
if ok {
return e.Shard, nil
}
return d.fallback.Shard(key)
}
// ShardForWrite refuses writes while a key is being cut over.
func (d *Directory) ShardForWrite(key string) (ShardID, error) {
d.mu.RLock()
e, ok := d.entries[key]
d.mu.RUnlock()
if ok && e.State == Moving {
return "", ErrMoving
}
return d.Shard(key)
}
// Place pins a key to a shard (state Active).
func (d *Directory) Place(key string, s ShardID) { d.set(key, Entry{Shard: s, State: Active}) }
// BeginMove freezes writes for key; reads still go to the current shard.
func (d *Directory) BeginMove(key string) error {
cur, err := d.Shard(key)
if err != nil {
return err
}
d.set(key, Entry{Shard: cur, State: Moving})
return nil
}
// CompleteMove flips the key to its new shard and unfreezes writes.
func (d *Directory) CompleteMove(key string, to ShardID) { d.Place(key, to) }
func (d *Directory) set(key string, e Entry) {
d.mu.Lock()
d.entries[key] = e
d.version++
d.mu.Unlock()
}
// Version increases on every change to the table.
func (d *Directory) Version() uint64 {
d.mu.RLock()
defer d.mu.RUnlock()
return d.version
}
// ------------------------------------------------------------ composite
// RoutingKey builds the partition key from the leading parts of a compound
// key: RoutingKey("tenant-7", "order-9") routes on "tenant-7" only, so all
// of a tenant's rows are co-located and the full key stays unique.
func RoutingKey(parts ...string) string {
if len(parts) == 0 {
return ""
}
return parts[0]
}
// CompoundKey joins parts for storage; the first part is the routing key.
func CompoundKey(parts ...string) string { return strings.Join(parts, "#") }Scatter-gather with bounded concurrency and a per-shard deadline, and the k-way merge for ORDER BY ... LIMIT:
package router
import (
"context"
"time"
)
// Result is one shard's answer to a scatter-gather query.
type Result[T any] struct {
Shard ShardID
Value T
Err error
}
// ScatterGather runs fn on every shard with at most limit calls in flight
// and a per-shard deadline. Results come back in the order of shards. A
// slow shard costs its deadline, not the whole request: the caller decides
// whether partial results are acceptable (search) or not (a report).
func ScatterGather[T any](ctx context.Context, shards []ShardID, limit int,
perShard time.Duration, fn func(context.Context, ShardID) (T, error)) []Result[T] {
if limit <= 0 {
limit = len(shards)
}
out := make([]Result[T], len(shards))
sem := make(chan struct{}, limit)
done := make(chan struct{}, len(shards))
for i, s := range shards {
go func() {
defer func() { done <- struct{}{} }()
select {
case sem <- struct{}{}:
case <-ctx.Done():
out[i] = Result[T]{Shard: s, Err: ctx.Err()}
return
}
defer func() { <-sem }()
sctx, cancel := context.WithTimeout(ctx, perShard)
defer cancel()
v, err := fn(sctx, s)
out[i] = Result[T]{Shard: s, Value: v, Err: err}
}()
}
for range shards {
<-done
}
return out
}
// MergeSorted merges per-shard lists that are each already sorted by less
// and returns the global first limit items. For ORDER BY ... LIMIT n every
// shard must return its own first n, not n divided by the shard count.
func MergeSorted[T any](lists [][]T, less func(a, b T) bool, limit int) []T {
idx := make([]int, len(lists))
var out []T
for len(out) < limit {
best := -1
for i, l := range lists {
if idx[i] < len(l) && (best < 0 || less(l[idx[i]], lists[best][idx[best]])) {
best = i
}
}
if best < 0 {
break
}
out = append(out, lists[best][idx[best]])
idx[best]++
}
return out
}package router
import (
"context"
"errors"
"fmt"
"math"
"slices"
"testing"
"time"
)
func shards(n int) []ShardID {
out := make([]ShardID, n)
for i := range out {
out[i] = ShardID(fmt.Sprintf("s%d", i))
}
return out
}
func TestRangeRoutingAndRangeQueries(t *testing.T) {
r, err := NewRange([]Range{{"", "s0"}, {"g", "s1"}, {"n", "s2"}, {"t", "s3"}})
if err != nil {
t.Fatal(err)
}
cases := map[string]ShardID{"apple": "s0", "g": "s1", "melon": "s1", "nut": "s2", "zebra": "s3"}
for k, want := range cases {
if got, _ := r.Shard(k); got != want {
t.Errorf("Shard(%q) = %s, want %s", k, got, want)
}
}
if got := r.ShardsFor("h", "p"); !slices.Equal(got, []ShardID{"s1", "s2"}) {
t.Errorf("ShardsFor(h,p) = %v, want [s1 s2]", got)
}
if _, err := NewRange([]Range{{"a", "s0"}}); err == nil {
t.Error("ranges not starting at the empty key must be rejected")
}
}
func TestPartitionOfMatchesPHPcrc32(t *testing.T) {
// php -r 'echo crc32("tenant-42") % 1024;' prints 716.
if got := PartitionOf("tenant-42", 1024); got != 716 {
t.Fatalf("PartitionOf = %d, want 716 (PHP crc32 contract)", got)
}
}
func TestFixedPartitionsKeepKeyToPartition(t *testing.T) {
f4, _ := NewFixedPartitions(1024, shards(4))
f5 := FromAssignment(f4.Assignment())
for i := 0; i < 1000; i++ {
k := fmt.Sprintf("k%d", i)
if f4.Partition(k) != f5.Partition(k) {
t.Fatal("key-to-partition must not depend on the assignment")
}
}
if _, err := NewFixedPartitions(2, shards(4)); err == nil {
t.Error("fewer partitions than shards must be rejected")
}
}
func TestRingMovesAboutOneOverNPlusOne(t *testing.T) {
r4, _ := NewRing(shards(4), 256)
r5, _ := NewRing(shards(5), 256)
const n = 50_000
moved := 0
for i := 0; i < n; i++ {
k := fmt.Sprintf("user-%d", i)
a, _ := r4.Shard(k)
b, _ := r5.Shard(k)
if a != b {
moved++
if b != "s4" {
t.Fatalf("key %s moved between old shards %s -> %s", k, a, b)
}
}
}
frac := float64(moved) / n
if math.Abs(frac-0.2) > 0.05 {
t.Errorf("moved %.3f of keys, want about 0.20", frac)
}
}
func TestRingVnodesBalanceLoad(t *testing.T) {
spread := func(vnodes int) float64 {
r, _ := NewRing(shards(8), vnodes)
count := map[ShardID]int{}
for i := 0; i < 80_000; i++ {
s, _ := r.Shard(fmt.Sprintf("k%d", i))
count[s]++
}
lo, hi := math.MaxInt, 0
for _, c := range count {
lo, hi = min(lo, c), max(hi, c)
}
return float64(hi) / float64(lo)
}
if one, many := spread(1), spread(256); many >= one || many > 1.4 {
t.Errorf("max/min load: 1 vnode %.2f, 256 vnodes %.2f; want 256 vnodes well balanced", one, many)
}
}
func TestDirectoryOverridesAndCutover(t *testing.T) {
fp, _ := NewFixedPartitions(64, shards(2))
d := NewDirectory(fp)
d.Place("tenant-big", "dedicated-1")
if s, _ := d.Shard("tenant-big"); s != "dedicated-1" {
t.Fatalf("directory entry ignored: %s", s)
}
want, _ := fp.Shard("tenant-small")
if s, _ := d.Shard("tenant-small"); s != want {
t.Fatalf("fallback not used: %s", s)
}
v := d.Version()
if err := d.BeginMove("tenant-small"); err != nil {
t.Fatal(err)
}
if _, err := d.ShardForWrite("tenant-small"); !errors.Is(err, ErrMoving) {
t.Fatalf("writes must be frozen during cutover, got %v", err)
}
if s, _ := d.Shard("tenant-small"); s != want {
t.Fatalf("reads must stay on the old shard during cutover, got %s", s)
}
d.CompleteMove("tenant-small", "s9")
if s, err := d.ShardForWrite("tenant-small"); err != nil || s != "s9" {
t.Fatalf("after cutover: %s %v", s, err)
}
if d.Version() <= v {
t.Fatal("version must increase on every change")
}
}
func TestCompoundKeyRoutesOnTenant(t *testing.T) {
if RoutingKey("tenant-7", "order-9") != "tenant-7" || CompoundKey("tenant-7", "order-9") != "tenant-7#order-9" {
t.Fatal("compound key helpers")
}
}
func TestScatterGatherDeadlinesAndOrder(t *testing.T) {
ss := shards(5)
res := ScatterGather(context.Background(), ss, 2, 50*time.Millisecond,
func(ctx context.Context, s ShardID) (int, error) {
if s == "s3" { // one slow shard
select {
case <-time.After(time.Second):
return 0, nil
case <-ctx.Done():
return 0, ctx.Err()
}
}
return len(s), nil
})
for i, r := range res {
if r.Shard != ss[i] {
t.Fatalf("results out of order: %v", res)
}
}
if !errors.Is(res[3].Err, context.DeadlineExceeded) {
t.Fatalf("slow shard should hit its deadline, got %v", res[3].Err)
}
if res[0].Err != nil || res[0].Value != 2 {
t.Fatalf("fast shard: %+v", res[0])
}
}
func TestMergeSortedGlobalLimit(t *testing.T) {
// Newest first; each shard returned its own top 3.
lists := [][]int{{90, 50, 10}, {99, 98, 97}, {60, 40, 20}}
got := MergeSorted(lists, func(a, b int) bool { return a > b }, 4)
if !slices.Equal(got, []int{99, 98, 97, 90}) {
t.Fatalf("got %v", got)
}
}A hot-key detector (Space-Saving, bounded memory) and the salt sizing used in the Salting block:
// Package hotkey finds the keys that take a disproportionate share of
// traffic (Space-Saving top-k with bounded memory) and sizes the salt
// that spreads one hot key over several partitions.
package hotkey
import (
"fmt"
"math"
"sort"
"sync"
)
// Item is a key with its estimated count. Count overestimates by at most
// Err, so Count-Err is a guaranteed lower bound.
type Item struct {
Key string
Count uint64
Err uint64
}
// Detector implements the Space-Saving algorithm (Metwally et al. 2005):
// it tracks at most capacity keys; a new key replaces the current minimum
// and inherits its count as error. Heavy keys are never evicted.
type Detector struct {
mu sync.Mutex
capacity int
items map[string]*Item
total uint64
}
// New returns a detector that keeps at most capacity counters.
func New(capacity int) *Detector {
if capacity < 1 {
capacity = 1
}
return &Detector{capacity: capacity, items: make(map[string]*Item, capacity)}
}
// Observe records one request for key. O(capacity) on eviction, which is
// fine for capacities in the hundreds; use a stream-summary list beyond.
func (d *Detector) Observe(key string) {
d.mu.Lock()
defer d.mu.Unlock()
d.total++
if it, ok := d.items[key]; ok {
it.Count++
return
}
if len(d.items) < d.capacity {
d.items[key] = &Item{Key: key, Count: 1}
return
}
var minIt *Item
for _, it := range d.items {
if minIt == nil || it.Count < minIt.Count {
minIt = it
}
}
delete(d.items, minIt.Key)
d.items[key] = &Item{Key: key, Count: minIt.Count + 1, Err: minIt.Count}
}
// Top returns up to n items, highest count first.
func (d *Detector) Top(n int) []Item {
d.mu.Lock()
defer d.mu.Unlock()
out := make([]Item, 0, len(d.items))
for _, it := range d.items {
out = append(out, *it)
}
sort.Slice(out, func(i, j int) bool {
if out[i].Count != out[j].Count {
return out[i].Count > out[j].Count
}
return out[i].Key < out[j].Key
})
if len(out) > n {
out = out[:n]
}
return out
}
// Hot returns keys whose guaranteed share of traffic is at least share
// (0.05 = 5%). Using the lower bound avoids false alarms.
func (d *Detector) Hot(share float64) []Item {
var out []Item
total := d.Total()
for _, it := range d.Top(d.capacity) {
if total > 0 && float64(it.Count-it.Err)/float64(total) >= share {
out = append(out, it)
}
}
return out
}
// Total is the number of observations since the last Reset.
func (d *Detector) Total() uint64 {
d.mu.Lock()
defer d.mu.Unlock()
return d.total
}
// Reset starts a new window (call it every N seconds from a ticker).
func (d *Detector) Reset() {
d.mu.Lock()
defer d.mu.Unlock()
d.items = make(map[string]*Item, d.capacity)
d.total = 0
}
// SaltFactor is how many sub-keys a hot key needs so that each stays under
// targetUtil of the per-partition limit, rounded up to a power of two.
// Example: 4,000 writes/s on DynamoDB (1,000 WCU per partition) at 0.7
// utilisation needs ceil(4000/700) = 6, rounded to 8.
func SaltFactor(rate, perPartitionLimit, targetUtil float64) int {
if rate <= 0 || perPartitionLimit <= 0 || targetUtil <= 0 {
return 1
}
n := int(math.Ceil(rate / (perPartitionLimit * targetUtil)))
p := 1
for p < n {
p <<= 1
}
return p
}
// Salted returns the sub-key for one write: key#0 .. key#(n-1). Pick i
// randomly for write spreading, or from a hash of another attribute (order
// id) so that a point read can recompute it.
func Salted(key string, i, n int) string {
if n <= 1 {
return key
}
return fmt.Sprintf("%s#%d", key, i%n)
}
// AllSalts lists every sub-key a read must query and merge.
func AllSalts(key string, n int) []string {
if n <= 1 {
return []string{key}
}
out := make([]string, n)
for i := range out {
out[i] = Salted(key, i, n)
}
return out
}package hotkey
import (
"fmt"
"math/rand/v2"
"testing"
)
func TestDetectorFindsCelebrity(t *testing.T) {
d := New(50)
r := rand.New(rand.NewPCG(1, 2))
for i := 0; i < 100_000; i++ {
switch {
case i%5 == 0: // 20% of traffic to one celebrity account
d.Observe("user-celebrity")
case i%50 == 1: // 2% to a popular one
d.Observe("user-popular")
default: // long tail of 100k users
d.Observe(fmt.Sprintf("user-%d", r.IntN(100_000)))
}
}
hot := d.Hot(0.05)
if len(hot) != 1 || hot[0].Key != "user-celebrity" {
t.Fatalf("Hot(5%%) = %+v, want only the celebrity", hot)
}
top := d.Top(2)
if top[0].Key != "user-celebrity" || top[1].Key != "user-popular" {
t.Fatalf("Top(2) = %+v", top)
}
d.Reset()
if d.Total() != 0 || len(d.Top(10)) != 0 {
t.Fatal("Reset must clear the window")
}
}
func TestSaltFactor(t *testing.T) {
cases := []struct {
rate, limit, util float64
want int
}{
{4000, 1000, 0.7, 8},
{500, 1000, 0.7, 1},
{20000, 1000, 0.5, 64},
}
for _, c := range cases {
if got := SaltFactor(c.rate, c.limit, c.util); got != c.want {
t.Errorf("SaltFactor(%v,%v,%v) = %d, want %d", c.rate, c.limit, c.util, got, c.want)
}
}
}
func TestSaltsRoundTrip(t *testing.T) {
all := AllSalts("2026-11-26", 4)
if len(all) != 4 || all[3] != "2026-11-26#3" {
t.Fatalf("AllSalts = %v", all)
}
if Salted("k", 9, 4) != "k#1" || Salted("k", 3, 1) != "k" {
t.Fatal("Salted")
}
}The online rebalancing plan generator: minimal moves to a new shard set, waves that respect a per-shard migration limit, and the seven-phase runbook per move (the tests include Notion's 480 logical shards going from 32 to 96 hosts):
// Package rebalance turns "the cluster now has these shards" into the
// smallest set of partition moves, schedules them in waves that respect a
// per-shard concurrency limit, and spells out the online move runbook for
// each one (backfill, catch-up, verify, freeze, cutover, cleanup).
package rebalance
import (
"errors"
"fmt"
"slices"
"sort"
"academy/sharding-consistent-hashing-system/router"
)
// Move relocates one fixed partition between shards.
type Move struct {
Partition int
From, To router.ShardID
}
// Plan is the result of Compute.
type Plan struct {
Moves []Move
Before map[router.ShardID]int
After map[router.ShardID]int
Assignment []router.ShardID // the partition table after all moves
}
// Compute returns the minimum number of moves that leaves every target
// shard with floor(P/S) or ceil(P/S) partitions. Partitions on shards not
// in target (decommissioned) always move. Shards that already hold the
// most partitions keep the extra one, which is what makes the plan minimal.
func Compute(assign []router.ShardID, target []router.ShardID) (Plan, error) {
if len(target) == 0 || len(assign) < len(target) {
return Plan{}, errors.New("rebalance: need partitions >= target shards > 0")
}
tgt := slices.Clone(target)
slices.Sort(tgt)
if len(slices.Compact(slices.Clone(tgt))) != len(tgt) {
return Plan{}, errors.New("rebalance: duplicate target shard")
}
isTarget := map[router.ShardID]bool{}
for _, s := range tgt {
isTarget[s] = true
}
before := map[router.ShardID]int{}
owned := map[router.ShardID][]int{}
for p, s := range assign {
before[s]++
owned[s] = append(owned[s], p)
}
// Quotas: base for everyone, +1 for the r shards that currently hold most.
base, r := len(assign)/len(tgt), len(assign)%len(tgt)
byLoad := slices.Clone(tgt)
sort.SliceStable(byLoad, func(i, j int) bool { return before[byLoad[i]] > before[byLoad[j]] })
quota := map[router.ShardID]int{}
for i, s := range byLoad {
quota[s] = base
if i < r {
quota[s]++
}
}
// Collect partitions that must leave: all of a removed shard, the excess
// of an overloaded one (highest partition numbers first, deterministic).
var pool []Move
var sources []router.ShardID
for s := range owned {
sources = append(sources, s)
}
slices.Sort(sources)
for _, s := range sources {
ps := owned[s]
keep := 0
if isTarget[s] {
keep = min(quota[s], len(ps))
}
for _, p := range ps[keep:] {
pool = append(pool, Move{Partition: p, From: s})
}
}
// Fill shards below quota, in name order.
after := map[router.ShardID]int{}
for _, s := range tgt {
after[s] = min(before[s], quota[s])
}
next := slices.Clone(assign)
i := 0
for _, s := range tgt {
for after[s] < quota[s] && i < len(pool) {
pool[i].To = s
next[pool[i].Partition] = s
after[s]++
i++
}
}
if i != len(pool) {
return Plan{}, fmt.Errorf("rebalance: %d partitions left unassigned", len(pool)-i)
}
sort.Slice(pool, func(a, b int) bool { return pool[a].Partition < pool[b].Partition })
return Plan{Moves: pool, Before: before, After: after, Assignment: next}, nil
}
// Waves groups moves so that no shard takes part in more than perShard
// moves at once (MongoDB: one migration per shard; Citus: one background
// executor per node by default). Each wave can run in parallel.
func Waves(moves []Move, perShard int) [][]Move {
if perShard < 1 {
perShard = 1
}
left := slices.Clone(moves)
var waves [][]Move
for len(left) > 0 {
busy := map[router.ShardID]int{}
var wave, rest []Move
for _, m := range left {
if busy[m.From] < perShard && busy[m.To] < perShard {
busy[m.From]++
busy[m.To]++
wave = append(wave, m)
} else {
rest = append(rest, m)
}
}
waves = append(waves, wave)
left = rest
}
return waves
}
// Phase is one step of an online partition move.
type Phase int
const (
Backfill Phase = iota + 1 // copy a snapshot of the partition to the target
CatchUp // stream changes made since the snapshot (CDC, logical replication, audit log)
Verify // compare counts and checksums; run dark reads
Freeze // block writes for the partition; wait for zero lag
Cutover // flip routing to the target; bump the topology version
Unfreeze // accept writes on the target; keep reverse replication for rollback
Cleanup // after a grace period, delete the partition from the source
)
var phaseText = map[Phase]string{
Backfill: "backfill snapshot",
CatchUp: "catch up change stream",
Verify: "verify counts and checksums",
Freeze: "freeze writes, drain lag to zero",
Cutover: "flip routing, bump topology version",
Unfreeze: "unfreeze on target, reverse replication on",
Cleanup: "delete source copy after grace period",
}
func (p Phase) String() string { return phaseText[p] }
// Runbook renders the ordered phases for one move.
func Runbook(m Move) []string {
out := make([]string, 0, len(phaseText))
for p := Backfill; p <= Cleanup; p++ {
out = append(out, fmt.Sprintf("p%04d %s->%s %d. %s", m.Partition, m.From, m.To, int(p), p))
}
return out
}package rebalance
import (
"fmt"
"testing"
"academy/sharding-consistent-hashing-system/router"
)
func ids(n int) []router.ShardID {
out := make([]router.ShardID, n)
for i := range out {
out[i] = router.ShardID(fmt.Sprintf("s%d", i))
}
return out
}
func spread(m map[router.ShardID]int) int {
lo, hi := 1<<30, 0
for _, c := range m {
lo, hi = min(lo, c), max(hi, c)
}
return hi - lo
}
func TestAddShardMovesOnlyToNewShard(t *testing.T) {
fp, _ := router.NewFixedPartitions(64, ids(4)) // 16 each
plan, err := Compute(fp.Assignment(), ids(5))
if err != nil {
t.Fatal(err)
}
if len(plan.Moves) != 12 { // 64/5 = 12.8: four shards keep 13, s4 gets 12
t.Fatalf("moves = %d, want 12", len(plan.Moves))
}
for _, m := range plan.Moves {
if m.To != "s4" {
t.Fatalf("move between old shards: %+v", m)
}
}
if spread(plan.After) > 1 {
t.Fatalf("not balanced: %v", plan.After)
}
seen := map[int]bool{}
for _, m := range plan.Moves {
if seen[m.Partition] {
t.Fatalf("partition %d moved twice", m.Partition)
}
seen[m.Partition] = true
if plan.Assignment[m.Partition] != m.To {
t.Fatal("assignment does not reflect the move")
}
}
}
func TestNotionStyleTripling(t *testing.T) {
// 480 logical shards on 32 hosts (15 each) to 96 hosts (5 each).
fp, _ := router.NewFixedPartitions(480, ids(32))
plan, err := Compute(fp.Assignment(), ids(96))
if err != nil {
t.Fatal(err)
}
if len(plan.Moves) != 480-32*5 {
t.Fatalf("moves = %d, want %d", len(plan.Moves), 480-32*5)
}
for _, c := range plan.After {
if c != 5 {
t.Fatalf("every host should hold 5 logical shards: %v", plan.After)
}
}
}
func TestRemoveShardDrainsIt(t *testing.T) {
fp, _ := router.NewFixedPartitions(60, ids(5))
plan, err := Compute(fp.Assignment(), ids(4))
if err != nil {
t.Fatal(err)
}
if len(plan.Moves) != 12 {
t.Fatalf("moves = %d, want 12 (all of s4)", len(plan.Moves))
}
for _, m := range plan.Moves {
if m.From != "s4" {
t.Fatalf("unexpected source %+v", m)
}
}
if _, ok := plan.After["s4"]; ok {
t.Fatal("removed shard still has partitions")
}
}
func TestAlreadyBalancedIsNoop(t *testing.T) {
fp, _ := router.NewFixedPartitions(64, ids(4))
plan, _ := Compute(fp.Assignment(), ids(4))
if len(plan.Moves) != 0 {
t.Fatalf("expected no moves, got %d", len(plan.Moves))
}
}
func TestWavesRespectPerShardLimit(t *testing.T) {
fp, _ := router.NewFixedPartitions(64, ids(4))
plan, _ := Compute(fp.Assignment(), ids(5))
if w := Waves(plan.Moves, 1); len(w) != 12 {
t.Fatalf("one migration per shard: %d waves, want 12", len(w))
}
if w := Waves(plan.Moves, 2); len(w) != 6 {
t.Fatalf("two per shard: %d waves, want 6", len(w))
}
// Spreading 8 moves from 8 different shards to 8 new shards runs in one wave.
var moves []Move
for i := 0; i < 8; i++ {
moves = append(moves, Move{Partition: i, From: ids(8)[i], To: router.ShardID(fmt.Sprintf("n%d", i))})
}
if w := Waves(moves, 1); len(w) != 1 {
t.Fatalf("disjoint moves should share a wave: %d", len(w))
}
}
func TestRunbookOrder(t *testing.T) {
steps := Runbook(Move{Partition: 7, From: "s0", To: "s4"})
if len(steps) != 7 || steps[0] != "p0007 s0->s4 1. backfill snapshot" ||
steps[4] != "p0007 s0->s4 5. flip routing, bump topology version" {
t.Fatalf("runbook = %q", steps)
}
}
func TestRejectsBadInput(t *testing.T) {
if _, err := Compute(ids(2), ids(3)); err == nil {
t.Error("fewer partitions than shards")
}
if _, err := Compute(ids(4), []router.ShardID{"s0", "s0"}); err == nil {
t.Error("duplicate target")
}
}Ids that carry their logical shard, in Instagram's published bit layout:
// Package shardid builds 64-bit ids that carry their logical shard, in the
// layout Instagram published in 2012: 41 bits of milliseconds since a
// custom epoch, 13 bits of logical shard, 10 bits of a per-shard sequence.
// Any service can route a lookup by id alone. See /database/id-generation
// for the wider menu (Snowflake, ULID, UUIDv7).
package shardid
import (
"errors"
"time"
)
const (
shardBits = 13
seqBits = 10
maxShard = 1<<shardBits - 1
seqMask = 1<<seqBits - 1
)
// Epoch is the custom epoch; it must never change once ids exist.
var Epoch = time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC)
// ErrShardRange is returned for a shard outside 0..8191.
var ErrShardRange = errors.New("shardid: logical shard out of range")
// Compose packs time, logical shard and sequence (mod 1024) into an id.
func Compose(t time.Time, shard int, seq uint64) (int64, error) {
if shard < 0 || shard > maxShard {
return 0, ErrShardRange
}
ms := t.Sub(Epoch).Milliseconds()
return ms<<(shardBits+seqBits) | int64(shard)<<seqBits | int64(seq&seqMask), nil
}
// Shard extracts the logical shard: routing without a lookup.
func Shard(id int64) int { return int(id>>seqBits) & maxShard }
// Time extracts the creation time (ids sort by time across shards).
func Time(id int64) time.Time {
return Epoch.Add(time.Duration(id>>(shardBits+seqBits)) * time.Millisecond)
}package shardid
import (
"testing"
"time"
)
func TestRoundTrip(t *testing.T) {
at := Epoch.Add(1387263000 * time.Millisecond)
id, err := Compose(at, 1341, 5001)
if err != nil {
t.Fatal(err)
}
if Shard(id) != 1341 || !Time(id).Equal(at) || id&seqMask != 5001%1024 {
t.Fatalf("id %d: shard %d time %v", id, Shard(id), Time(id))
}
later, _ := Compose(at.Add(time.Millisecond), 0, 0)
if later <= id {
t.Fatal("ids must sort by time regardless of shard")
}
if _, err := Compose(at, 8192, 0); err == nil {
t.Fatal("shard 8192 must be rejected")
}
}The measurement program used in Mechanics and the Lab:
// movecost measures how much data moves when a cluster grows from 4 to 5
// shards under each placement strategy, and how even the load is.
//
// go run ./cmd/movecost
package main
import (
"fmt"
"academy/sharding-consistent-hashing-system/rebalance"
"academy/sharding-consistent-hashing-system/router"
)
func shards(n int) []router.ShardID {
out := make([]router.ShardID, n)
for i := range out {
out[i] = router.ShardID(fmt.Sprintf("s%d", i))
}
return out
}
type mod int
func (m mod) Name() string { return fmt.Sprintf("modulo-%d", int(m)) }
func (m mod) Shard(k string) (router.ShardID, error) {
return router.ShardID(fmt.Sprintf("s%d", router.Hash64(k)%uint64(m))), nil
}
func moved(a, b router.Strategy, keys int) float64 {
n := 0
for i := 0; i < keys; i++ {
k := fmt.Sprintf("user-%d", i)
x, _ := a.Shard(k)
y, _ := b.Shard(k)
if x != y {
n++
}
}
return 100 * float64(n) / float64(keys)
}
func imbalance(s router.Strategy, keys int) float64 {
c := map[router.ShardID]int{}
for i := 0; i < keys; i++ {
x, _ := s.Shard(fmt.Sprintf("user-%d", i))
c[x]++
}
lo, hi := keys, 0
for _, v := range c {
lo, hi = min(lo, v), max(hi, v)
}
return float64(hi) / float64(lo)
}
func main() {
const keys = 200_000
fmt.Printf("%-28s %10s %16s\n", "strategy (4 -> 5 shards)", "keys moved", "max/min load @5")
fmt.Printf("%-28s %9.1f%% %16.2f\n", "hash mod N", moved(mod(4), mod(5), keys), imbalance(mod(5), keys))
for _, v := range []int{1, 16, 256} {
a, _ := router.NewRing(shards(4), v)
b, _ := router.NewRing(shards(5), v)
fmt.Printf("%-28s %9.1f%% %16.2f\n", fmt.Sprintf("ring, %d vnodes/shard", v), moved(a, b, keys), imbalance(b, keys))
}
fp4, _ := router.NewFixedPartitions(1024, shards(4))
plan, _ := rebalance.Compute(fp4.Assignment(), shards(5))
fp5 := router.FromAssignment(plan.Assignment)
fmt.Printf("%-28s %9.1f%% %16.2f\n", "1024 fixed partitions", moved(fp4, fp5, keys), imbalance(fp5, keys))
fmt.Printf("\nplan: %d of 1024 partitions move, %d waves at 1 migration per shard\n",
len(plan.Moves), len(rebalance.Waves(plan.Moves, 1)))
for _, step := range rebalance.Runbook(plan.Moves[0]) {
fmt.Println(" ", step)
}
}Limits, stated so nobody mistakes this for a library: the directory is in memory (production keeps it in a replicated store and caches it with a version); the planner balances partition counts, not bytes or QPS (a weighted version sorts by measured load); Waves is greedy, not optimal; ScatterGather returns per-shard errors and leaves the partial-results policy to the caller; the Space-Saving eviction is O(capacity), fine for a few hundred counters.
The Go angle
- Placement hashes must be stable across processes and releases:
hash/fnvandhash/crc32are deterministic;hash/maphashand Go map iteration are randomised per process and must never decide placement. crc32.ChecksumIEEEequals PHP'scrc32()and many other languages' CRC-32, which is why it is the cross-language routing contract here (TestPartitionOfMatchesPHPcrc32pins a vector). Redis Cluster uses CRC16 (XMODEM variant) for the same reason: every client must agree.database/sqlgives one*sql.DBpool per shard; keep amap[ShardID]*sql.DBbuilt at start-up and size each pool for its shard (see Connection Pooling); Notion's PgBouncer sharding shows connection counts multiply during a move.context.WithTimeoutper shard plus a semaphore channel gives bounded fan-out;errgroup.GroupwithSetLimitfromgolang.org/x/syncis the library version, but it cancels siblings on the first error, which is wrong when partial results are acceptable.sort.Searchover sorted range bounds or ring points is the O(log n) lookup; build the ring once and swap it atomically (atomic.Pointer[Ring]) on membership change.- go-redis
ClusterClientfollowsMOVEDandASKautomatically and groups pipelines by node; the MongoDB Go driver talks tomongosand needs nothing special; Vitess speaks the MySQL protocol, sogo-sql-driver/mysqlconnects to vtgate unchanged.
Laravel
Before
One connection; a tenant page that never names a shard, a support search that joins across what will become shards, and a DB::transaction that will silently stop being atomic.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
/**
* Before: one connection, and queries that only work while every row lives
* in one database. Each line marked below breaks the day the table is split.
*/
final class OrderController
{
public function index(Request $request)
{
$tenantId = $request->user()->tenant_id;
// Works on one database. After sharding: which shard? Nobody passes it.
return DB::table('orders')
->where('tenant_id', $tenantId)
->orderByDesc('created_at')
->limit(20)
->get();
}
public function supportSearch(Request $request)
{
// No tenant in the filter: after sharding this is a scatter-gather
// over every shard, and the JOIN to customers may cross shards.
return DB::table('orders')
->join('customers', 'customers.id', '=', 'orders.customer_id')
->where('customers.email', $request->string('email'))
->orderByDesc('orders.created_at')
->limit(20)
->get();
}
public function transfer(Request $request)
{
// One ACID transaction across two tenants. After sharding the two
// rows may live on different databases and this stops being atomic.
DB::transaction(function () use ($request) {
DB::table('credits')->where('tenant_id', $request->integer('from'))->decrement('balance', 100);
DB::table('credits')->where('tenant_id', $request->integer('to'))->increment('balance', 100);
});
return response()->noContent();
}
}After
The routing contract and one connection per shard (merged into config/database.php):
<?php
/*
* Routing contract. Partition = crc32(tenant_id) % partitions, exactly what
* the Go router's PartitionOf computes. The number of partitions never
* changes; the map from partition ranges to connections does.
*/
return [
'partitions' => 1024,
// Inclusive partition ranges => connection names in config/database.php.
// Rebalancing edits this map (or the shard_directory table), never the hash.
'map' => [
[0, 255, 'shard_0'],
[256, 511, 'shard_1'],
[512, 767, 'shard_2'],
[768, 1023, 'shard_3'],
],
// Connection that holds the shard_directory table and other global data.
'directory_connection' => env('SHARD_DIRECTORY_CONNECTION', 'pgsql'),
// Seconds a resolved placement may be cached by each app server.
'cache_ttl' => 30,
];<?php
/*
* Merged into config/database.php:
* 'connections' => [ 'pgsql' => [...], ...require __DIR__.'/database-shards.php' ],
* One connection per physical shard; each may have its own read replicas.
*/
$shards = [];
foreach (explode(',', env('SHARD_HOSTS', 'db-0.internal,db-1.internal,db-2.internal,db-3.internal')) as $i => $host) {
$shards["shard_{$i}"] = [
'driver' => 'pgsql',
'host' => trim($host),
'port' => env('SHARD_PORT', '5432'),
'database' => env('SHARD_DATABASE', 'app'),
'username' => env('SHARD_USERNAME', 'app'),
'password' => env('SHARD_PASSWORD', ''),
'charset' => 'utf8',
'prefix' => '',
'search_path' => 'public',
'sslmode' => 'require',
];
}
return $shards;The directory table on the central connection:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
/*
* Lookup service table on the directory connection. A row overrides the
* hash placement for one tenant (a whale on its own shard, a tenant being
* moved). No row means: use crc32(tenant_id) % partitions and the map.
*/
return new class extends Migration
{
public function up(): void
{
Schema::connection(config('sharding.directory_connection'))->create('shard_directory', function (Blueprint $table) {
$table->string('tenant_id')->primary();
$table->string('connection'); // e.g. shard_4
$table->string('status')->default('active'); // active | moving
$table->unsignedBigInteger('version')->default(1);
$table->timestamps();
});
}
public function down(): void
{
Schema::connection(config('sharding.directory_connection'))->dropIfExists('shard_directory');
}
};The shard resolver (directory first, CRC-32 partition and map second, cached, with a write freeze) and its exception:
<?php
namespace App\Sharding;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
/**
* Tenant id in, connection name out. Directory row first (overrides and
* moves), then the fixed-partition hash. Register as a singleton.
*/
final class ShardResolver
{
public function partitionOf(string $tenantId): int
{
// Same contract as Go router.PartitionOf: CRC-32 (IEEE) mod P.
return crc32($tenantId) % (int) config('sharding.partitions');
}
public function connectionFor(string $tenantId): string
{
return $this->placement($tenantId)['connection'];
}
/** Refuses while the tenant is frozen for cutover. */
public function connectionForWrite(string $tenantId): string
{
$placement = $this->placement($tenantId);
if ($placement['status'] === 'moving') {
throw new TenantMoving("tenant {$tenantId} is moving, retry shortly");
}
return $placement['connection'];
}
/** @return list<string> every shard connection, for scatter-gather */
public function allConnections(): array
{
return array_values(array_unique(array_column(config('sharding.map'), 2)));
}
/** @return array{connection: string, status: string} */
public function placement(string $tenantId): array
{
$row = Cache::remember(
"shard:dir:{$tenantId}",
(int) config('sharding.cache_ttl'),
fn () => DB::connection(config('sharding.directory_connection'))
->table('shard_directory')
->where('tenant_id', $tenantId)
->first(['connection', 'status']) ?? false, // cache the miss too
);
if ($row !== false && $row !== null) {
return ['connection' => $row->connection, 'status' => $row->status];
}
$partition = $this->partitionOf($tenantId);
foreach (config('sharding.map') as [$from, $to, $connection]) {
if ($partition >= $from && $partition <= $to) {
return ['connection' => $connection, 'status' => 'active'];
}
}
throw new \LogicException("partition {$partition} is not mapped");
}
/** Call after changing a directory row so this server stops using the old answer. */
public function forget(string $tenantId): void
{
Cache::forget("shard:dir:{$tenantId}");
}
}<?php
namespace App\Sharding;
use RuntimeException;
/** Thrown for writes while a tenant is being cut over; callers retry. */
final class TenantMoving extends RuntimeException
{
}A tenant-aware model trait: forTenant() binds the query to the tenant's connection with Model::on() and filters by tenant; getConnectionName() routes saves by the model's own tenant_id; saving and deleting listeners refuse writes during a move:
<?php
namespace App\Models\Concerns;
use App\Sharding\ShardResolver;
use Illuminate\Database\Eloquent\Builder;
use LogicException;
/**
* For models whose table exists on every shard and is partitioned by
* tenant_id. Reads go through forTenant(); a model saves to the shard of
* its own tenant_id; writes are refused while the tenant is being cut over.
*/
trait ShardedByTenant
{
public static function bootShardedByTenant(): void
{
$guard = function ($model) {
$tenantId = $model->getAttribute('tenant_id');
if (empty($tenantId)) {
throw new LogicException($model::class.' needs tenant_id before it can be routed');
}
// Throws App\Sharding\TenantMoving during the cutover freeze.
app(ShardResolver::class)->connectionForWrite((string) $tenantId);
};
static::saving($guard);
static::deleting($guard);
}
/** Entry point for reads: a query bound to the tenant's shard and filtered by it. */
public static function forTenant(string $tenantId): Builder
{
$connection = app(ShardResolver::class)->connectionFor($tenantId);
return static::on($connection)->where('tenant_id', $tenantId);
}
/**
* Eloquent asks the model for its connection when saving, deleting and
* building relations. Route by the model's own tenant_id when it has one;
* otherwise keep whatever connection the query or parent model set.
*/
public function getConnectionName()
{
$tenantId = $this->attributes['tenant_id'] ?? null;
if ($tenantId !== null) {
return app(ShardResolver::class)->connectionFor((string) $tenantId);
}
return parent::getConnectionName();
}
}<?php
namespace App\Models;
use App\Models\Concerns\ShardedByTenant;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
/**
* Primary key is (tenant_id, id) on every shard; id is globally unique
* (Snowflake-style, see /database/id-generation), so no shard can mint a
* duplicate and an order can move between shards without renumbering.
*/
class Order extends Model
{
use ShardedByTenant;
public $incrementing = false;
protected $keyType = 'int';
protected $fillable = ['id', 'tenant_id', 'customer_id', 'total_cents', 'status'];
/** Co-located: order lines carry the same tenant_id and live on the same shard. */
public function lines(): HasMany
{
return $this->hasMany(OrderLine::class)->where('tenant_id', $this->tenant_id);
}
}<?php
namespace App\Models;
use App\Models\Concerns\ShardedByTenant;
use Illuminate\Database\Eloquent\Model;
class OrderLine extends Model
{
use ShardedByTenant;
protected $fillable = ['tenant_id', 'order_id', 'sku', 'quantity', 'price_cents'];
}The scatter-gather helper on Concurrency::run (child processes, named results, a timeout), with the per-shard LIMIT and merge:
<?php
namespace App\Sharding;
use Closure;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Concurrency;
use Illuminate\Support\Facades\DB;
/**
* Runs the same query on every shard in parallel child processes
* (Concurrency::run, process driver) and merges the answers. Use it for
* admin and support screens; product paths should carry the tenant id.
*/
final class ScatterGather
{
public function __construct(private readonly ShardResolver $resolver)
{
}
/**
* ORDER BY $column DESC LIMIT $limit across shards: each shard returns
* its own top $limit, then the merge keeps the global top $limit.
*
* @param Closure(\Illuminate\Database\Query\Builder): \Illuminate\Database\Query\Builder $query
*/
public function topN(string $table, Closure $query, string $column, int $limit, int $timeout = 5): Collection
{
$tasks = [];
foreach ($this->resolver->allConnections() as $connection) {
$tasks[$connection] = fn () => $query(DB::connection($connection)->table($table))
->orderByDesc($column)
->limit($limit)
->get()
->map(fn ($row) => (array) $row + ['_shard' => $connection])
->all();
}
// Named results; a task that exceeds $timeout seconds is terminated
// and the whole call fails: decide whether partial results are fine.
$perShard = Concurrency::run($tasks, timeout: $timeout);
return collect($perShard)
->flatten(1)
->sortByDesc($column)
->take($limit)
->values();
}
/** COUNT(*) is additive; AVG is not (sum the sums and the counts instead). */
public function count(string $table, Closure $query): int
{
$tasks = [];
foreach ($this->resolver->allConnections() as $connection) {
$tasks[$connection] = fn () => $query(DB::connection($connection)->table($table))->count();
}
return array_sum(Concurrency::run($tasks));
}
}The controller after the change:
<?php
namespace App\Http\Controllers;
use App\Models\Order;
use App\Sharding\ScatterGather;
use Illuminate\Http\Request;
/** After: every product query carries the tenant; support search is an explicit scatter. */
final class OrderController
{
public function index(Request $request)
{
// Single-shard, single-partition query: the common path.
return Order::forTenant((string) $request->user()->tenant_id)
->latest()
->limit(20)
->get();
}
public function supportSearch(Request $request, ScatterGather $scatter)
{
// Rare admin path: fan out, merge top 20. customer_email is
// denormalised onto orders so no cross-shard JOIN is needed.
return $scatter->topN(
'orders',
fn ($q) => $q->where('customer_email', $request->string('email')),
'created_at',
20,
);
}
}An online tenant move: backfill with chunkById and idempotent upsert, catch-up passes on updated_at, freeze through the directory, final catch-up, count-and-checksum verification, cutover:
<?php
namespace App\Console\Commands;
use App\Sharding\ShardResolver;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
/**
* Online move of one tenant between shards:
* backfill -> catch up -> verify -> freeze -> final catch up -> cutover -> cleanup later.
* Relies on updated_at being set on every write (Eloquent timestamps) and on
* soft deletes, so the catch-up pass also sees deletions.
*/
final class MoveTenant extends Command
{
protected $signature = 'shard:move-tenant {tenant} {to} {--tables=orders,order_lines} {--chunk=1000}';
protected $description = 'Move one tenant to another shard with backfill, catch-up, verify and cutover';
public function handle(ShardResolver $resolver): int
{
$tenant = (string) $this->argument('tenant');
$to = (string) $this->argument('to');
$from = $resolver->connectionFor($tenant);
$tables = explode(',', (string) $this->option('tables'));
if ($from === $to) {
$this->info("tenant {$tenant} already on {$to}");
return self::SUCCESS;
}
// 1. Backfill while writes continue on the source.
$since = now()->subSecond();
foreach ($tables as $table) {
$this->copy($tenant, $table, $from, $to, null);
}
// 2. Catch up rows changed during the backfill (repeat until small).
foreach (range(1, 3) as $pass) {
$next = now()->subSecond();
$changed = 0;
foreach ($tables as $table) {
$changed += $this->copy($tenant, $table, $from, $to, $since);
}
$since = $next;
$this->line("catch-up pass {$pass}: {$changed} rows");
if ($changed < 100) {
break;
}
}
// 3. Freeze writes for this tenant only (ShardResolver::connectionForWrite throws).
$this->setDirectory($resolver, $tenant, $from, 'moving');
sleep((int) config('sharding.cache_ttl') + 1); // every server must see "moving"
// 4. Final catch-up and verification with writes stopped.
foreach ($tables as $table) {
$this->copy($tenant, $table, $from, $to, $since);
if (! $this->same($tenant, $table, $from, $to)) {
$this->setDirectory($resolver, $tenant, $from, 'active'); // roll back the freeze
$this->error("verification failed on {$table}; tenant stays on {$from}");
return self::FAILURE;
}
}
// 5. Cutover: one directory write flips reads and writes to the target.
$this->setDirectory($resolver, $tenant, $to, 'active');
$this->info("tenant {$tenant} moved {$from} -> {$to}; delete source rows after the grace period");
return self::SUCCESS;
}
private function copy(string $tenant, string $table, string $from, string $to, $since): int
{
$copied = 0;
DB::connection($from)->table($table)
->where('tenant_id', $tenant)
->when($since, fn ($q) => $q->where('updated_at', '>=', $since))
->chunkById((int) $this->option('chunk'), function ($rows) use ($table, $to, &$copied) {
$values = $rows->map(fn ($row) => (array) $row)->all();
$columns = array_keys($values[0]);
// Idempotent: re-running a chunk overwrites with the same values.
DB::connection($to)->table($table)->upsert($values, ['id'], array_diff($columns, ['id']));
$copied += count($values);
});
return $copied;
}
private function same(string $tenant, string $table, string $from, string $to): bool
{
// Row count plus a sum of per-row hashes (PostgreSQL hashtext). Same
// schema and column order on both shards is assumed.
$fingerprint = fn (string $connection) => DB::connection($connection)->table($table, 't')
->where('t.tenant_id', $tenant)
->selectRaw('count(*) as n, coalesce(sum(hashtext(t::text)), 0) as h')
->first();
return $fingerprint($from) == $fingerprint($to);
}
private function setDirectory(ShardResolver $resolver, string $tenant, string $connection, string $status): void
{
DB::connection(config('sharding.directory_connection'))->table('shard_directory')->upsert(
[['tenant_id' => $tenant, 'connection' => $connection, 'status' => $status, 'version' => 1, 'created_at' => now(), 'updated_at' => now()]],
['tenant_id'],
['connection', 'status', 'updated_at'],
);
DB::connection(config('sharding.directory_connection'))->table('shard_directory')
->where('tenant_id', $tenant)->increment('version');
$resolver->forget($tenant);
}
}Limits: every file passes php -l and uses APIs checked against the Laravel 13 documentation or framework source, but nothing was executed against real databases. MoveTenant relies on updated_at from the database clock and on soft deletes (hard deletes during the move are not caught up); the freeze waits one cache TTL so every server sees moving; the checksum assumes identical column order on both shards; the source copy must be deleted later by a separate, deliberate step.
The Laravel angle
DB::connection('shard_2')returns any connection defined inconfig/database.php("you may access each connection via the connection method provided by the DB facade"); connections are lazy, so defining 96 of them costs nothing until used.- Laravel 13 documents a model's fixed connection with the
#[Connection('mysql')]attribute; per-tenant routing needs a dynamic choice, so the trait overridesgetConnectionName()and uses the staticModel::on($connection)(both public framework methods inIlluminate\Database\Eloquent\Model). - Relations inherit the parent's connection when the related model has none, which is why co-located child tables (
order_lines) work through$order->lineson the same shard. DB::transaction()is per connection. A closure that writes to two shards is two transactions; make cross-shard work a saga with queued jobs and idempotent steps.Concurrency::run([...], timeout: 30)runs closures "simultaneously in child PHP processes" with the defaultprocessdriver; theforkdriver is faster but CLI-only; results must be serialisable, so return arrays, not models.- Read/write splitting (
read,write,sticky) works inside each shard connection; Laravel 13 also documentsDB::connection('mysql')->olap(...)for analytical queries on Vitess (PlanetScale), the right workload type for a scatter-gather report. chunkByIdkeeps memory flat during backfills and is restart-safe because it pages by key, not by offset;upsertmakes re-running a chunk harmless.
Solving the classic problems
The celebrity key
Symptom: one shard at 100% CPU or one DynamoDB partition throttled while the rest idle; top-keys shows one account.
| Solution | How | Advantage | Cost or limit |
|---|---|---|---|
| Cache hot reads | Read-through cache with request coalescing in front of the shard | Removes most reads at once | Writes unchanged; invalidation |
| Salt the write key | key#0..key#N-1, reads merge | Writes spread over N partitions | N reads per full read |
| Split the entity | Separate the follower list from the profile; shard followers by follower id | Hot part isolated | Data model change |
| Fan-out on read for celebrities | Do not push a celebrity's posts to every follower's feed | Write amplification gone | Read-time merge (see Feeds) |
| Dedicated shard | Directory pin | Noisy-neighbour isolation | Still one machine for that key |
The monotonic key hotspot
Symptom: inserts all land on the newest range; MongoDB balancer keeps moving the top chunk; Citus or Cassandra hold "today" on one node.
| Solution | How | Advantage | Cost or limit |
|---|---|---|---|
| Hash the key | MongoDB hashed shard key, Vitess xxhash vindex, Figma "hash of the sharding key" | Even inserts | Range scans on the key scatter |
| Prefix with an entity | (sensor_id, ts), (tenant_id, created_at) | Even writes, range reads per entity | Cross-entity time ranges scatter |
| Time bucket plus salt | day#salt | Bounded partitions | N reads per bucket |
| Range partition by time on one host | PostgreSQL declarative partitioning, not sharding | Cheap retention by dropping partitions | One host's write limit |
The whale tenant
Symptom: one tenant's data or QPS approaches a shard's capacity; neighbours' p99 rises.
| Solution | How | Advantage | Cost or limit |
|---|---|---|---|
| Directory pin to a dedicated shard | MoveTenant then a directory row | No code change for the tenant | Must still fit one shard |
| Citus tenant isolation | isolate_tenant_to_new_shard, then citus_move_shard_placement | Built in | Citus only |
| Sub-shard the tenant | Composite key (tenant_id, project_id) for that tenant | Scales beyond one shard | Cross-project queries scatter for that tenant |
| Per-tenant rate limits | Limit at the gateway | Protects neighbours | Does not add capacity |
Adding capacity before a known peak
Symptom: projections say the fleet runs out of CPU or IOPS before the next peak (Notion's new-year spike).
| Solution | How | Advantage | Cost or limit |
|---|---|---|---|
| Move fixed partitions to new hosts | Plan with rebalance.Compute, copy with logical replication, flip per host | No key changes partition | Copy time; connections multiply (Notion had to shard PgBouncer) |
| Split ranges | Vitess Reshard -80 into -40,40-80 | Built-in workflow | Read-only cutover seconds |
| Vertical scale the hottest shards | Bigger instance for the shards that need it | Fast | Only buys time |
Search without the shard key
Symptom: support or login queries by email/phone scatter over every shard.
| Solution | How | Advantage | Cost or limit |
|---|---|---|---|
| Lookup table | email -> tenant_id/user_id, unique, on a directory store | One lookup, global uniqueness | Extra write; keep in sync |
| Global secondary index | DynamoDB GSI, Vitess lookup vindex | Managed | Eventual consistency |
| Search index from CDC | Elasticsearch fed from all shards | Full-text and filters | Seconds of lag, another system |
| Explicit scatter for rare admin use | ScatterGather::topN with deadlines | No new system | N x work |
A transaction across two shards
Symptom: a business operation must change rows of two tenants or two aggregates that live on different shards.
| Solution | How | Advantage | Cost or limit |
|---|---|---|---|
| Re-key so they co-locate | Shard by the enclosing aggregate (organisation, not team) | Plain ACID | May create a whale |
| Saga with outbox | Local transaction plus event, compensation | Works on any store | Visible pending state |
| Product 2PC | Citus, Spanner, CockroachDB, Vitess atomic transactions | Atomic | Latency, coordinator recovery |
Resharding war stories
Every claim in this section is from the company's own post (saved, see References); the "lesson" column is this chapter's reading of it and is labelled inference.
| Company | What they did | Numbers they published | Lesson (inference) |
|---|---|---|---|
| Notion (2021) | Application-level sharding of Postgres by workspace ID; audit-log catch-up; backfill; verification by sampled ranges and dark reads; five-minute maintenance window | 480 logical shards, 32 hosts, 15 schemas per host; backfill "around three days" on 96 CPUs | Factor-rich logical shard counts make later growth a mapping change |
| Notion (2023) | Re-sharded 32 to 96 hosts with Postgres logical replication, sharded PgBouncer first, failed over per host with reverse replication | "from having 15 schemas per shard to 5"; sync time "from 3 days to 12 hours" without indexes; CPU and IOPS "around 20%" after | Plan for the connection layer as part of resharding; rollback path via reverse replication |
| Figma (2024) | Colos by UserID/FileID/OrgID; hashed routing; logical sharding through views; DBProxy query engine with scatter-gather; no atomic cross-shard transactions | First table sharded after "roughly nine months"; failover with "only ten seconds of partial availability" | Separate logical from physical sharding so the risky step is small; measure which queries would scatter before choosing keys |
| Instagram (2012) | Several thousand logical shards as Postgres schemas mapped to fewer hosts; ids generated in PL/pgSQL with the shard inside | 41 bits time, 13 bits shard, 10 bits sequence | Put the shard in the id and routing needs no lookup |
| Pinterest (2015) | MySQL shards db00000..; placement never changes; config of shard ranges to hosts in ZooKeeper; mod shard for non-id lookups; JSON blobs to avoid ALTERs | 4,096 initial shards of a 16-bit shard space; 64-bit ids | Immutable placement plus moving whole shards between hosts keeps operations simple |
Choosing
Strategy for the workload
| Workload | Partition key | Strategy | Extra technique | Reason |
|---|---|---|---|---|
| B2B SaaS | tenant_id | Hashed fixed partitions plus directory | Isolate whales, reference tables | Almost every query and transaction is per tenant |
| Consumer social app | user_id | Hash or fixed partitions | Celebrity handling, lookup tables for email/handle | Point access by user; skew from celebrities |
| Time series / IoT | (device_id, time bucket) | Hash on device, range on time inside | Retention by bucket, salting for hot devices | Writes are "now"; reads are per device and recent |
| Event log / analytics | event_id hashed, or (tenant_id, day) | Hash | CDC to a warehouse | Even ingest; analysis elsewhere |
| Geo-regulated product | (region, tenant_id) | Directory by region | Region pinning, separate global data | Law and latency |
| Cache cluster | The cache key | Consistent hashing with vnodes | Hash tags for multi-key operations | Membership changes often; no central table |
| Chat / messaging | channel_id ((channel_id, bucket) in Cassandra) | Hash, bucketed partitions | Bucket by time to bound partition size | Reads per channel; wide partitions otherwise |
Build, adopt or avoid
| Option | When it fits | What you give up |
|---|---|---|
| Do not shard (replicas, cache, bigger box, vertical partitioning) | The limit is reads, or growth fits one more instance size | Nothing yet; revisit with numbers |
| Application-level sharding (Notion, Figma, Instagram, Pinterest) | Strong in-house database operations, clear key, custom needs | You build routing, moves, tooling |
| Vitess | MySQL at scale, want a proxy and resharding workflows | MySQL only; some SQL limits across shards |
| Citus | PostgreSQL, multi-tenant or real-time analytics | Extension and coordinator operations; co-location rules |
| MongoDB sharding | Document model fits; want balancer and mongos | Shard key discipline; broadcast queries |
| DynamoDB / Cassandra | Key-value or wide-column access patterns known up front | Joins, ad hoc queries, transactions beyond the product's limits |
| Distributed SQL (Spanner, CockroachDB, TiDB, YugabyteDB) | Want SQL and transactions across partitions without app routing | Latency of consensus, cost, migration (Figma weighed this and deferred it) |
In architecture: from a single process to a distributed system
Monolith: one process, one database
A Laravel or Go monolith on one PostgreSQL. Do not shard; prepare. Put tenant_id (or the future key) on every table and in every primary key and unique index, pass it through every query, use ids that will stay unique across databases, and keep transactions inside one tenant. Notion's lesson was that the partition key "was not yet populated in the old database". If one table dominates, partition it on the same host with PostgreSQL declarative partitioning first.
Modular monolith: boundaries without the network
Each module owns its tables and can move to its own database (vertical partitioning, Figma's first lever). Modules call each other through interfaces, not joins, so a module can later be sharded by its own key (billing by account, content by workspace). The shard key is a module decision; the resolver lives in the module's infrastructure layer.
Microservices: every arrow is a decision
Each service owns its data (Data Ownership in Microservices) and may shard it by a different key: orders by tenant_id, notifications by user_id. A request that crosses services and shards becomes a saga with an outbox, never a distributed transaction across services. Example: POST /transfers on the billing service debits tenant 3 on shard 0 and writes TransferDebited to the outbox in the same local transaction; the relay publishes; the billing consumer for tenant 9 (shard 2) applies the credit idempotently keyed by transfer_id; a timeout triggers the compensation. Read models that need data across shards are built from events (Data Patterns: CQRS).
Distributed data: replicas, caches, regions
Each shard is itself a replica set (Vitess: "sharding is orthogonal to (MySQL) replication"), so every shard has its own failover, lag and read-your-writes concerns (Replication, Read Replicas & Failover). Caches in front of shards must key by the same partition key; Redis Cluster adds its own slot sharding with hash tags. Across regions, geo sharding gives each record one home region; reads from elsewhere pay the cross-region round trip. During a move, replicas and caches of the old owner can serve stale data after cutover: invalidate by topology version. Consistency guarantees stop at the shard boundary; see Consistency Models and CAP & PACELC.
Scaling path: 1x, 10x, 100x
| Load | Design | What changes |
|---|---|---|
| 1x: one primary at 30% | One database, replicas for reads, tenant id everywhere | Nothing to shard; keep the key in every query |
| 10x: primary at 70% IOPS or table maintenance failing | Vertical partitioning; then logical sharding (views or schemas) on the same hosts | Router and directory in place; scatter queries found and removed |
| 100x: many hosts | Fixed logical partitions on 8 to 32 hosts; directory for whales; global ids; lookup tables | Online moves, fleet-wide migrations, per-shard observability |
| 1000x: hundreds of hosts, several regions | Hundreds of hosts, geo directory, automated rebalancing, CQRS read side, warehouse for analytics | Topology service, automated move planner, per-tenant isolation as a product feature |
Lab: placement, move cost and an online move
Steps 1 and 2 were run on the author's laptop (Go only, no database). Steps 3 to 6 are expected, not run: they need PostgreSQL with Citus, MongoDB or Redis Cluster, which this lab does not start.
-- Schema used by steps 3 to 5 (each shard has the same tables).
CREATE TABLE orders (
tenant_id text NOT NULL,
id bigint NOT NULL, -- global id (shardid package)
customer_email text NOT NULL, -- denormalised for support search
total_cents bigint NOT NULL,
status text NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now(),
deleted_at timestamptz,
PRIMARY KEY (tenant_id, id)
);
CREATE UNIQUE INDEX orders_id ON orders (id);
CREATE INDEX orders_tenant_created ON orders (tenant_id, created_at DESC);- Run the tests and the movement measurement (run):
$ cd docs/snippets/system-design/sharding-consistent-hashing-system/go
$ go test -race -count=1 ./...
ok academy/sharding-consistent-hashing-system/hotkey
ok academy/sharding-consistent-hashing-system/rebalance
ok academy/sharding-consistent-hashing-system/router
ok academy/sharding-consistent-hashing-system/shardid
$ go run ./cmd/movecost
strategy (4 -> 5 shards) keys moved max/min load @5
hash mod N 80.1% 1.01
ring, 1 vnodes/shard 37.7% 61.89
ring, 16 vnodes/shard 22.4% 1.79
ring, 256 vnodes/shard 17.8% 1.27
1024 fixed partitions 19.9% 1.00
plan: 204 of 1024 partitions move, 204 waves at 1 migration per shard
p0820 s0->s4 1. backfill snapshot
...
p0820 s0->s4 7. delete source copy after grace period- The before program (run):
go run ./beforeprints4 -> 5 shards: 80017 of 100000 keys change shard (80.0%). Every one of those rows would have to be copied while the system is live. - Citus co-location and a router query (expected, not run):
SELECT create_distributed_table('orders', 'tenant_id');thenEXPLAIN SELECT * FROM orders WHERE tenant_id = 't7' ORDER BY created_at DESC LIMIT 20;. Expected: a plan with one task ("Task Count: 1"). Remove thetenant_idfilter: the task count becomes the shard count (32 by default). - Add a worker and rebalance online (expected, not run):
SELECT citus_add_node('worker-3.example.internal', 5432); SELECT citus_rebalance_start();while a pgbench script inserts orders for random tenants. Expected: inserts continue (non-blocking since Citus 11.0),SELECT * FROM citus_rebalance_status();shows moves running one per node by default. - Hot key on Redis Cluster (expected, not run): three masters,
redis-benchmark -t incr -r 1 -n 1000000 -c 50against one key. Expected: one node saturates while the others idle; repeat with eight keyscnt:p7:0..7(no hash tag) and the load spreads; with the tag (cnt:{p7}:0..7) they all land in one slot again. - Slot migration seen by a client (expected, not run):
CLUSTER SETSLOT 8 IMPORTING <A-id>on B,CLUSTER SETSLOT 8 MIGRATING <B-id>on A, move some keys withMIGRATE;redis-cli -c GETon a moved key prints a redirect via-ASK, and afterCLUSTER SETSLOT 8 NODE <B-id>a request to A answers-MOVED 8.
Common misconceptions
| Belief | Reality |
|---|---|
| "Sharding is the first step to scale." | It is the last; replicas, caches, indexes, vertical partitioning and bigger machines come first |
| "Hashing guarantees even load." | It spreads distinct keys; one hot key is still one shard |
"hash(key) % N is fine." | Changing N moves about (N-1)/N of the data; use fixed partitions or a ring |
| "Consistent hashing moves nothing." | It moves about 1/(N+1), the minimum, and needs vnodes for even load |
| "Adaptive capacity removes hot partitions in DynamoDB." | One item key still tops out at 3,000 RCU / 1,000 WCU |
| "A proxy makes sharding transparent." | It hides location, not the cost of scatter-gather or cross-shard joins |
| "Scatter-gather is parallel, so it is fast." | Work is N times higher and latency is the slowest shard's |
| "Each shard can return LIMIT/N rows." | Each must return LIMIT rows; the merge re-applies the limit |
| "A unique index on a sharded table is globally unique." | Only within one shard, unless it includes the shard key or is a global lookup |
"DB::transaction covers both shards." | It covers one connection; the second write is independent |
| "Dual writes from the app are the easy migration." | Partial failures diverge the copies; use a log-based catch-up |
| "Pick the shard key later." | Changing it is a full data migration |
| "Database per tenant scales best." | It isolates, but multiplies migrations, connections and backups |
| "Auto-increment ids still work." | Every shard mints the same ids; use a global scheme |
Cheat sheet
| Topic | What to remember |
|---|---|
| When | Shard for writes, size or maintenance limits of one primary, after cheaper moves |
| Key | In almost every query and transaction; high cardinality; no dominant value; not monotonic |
| Strategy | Hash into fixed partitions (or a ring), plus a directory for exceptions |
| P | Many more partitions than hosts; factor-rich if partitions are heavy (Notion's 480) |
| Range | For range scans; never with a "now" prefix |
| Hot key | Detect top keys; cache reads; salt writes; isolate whales |
| Salting | N = rate / (limit x utilisation); reads query all N and merge |
| Co-location | Same key for tables joined or written together; reference tables for small shared data |
| Moves | Backfill, catch up from a log, verify, freeze seconds, cutover with a version, reverse replication, cleanup |
| Routing | Client library, proxy (vtgate, mongos, coordinator) or lookup; version the map |
| Scatter | Admin paths only; per-shard deadline; each shard returns full LIMIT; keyset pagination |
| Indexes | Local is cheap to write, scatters on read; global is one read, eventual |
| Transactions | Single-shard by design; saga for the rest; 2PC only inside a product |
| Ids | Time-ordered 64-bit ids that carry the logical shard |
| Products | DynamoDB 1,000 WCU/partition; MongoDB 128 MB chunks; Redis 16384 slots; Citus 32 shards; Cassandra 2 billion cells |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — Your PostgreSQL primary is at 85% CPU, almost all from reads. Should you shard? Must-know
Answer
Answer: No. Reads scale with replicas and caches; fix the queries and indexes, add read replicas with a read-your-writes policy, and cache hot reads. Shard when writes, size or maintenance exceed what one primary can do.
2 — Why is hash(user_id) % N a bad placement function, and what replaces it? Must-know
Answer
Answer: When N changes, about (N-1)/N of keys change shard (80% from 4 to 5 in the lab). Hash into a fixed number of partitions and map partitions to hosts with a table, or use a consistent-hash ring with virtual nodes; both move about 1/(N+1).
3 — MongoDB lists three properties of a good shard key. Name them and give a bad key for each. Important
Answer
Answer: Cardinality (continent has 7 values, so at most 7 chunks), frequency (status where 90% are done), and monotonic change (createdAt or ObjectId on a ranged key sends all inserts to one chunk).
4 — A DynamoDB table keyed by date throttles every day at 09:00. Explain and fix it. Must-know
Answer
Answer: All writes for today hit one partition key, capped at 1,000 WCU per partition even with adaptive capacity. Add a suffix: random date#1..N for spreading writes, or calculated from the order id for point reads; reads of a whole day query all N and merge. Size N from the write rate.
5 — Notion chose 480 logical shards. Why not 512? Good to know
Answer
Answer: 480 has many factors (32, 40, 48, 60, 80, 96, ...), so hosts can grow in small steps with an even number of shards each. 512's factors are powers of two, so even distribution requires doubling the host count.
6 — What are the phases of an online partition move, and which one is the only time writes stop? Important
Answer
Answer: Backfill, catch-up from a change stream, verify, freeze, cutover (flip routing, bump version), rollback window with reverse replication, cleanup. Writes stop only during the freeze, for seconds (Vitess: "a few seconds of read-only downtime"; MongoDB reshardCollection: up to two seconds).
7 — A support search by email takes 900 ms on 64 shards though each shard answers in 10 ms on average. Why, and what do you change? Important
Answer
Answer: The query scatters to 64 shards and waits for the slowest; with 64 shards some shard is almost always in its tail. Add a lookup table or global index from email to tenant/user, or a search index fed by CDC; keep scatter for rare admin use with per-shard deadlines.
8 — What is the difference between a DynamoDB LSI and GSI for a sharded design? Important
Answer
Answer: An LSI shares the base table's partition key (local, strong reads allowed, created with the table, 10 GB per key value). A GSI has its own partition key (global, updated asynchronously, eventually consistent reads only, its own capacity, can throttle base writes).
9 — Two tenants on different shards must exchange credits atomically. Give two designs and their costs. Important
Answer
Answer: A saga: debit with an outbox event on shard A, idempotent credit on shard B, compensation on failure; visible pending state and compensation logic. Or 2PC through a product that recovers in-doubt transactions (Citus, Spanner, CockroachDB, Vitess); coordinator latency and locks during prepare. Best: re-key so the operation is single-shard if it is frequent.
10 — Why do Instagram and Pinterest put the shard number inside the id? Good to know
Answer
Answer: Any service can find the shard of an object from its id with a bit shift, without a lookup, and ids stay unique across shards because each shard generates only ids containing its own number. The bits must name a logical shard, not a host, because logical shards move between hosts.
11 — During a Redis Cluster resharding a client receives -ASK 8 192.0.2.12:6379. What must it do, and how is that different from -MOVED? Good to know
Answer
Answer: Send ASKING followed by the command to node B, once, without changing its slot map: the slot is migrating and this key is already on B. -MOVED means the slot now belongs to another node permanently; the client updates its map.
12 — Your Laravel app saves an Order with tenant_id while that tenant is being moved. What happens with the code in this chapter, and why is that the desired behaviour? Important
Answer
Answer: The saving listener asks the resolver for a write connection; the directory status is moving, so TenantMoving is thrown and the request is retried after the cutover. Accepting the write on the old shard during the final catch-up could lose it after the flip.
Glossary
| Term | Meaning |
|---|---|
| Sharding | Splitting one dataset across several databases (shards), each holding a subset of rows |
| Partition | A subset of the data; in many products also the unit of placement and movement |
| Shard | A physical database (or replica set) holding one or more partitions |
| Partition key | The field whose value decides a row's partition |
| Shard key | MongoDB's name for the partition key |
| Distribution column | Citus's name for the partition key |
| Range partitioning | Placement by sorted key ranges |
| Hash partitioning | Placement by a hash of the key |
| Fixed partitions | A constant number of hashed partitions mapped to hosts by a table |
| Logical shard | A fixed partition implemented as a schema or database object (Notion, Instagram) |
| Physical shard | The host or database that holds logical shards |
| Dynamic splitting | Partitions split when they grow (MongoDB chunks, HBase regions) |
| Consistent hashing | Keys and nodes on a hash ring; a key belongs to the next node clockwise |
| Virtual node (vnode) | One of many ring positions owned by a physical node |
| Directory-based sharding | Placement by an explicit lookup table |
| Lookup service | The component or table that answers "which shard holds key x" |
| Composite key | A key of several fields; routing usually uses the first |
| Co-location | Related tables share the partition key so related rows share a shard |
| Colo | Figma's group of co-located tables with one sharding key |
| Reference table | A small table copied to every shard (Citus) |
| Aggregate per shard | DDD rule: one aggregate's data on one shard, so its invariants stay transactional |
| Geo sharding | Placement by region |
| Zone sharding | MongoDB pinning of key ranges to shards (for example by region) |
| Cardinality | Number of distinct values of the key |
| Frequency | How often each key value occurs |
| Monotonic key | A key that only increases (timestamps, sequences, ObjectId) |
| Skew | Uneven data or load across partitions |
| Hot partition | A partition receiving disproportionate traffic |
| Hot key | One key responsible for a hot partition |
| Celebrity problem | Hot keys created by a few very popular accounts |
| Whale tenant | A tenant much larger than the rest |
| Write hotspot | All writes landing in one partition, usually from a time-based key |
| Time-based key | A key whose leading part is a timestamp |
| Key salting | Adding a suffix to spread one key over N partitions (write sharding) |
| Bucketing | Adding a coarse component (month, bucket number) to the partition key |
| Adaptive capacity | DynamoDB feature that shifts throughput to hot partitions and isolates hot items |
| Burst capacity | DynamoDB's retained unused capacity (up to 300 s) for spikes |
| Wide partition | A Cassandra partition with very many rows or cells |
| Item collection | DynamoDB items sharing one partition key value |
| Jumbo chunk | A MongoDB chunk too large to split, often one key value |
| Rebalancing | Moving partitions to even out data or load |
| Resharding | Changing the number of shards or the partition key |
| Balancer | MongoDB background process that migrates ranges between shards |
| Chunk migration | MongoDB move of one range (chunk) between shards |
| Slot migration | Redis Cluster move of one hash slot between nodes |
| Hash slot | One of 16384 Redis Cluster partitions |
| Hash tag | The {...} part of a Redis key that alone is hashed |
| MOVED / ASK | Redis Cluster redirections: permanent owner change / one-off during migration |
| Dual write | Writing to old and new stores at once during a migration |
| Backfill | Copying existing data into the new location |
| Catch-up | Applying changes made since the backfill snapshot |
| Dark read | Reading from both old and new stores and comparing results without serving the new one |
| VDiff | Vitess tool that compares source and target data of a workflow |
| Cutover | The moment routing switches to the new location |
| Reverse replication | Replicating from the new owner back to the old to keep a rollback path |
| Topology version | Version number of the partition map, used to reject stale routing |
| Router | The component that sends each request to the right shard |
| vtgate | Vitess's stateless routing proxy |
| Vindex | Vitess function or lookup that maps a column value to a keyspace ID |
| Keyspace ID | Vitess's routing value; shards own ranges of it |
| mongos | MongoDB's query router |
| Coordinator | Citus node that holds metadata and plans distributed queries |
| Scatter-gather | Sending a query to all shards and merging the results |
| Fan-out | The number of shards (or services) one request touches |
| Targeted query | A query routed to one or a few shards using the shard key |
| Broadcast operation | MongoDB's name for a query sent to all shards |
| Local secondary index | An index stored with each partition, covering only its rows |
| Global secondary index (GSI) | An index partitioned by the indexed attribute, across all partitions |
| Denormalisation | Copying data so a query can be answered from one partition |
| Materialised view | A stored, precomputed query result kept up to date from the base data |
| CQRS | Separating the write model from read models built for queries |
| Cross-shard query | A query that needs data from more than one shard |
| Cross-shard transaction | A transaction that writes to more than one shard |
| 2PC | Two-phase commit: prepare on all participants, then commit |
| Saga | A sequence of local transactions with compensating actions |
| Global unique id | An id unique across all shards without coordination per insert |
| Snowflake id | Twitter's 64-bit id: time, machine id, sequence |
| Multi-tenancy | One system serving many customers (tenants) |
| Shard per tenant | Placing one tenant alone on its own shard or database |
| Space-Saving | A bounded-memory algorithm that tracks the most frequent keys |
| Vitess | MySQL sharding system with vtgate, vindexes and resharding workflows |
| Citus | PostgreSQL extension for distributed tables |
| MongoDB sharding | MongoDB's sharded clusters with mongos, config servers and a balancer |
| Redis Cluster | Redis's sharded mode with 16384 hash slots |
| DynamoDB | AWS managed key-value store with hash partitioning |
| Cassandra | Wide-column database with a token ring and vnodes |
References
All URLs returned HTTP 200 when fetched; saved copies are listed in the chapter handoff.
- Notion, Herding elephants: Lessons learned from sharding Postgres at Notion and The Great Re-shard
- Figma, How Figma's databases team lived to tell the scale
- Instagram Engineering, Sharding & IDs at Instagram (archived copy; the live site did not answer)
- Pinterest Engineering, Sharding Pinterest: How we scaled our MySQL fleet (archived copy; Medium refuses automated clients)
- Twitter, Snowflake (2010 README)
- Amazon DynamoDB, Partition key design, Burst and adaptive capacity, Write sharding, Partitions and data distribution, Global secondary indexes, Local secondary indexes, Index best practices
- MongoDB, Shard keys, Choose a shard key, Balancer, Data partitioning with chunks, mongos, Reshard a collection, Hashed sharding, Ranged sharding
- Vitess, Sharding, Vindexes, Resharding user guide, Reshard reference, VTGate, Atomic distributed transactions
- Citus, Choosing the distribution column, Creating and modifying distributed objects, Cluster management, Configuration reference
- Redis, Redis Cluster specification
- Apache Cassandra, Data modelling introduction, RDBMS design, Evaluating and refining data models, Dynamo architecture, cassandra.yaml reference
- PostgreSQL, PREPARE TRANSACTION
- Karger et al., Consistent Hashing and Random Trees (1997)
- Martin Kleppmann, Designing Data-Intensive Applications
- Laravel 13, Database: Getting Started, Eloquent, Concurrency