Part 2 · Blueprint 09
Database Sharding & Consistent Hashing
15 min reading · Sources · Editorial review pending
More shards do not spread one hot key or remove cross-shard coordination.
Page details
Published date · Last edited:
Draft edition. Editorial review and supplementary reading recommendations are still being completed.
Format: Architecture walkthrough. Prerequisites: the beginner bootcamp. Chapter prerequisites: SQL vs. NoSQL vs. NewSQL Storage Engines, Indexes & Storage Engines: B-Trees vs. LSM Trees.
Sixty-second mental model
Problem: More shards do not spread one hot key or remove cross-shard coordination.
Use: Move ownership through a verified migration rather than a routing guess.
Design boundary: Place records and queries across shards using an explicit key. Good partitioning keeps dominant operations local while bounding hot partitions. Adding nodes does not distribute one indivisible hot key.
Layer 1 · Intuition
Hypothetical scenario: Northwind is designing sharding. Maya represents product requirements, Dev implementation and Priya reliability. The team must agree what one key means and which component owns the placement directory.
Think of branches owning different customer files. Separate the requester from placement directory, then identify the retained evidence needed after failure.
- Authority
- The entitled state owner.
- Invariant
- A rule preserved across concurrency and failures.
- Consistent hashing
- A placement family designed to limit key reassignment when membership changes. Analogy: A circular directory where a new desk takes a neighboring slice.
- Partition key
- A value used to determine placement or grouping of data. Analogy: The sorting code deciding which branch receives a record.
- Shard
- A partition of a dataset assigned to a storage owner or group. Analogy: One branch responsible for a subset of customer files.
- Sharding
- Partitioning data among owners using a stated placement scheme. Analogy: Dividing customer files among branches.
- Virtual node
- An additional logical ownership position assigned to a physical node in a placement scheme. Analogy: One office operating several labeled desks on the directory.
Architecture and worked reasoning
Design boundary: Place records and queries across shards using an explicit key. Good partitioning keeps dominant operations local while bounding hot partitions. Adding nodes does not distribute one indivisible hot key.
Responsibilities on the request path
Workload and limiting resource
Hypothetical total traffic is 12,000 writes/s over 12 shards, averaging 1,000 writes/s each. If one tenant produces 40%, its key range receives 4,800 writes/s despite the average. A selected 1,500 writes/s shard budget is exceeded by that tenant alone. Split its workload by a meaningful subkey or change its work/admission policy.
Keep the units attached to each intermediate result. The assumptions above describe a hypothetical exercise, not observed vendor capacity. A real capacity decision also needs a measured service curve, skew, recovery traffic and an explicit admission policy for overload.
Mutation or publication path
- Choose routing from the key and map version.
- Send mutation to its current owner.
- Move a range with a bounded handoff and duplicate/missing-write protection.
Observation and recovery path
- Resolve the current shard map.
- Issue local queries when possible.
- Merge bounded cross-shard results with stable pagination.
Failure that changes the decision
Hypothetical scenario: A client retains an old map during migration and writes to the previous owner. Redirect or fence stale routing; copying bytes without ownership transfer is insufficient.
Attempt this decision before reading the explanation
Would doubling the shard count fix a single hot account?
Only if that account can be split across the new shards without violating its transaction/access requirements. Hashing one unchanged account key still maps it to one owner.
Supporting mechanism analysis
Hypothetical scenario: Northwind. Maya represents product, Dev implementation and Priya reliability. The following workflow develops the underlying mechanism.
Hypothetical scenario. At Northwind, One promoted product receives more requests than all other catalogue keys.
In short. Measure hot partitions as well as total load. Choose a split key that can divide the observed workload.
Hypothetical scenario. A catalogue service stores many sellers in one database. Most queries request the items belonging to one seller, but a popular seller accounts for a disproportionate share of requests. Engineers propose adding shards. Before choosing a hash function, they must identify which resource is constrained and whether the expensive work can actually be divided.
Partitioning divides a logical dataset into subsets. Sharding commonly places those subsets on different independently operated storage nodes. A partitioned table inside one database does not automatically provide that distribution. Replication makes additional copies; it answers a different question from splitting ownership.
Dividing rows evenly does not divide their access rates, sizes or computational costs evenly. A single frequently updated record may dominate a shard that otherwise contains almost no data. Adding more partitions does not split that record's serialized updates unless the data model changes.
Choosing tenant identity as the key keeps a tenant's related operations together and may simplify deletion or placement. It also concentrates a large tenant. Choosing item identity spreads items but can turn a seller-wide listing or transaction into work across many owners. Neither choice removes the original access requirements.
Start with the actual predicates, ordering, update boundaries and isolation needs. Record which operations identify one owner, which require a small known set and which scatter across the whole dataset. A key that makes writes convenient can make the dominant read prohibitively expensive.
Range partitioning assigns adjacent keys to one partition and supports range-oriented placement. Hash partitioning transforms keys before assignment, often spreading distinct keys while losing useful adjacency. A directory can map a tenant or logical partition to an owner explicitly. Each approach has metadata, lookup and migration consequences.
Logical partitions can be more numerous than physical nodes, allowing selected subsets to move without changing every key's assignment. That indirection costs metadata and operational machinery. Many small partitions also increase scheduling, recovery and per-partition overhead.
PostgreSQL 17's table-partitioning documentation explains range, list and hash partitioning, pruning and maintenance within its database model. Use those concrete semantics carefully: local table partitioning is not a promise of automatic cross-node rebalancing or distributed transactions.
Hypothetical scenario. Put hash positions on a ring numbered 0 through 99. Place owner A at 10, B at 40 and C at 75. Route a key clockwise to the first owner at or after its hash, wrapping past 99 to 0. A owns (75,10], B owns (10,40] and C owns (40,75]. The parentheses exclude the starting point and the bracket includes the ending point.
Keys at 5, 20, 55, 65 and 90 therefore route to A, B, C, C and A. Add D at 60. Only the interval (40,60] changes owner: key 55 moves from C to D; the other chosen keys stay where they were. The changed arc contains 60 − 40 = 20 of the 100 integer positions, so uniform placement would assign an expected 20% of keys to that arc. The five selected keys are an illustration, not a sample proving an actual distribution.
Contrast a direct modulo rule on keys 0 through 11. Mapping key mod 3 to A/B/C and then key mod 4 to A/B/C/D keeps keys 0, 1 and 2 on their old owners and changes keys 3 through 11. That is 12 − 3 = 9 of the 12 assignments: 9 ÷ 12 = 75%. This chosen comparison explains why changing a divisor can move many keys; it is not a universal movement percentage. The Dynamo paper, Section 4.2 describes ring placement and virtual nodes.
A virtual node is another token owned by a physical machine. Several tokens can spread one machine's ownership across the ring and make reassignment more granular. The actual key distribution and capacity still matter. A single hot conversation has one hash; adding virtual nodes does not divide its ordered writes. The chat case separates that write boundary from recipient fan-out.
Finally, a new routing map is not a completed migration. Copy the chosen interval, replay changes, establish the new write authority and reject obsolete routing versions before retiring the old copy. Keep recovery evidence for interrupted movement. The ring selects an owner; the migration protocol makes the change safe.
Northwind's promotion can concentrate requests on one product even when product records are evenly distributed. A partition map assigns authority over keys. Consistent hashing is one way to reduce how placement changes when membership changes; it does not divide one indivisible hot key into independent operations. Virtual nodes improve placement flexibility but do not remove the need to measure actual request costs.
For a hypothetical workload of ten thousand requests per second across ten partitions, an even distribution would average one thousand per partition. Suppose one key contributes four thousand requests per second and belongs to a single owner. That owner receives at least four thousand before its other keys are counted. The remaining nine partitions can be mostly idle while the hot owner saturates. Adding another empty partition does not establish relief for that key.
Possible responses change different parts of the contract. A read-only cache can reduce repeated reads. A finer key can divide work only if the application can tolerate the resulting coordination or aggregation. Isolating a tenant changes placement, while changing a hot counter into independent partial counters changes its representation and read semantics. Name the required invariant before choosing which form of spreading is valid.
Moving ownership requires more than copying bytes. Take a snapshot, account for subsequent changes, and define a cutover point that prevents stale routes from continuing to write through the old owner. A routing generation helps identify obsolete requests only when the receiver enforces it. PostgreSQL table partitioning illustrates local partition boundaries and pruning; cross-machine sharding adds routing, authority transfer and partial-failure responsibilities that a local partitioned table does not provide.
Layer 3 · Internals
Trade-offs and limits
| Approach | Provides | Requires |
|---|---|---|
| Range placement | Supports locality and selected range scans. | Uneven keys and growing ranges can concentrate traffic. |
| Hash placement | Can spread independent keys across owners. | Ordered scans and membership changes require additional routing and migration work. |
Recovery decision
Hypothetical scenario: A client retains an old map during migration and writes to the previous owner. Redirect or fence stale routing; copying bytes without ownership transfer is insufficient.
Only if that account can be split across the new shards without violating its transaction/access requirements. Hashing one unchanged account key still maps it to one owner.
Write your design before revealing the review
Would doubling the shard count fix a single hot account?
Drafts and self-review are stored only in this browser. They are separate from reading completion.
Compare your decision
Only if that account can be split across the new shards without violating its transaction/access requirements. Hashing one unchanged account key still maps it to one owner.
A client retains an old map during migration and writes to the previous owner. Redirect or fence stale routing; copying bytes without ownership transfer is insufficient.
Check your understanding
Would doubling the shard count fix a single hot account?
Only if that account can be split across the new shards without violating its transaction/access requirements. Hashing one unchanged account key still maps it to one owner.
How would you recover from this failure: A client retains an old map during migration and writes to the previous owner. Redirect or fence stale routing; copying bytes without ownership transfer is insufficient.
Start with the exact boundary that failed. Choose routing from the key and map version. Send mutation to its current owner. Move a range with a bounded handoff and duplicate/missing-write protection. Then recover evidence through the observation path: Resolve the current shard map. Issue local queries when possible. Merge bounded cross-shard results with stable pagination. Preserve the distinction between a confirmed state change and an unavailable response.
Which assumption in the worked calculation would a burst or concentrated tenant invalidate first?
Hypothetical total traffic is 12,000 writes/s over 12 shards, averaging 1,000 writes/s each. If one tenant produces 40%, its key range receives 4,800 writes/s despite the average. A selected 1,500 writes/s shard budget is exceeded by that tenant alone. Split its workload by a meaningful subkey or change its work/admission policy. Recompute the affected resource rather than multiplying unrelated storage and network budgets by the same factor. Place records and queries across shards using an explicit key. Good partitioning keeps dominant operations local while bounding hot partitions. Adding nodes does not distribute one indivisible hot key.
Which component in this topology could be removed from a smaller first deployment?
Router, Shard map, Shard owners, Migration copier name responsibilities, not a requirement for separate processes. Co-locate responsibilities when their transaction, trust and capacity boundaries permit it. Choose routing from the key and map version.
What evidence must a caller have before relying on the observation path?
Resolve the current shard map. Issue local queries when possible. Merge bounded cross-shard results with stable pagination. Only if that account can be split across the new shards without violating its transaction/access requirements. Hashing one unchanged account key still maps it to one owner.
45-minute interview rubric
- 00–05: scope key and placement directory.
- 05–12: identify the limiting resource and derive the domain workload above, retaining units and assumptions.
- 12–28: draw placement directory, numbered writes and reads.
- 28–40: challenge recovery: Move ownership through a verified migration rather than a routing guess.
- 40–45: defend partition_key placement, observations and remaining assumptions.
Go deeper
- Redis cluster specification | Docs · Primary document · redis.io. Move ownership through a verified migration rather than a routing guess. Verified 2026-10-26.
- Dynamo: Amazon’s Highly Available Key-value Store · Primary document · cdn.amazon.science. Move ownership through a verified migration rather than a routing guess. Verified 2026-10-26.
- PostgreSQL: Documentation: 17: 5.12. Table Partitioning · Primary document · www.postgresql.org. Move ownership through a verified migration rather than a routing guess. Verified 2026-10-26.
Decision log
Move ownership through a verified migration rather than a routing guess.
Preserve key identity and placement directory ownership.
Revisit changed workload, observations or recovery objectives.