Skip to content

Partitioning: Consistent Hashing and Hot Shards

14 min reading

Choose key locality and placement from actual demand; separate copying state from transferring authority.

Page details

Distribute the data · Lesson 08

Published · Sources · 14 min reading · Last edited:

Know first: Numbers Every Engineer Should Know; Reading Architecture Diagrams.

Editorial correction:

Earlier design notes used unsupported universal performance or reliability claims. This revision explains conditional mechanisms and explicitly hypothetical examples; no author-run benchmark or production incident is asserted.

More
20px

Northwind: Partitioning: consistent hashing, hot keys and ownership

Outcome. After this lesson, you can move a hot product without creating two owners.

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.

One tenant outgrows the shared store

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.

The previous lesson specified what readers may observe. Now the design must preserve that contract while locating records, processing cross-partition operations and moving ownership. A routing map is part of correctness, not merely a performance optimization.

Equal record counts hide unequal demand

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.

Routing connects a key to an authority

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 separate routing from physical placementA request carries a tenant key. A versioned routing map selects its logical partition and current owner. Migration transfers state and changes authority before obsolete ownership is retired.Tenant keyVersioned routing mapPartition → ownerCurrent ownerMigration targetCopying bytes does not itself transfer write authority.

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.

Adding D takes one interval from CA clockwise hash ring has owners A at 10, B at 40 and C at 75. Inserting D at 60 transfers positions greater than 40 through 60 from C to D. Hash 55 changes owner, while the other illustrated keys retain their owner.0A:10B:40C:75D:60, newClockwiseownershipBefore: hash 55 → CAfter: hash 55 → DChanged arc: (40,60]Other arcs keep owners
The token values are chosen. The highlighted arc describes changed ownership, not a measured load balance.

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.

Move a hot product without creating two owners

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.

Calculate the busiest owner

Hypothetical scenario. Choose a workload of 1,000 requests per second. One tenant contributes 400; the other tenants contribute 600. With four tenant-keyed shards, assume the remaining demand is evenly divided for this example: 600 ÷ 4 = 150 requests per second per shard.

The shard containing the popular tenant therefore receives 400 + 150 = 550 requests per second. Each other shard receives 150. The mean is 1,000 ÷ 4 = 250, but no shard sees that mean in this allocation. Against a chosen planning limit of 300 requests per second per node, the hot owner exceeds the limit by 550 − 300 = 250 requests per second.

Increasing to eight owners under the same tenant placement gives 600 ÷ 8 = 75 background requests per owner. The popular tenant's owner still receives 400 + 75 = 475, above the same chosen limit. More nodes reduce the background but cannot distribute that tenant's indivisible demand.

Suppose instead that a selected migration moves 120 GB of existing data and receives a reserved transfer budget of 20 MB per second. Using decimal units, 120 GB = 120,000 MB, so the payload-only lower bound is 120,000 ÷ 20 = 6,000 seconds, or 100 minutes. If writes add a chosen 5 MB per second of change data, the transfer budget's catch-up surplus is 20 − 5 = 15 MB per second; a 3,000 MB remaining change backlog needs 3,000 ÷ 15 = 200 seconds under those constant rates.

These are planning examples, not measured capacities. Protocol overhead, competing traffic, retransmission, verification and changes in demand can extend the migration. If the change rate meets or exceeds the available transfer rate, this catch-up model never reaches zero.

In the wild: Move a hot product without creating two owners

The primary reference establishes this concrete distinction: postgreSQL table partitioning has concrete bounds, pruning and maintenance semantics, distinct from cross-node sharding.

Locality and spreading pull in different directions

A tenant-keyed design can isolate operational ownership while still sharing hardware. An exceptionally large tenant may need dedicated placement or a second partitioning level. Subdividing it changes query fan-out and transaction boundaries, so it should follow evidence about the costly operations.

Range boundaries make ordered scans natural but can concentrate monotonically arriving keys at one end. Hashing can spread many distinct arrivals, but one popular key remains one popular key. Consistent hashing changes the assignment structure when membership changes; it does not guarantee uniform workload or make movement free.

Cross-partition queries require a declared combination rule. A global ordered page needs stable ordering and pagination semantics, not simply a concatenation of whichever owners answer first. Likewise, uniqueness enforced independently on each owner does not establish a global uniqueness invariant.

The old owner keeps accepting writes

Hypothetical scenario. A migration copies a seller's records to a new owner. The router switches to the new location, but an old client keeps a cached route and the previous owner continues accepting changes. Both locations now contain plausible updates. Completing the copy did not make the cutover safe.

Design an explicit transition: establish a snapshot and change position, catch up changes, transfer authority under an agreed configuration, reject or redirect obsolete writes, and retain recovery evidence before removing the old copy. The exact protocol depends on the database and its transaction guarantees.

A routing version can help detect stale requests, but only if owners enforce it and configuration changes are coordinated. Deleting the previous copy immediately may remove the evidence needed to reconcile an interrupted cutover. Recovery and rollback need their own state transitions.

More partitions do not fix every bottleneck

“Hashing balances the workload.” It can spread distinct keys under stated assumptions. Key popularity and operation cost still determine demand.

“Partition pruning is an index.” Pruning can exclude irrelevant partitions using bounds and predicates; indexes then address access inside the remaining partitions. They solve related but distinct parts of the query.

“Moving a partition is an administrative copy.” It changes state ownership while requests continue. Correctness depends on routing, authority, concurrent changes and failure recovery.

Partition after identifying the resource boundary

Partition when a specific access, capacity, retention or isolation requirement benefits from it. Table partitions can help lifecycle operations even without separate servers. Distributed shards can spread resources when the chosen key actually divides the constrained work.

Delay distributed ownership when a simpler indexed store meets the requirement with adequate headroom and recovery behavior. Extra owners create cross-partition coordination, metadata and operational obligations. They are a response to a constraint, not evidence that a design is advanced.

The next lesson adds replicas to owners. Keep the distinction clear: partitioning decides which subset an owner manages; replication decides which copies can acknowledge or serve that subset and how another copy becomes authoritative after failure.

Limits of this model

The hot-key count assumes a single authoritative owner. Replication, caching or split representations can alter the workload, but each changes different semantics and operational costs. Local PostgreSQL partitioning is not a cross-node routing or distributed-transaction protocol.

Check yourself: defend the placement

Eight shards replace four, but one tenant still exceeds one node's planning limit. What assumption failed?

The workload did not divide with the tenant key. Examine whether the expensive work can be subdivided, served through bounded derived views or placed on a suitable owner. More empty capacity elsewhere does not relieve an indivisible hot key.

A query touches every partition. Does adding partitions establish a latency improvement?

No. It can add fan-out and combination work. Inspect predicates, required ordering, concurrency and the resource actually constrained; neither equal row counts nor more partitions establishes a faster response.

The destination has the complete snapshot. Can the old owner be deleted?

Not from that fact alone. Account for changes after the snapshot, transfer write authority, reject stale routes and establish recovery evidence. Data copying and safe cutover are separate requirements.

Northwind decision log

Measure hot partitions as well as total load.
Choose a split key that can divide the observed workload.
Plan key movement before reshaping the partition map.

Go deeper: Move a hot product without creating two owners

Related blog: Failover capacity when one workload is hot.