Learn

PATTERN · ORIGINAL

Partitioning and ordering: choosing keys you can live with

How a partition key decides where data lives, what stays in order and what melts under load: hash vs range, hot partitions, rebalancing with consistent hashing or fixed partitions, and per-entity sequence numbers.

Once data or traffic outgrows one machine, you split it, and the split is decided by a partition key. That one choice settles three things at once: which machine stores a record, which operations can happen on one machine (transactions, ordering, joins), and which operations must fan out to every machine. Choose well and the system scales by adding boxes. Choose badly and one box runs hot while the rest idle, or a simple query becomes a scatter-gather across 200 nodes.

What a good key looks like

Test a candidate key against the access patterns, not the data model. Ask three questions:

  1. Do the hot queries hit one partition? In a chat app, "load the last 50 messages of conversation X" is the dominant read. Keying messages by conversation ID answers it from one partition. Keying by message ID scatters it.
  2. Is load spread evenly? You want high cardinality (millions of distinct values, not 50 countries) and no single value carrying a large share of traffic.
  3. What must happen atomically or in order? Anything that must be ordered or transactional should share a key. In a wire transfer API, the balance updates for one account need ordering, so the account ID is a natural key. A transfer between two accounts then crosses partitions, which is a design decision you should name, not discover.

These pull against each other. A key fine enough to spread load (user ID) may split things you wanted together (a group conversation). Say which pattern you optimized and what the others cost.

Hash or range

Hash partitioning runs the key through a hash and assigns ranges of hash values to partitions. Load spreads evenly, and point lookups go straight to one partition, but range scans across keys are gone: users 1000 to 2000 live everywhere.

Range partitioning keeps keys sorted and gives each partition a contiguous slice. Scans are cheap, which is why time-series and ordered indexes like it. The classic failure is a monotonically increasing key such as a timestamp or an auto-increment ID: every new write lands in the last range, so one partition takes all the writes. The common fix is a compound key, for example (sensor_id, time), which spreads writes by sensor and keeps each sensor's history in order.

Hot partitions

Even with a good key, real traffic is skewed. Put numbers on it. Suppose 1 million writes per second across 200 partitions, and each partition handles 10,000 per second comfortably. Average load is 5,000, so you have headroom. Now one key (a celebrity, a trending stock ticker in a price feed) takes 3% of traffic: 30,000 writes per second on one partition. No amount of adding nodes helps, because a key cannot be split by the placement scheme alone.

Your options, roughly in order of cost:

  • Absorb reads with caching. If the heat is reads, replicate or cache the hot key. Caching and hot keys covers this side.
  • Batch writes before they reach the partition. Aggregate increments for a second and send one write. See counting at scale.
  • Salt the key. Write to key#0 through key#9 chosen at random, and read all ten and merge. Write load drops tenfold; every read now costs ten lookups, and any ordering across the salted pieces is lost.
  • Give the key its own partition or its own pipeline, if a handful of keys are known in advance.

Rebalancing without moving everything

Partitions must move when nodes join or leave. The naive scheme, hash(key) mod N, is a trap: changing N from 10 to 11 remaps about 10 of every 11 keys. At 20 TB that is a migration, not a scale-up.

Consistent hashing and virtual nodes

Place nodes at points on a hash ring and give each key to the next node clockwise. Adding a node takes over only the arc before it, so about 1/N of keys move. With one point per node, arcs vary wildly in size and a new node relieves only one neighbor. Virtual nodes fix both: each physical node owns many points (say 100 to 256), so load averages out, a new node takes a little from everyone, and a bigger machine can simply own more points. The Dynamo case study shows a production system that evolved its token scheme for exactly these reasons.

Fixed partitions mapped to nodes

The alternative many systems prefer operationally: create a fixed number of partitions up front, well above the node count (for example 4,096 partitions for 40 nodes), and keep a small map from partition to node. Keys never change partition; only partitions move, as whole units. Moving a partition is a file copy plus a map update, and the map is small enough to store in a coordination service and cache everywhere. The cost is choosing the count early. Too few and you cannot spread past that many nodes; too many and per-partition overhead adds up. Splitting partitions later is possible but is a real project.

OptionWins whenCosts
hash mod NNode count never changes, or data is a rebuildable cache.Almost every key moves on resize.
Consistent hashing with virtual nodesMembership changes often and you want no central map.More complex routing and repair; ranges shift on every join, so per-range state (indexes, checksums) must be rebuilt.
Fixed partitions plus a partition mapYou want predictable moves, simple backups per partition and an explicit control plane.Partition count is a long-term commitment; the map needs a reliable owner.
Range partitions with splitsRange scans matter and key distribution is unknown in advance.Sequential keys create a hot tail; split and merge logic needs care.

The partition map is a classic control-plane job. If you are sketching the key-value store, decide early who owns it.

Ordering: per partition is cheap, global is expensive

Inside one partition, ordering is nearly free. One leader appends records and assigns increasing offsets; consumers read in offset order. That is the core of a distributed log.

FIG. 1ORIGINAL SKETCH
record + key12key = conv 4222in offset order333ProducersKey routerhash(key) → pPartition 0Partition 1Partition 2Consumer AConsumer Border per key
Producers route each record by hash of its key, so all records for one key land in one partition and are consumed in order by a single consumer.

Global ordering, a single total order across everything, means every write passes through one sequencer or one consensus group. Throughput is capped by that single point, and if writers are in several regions, every write pays a cross-region round trip (often 60 to 150 ms). Ask whether the product needs it. Usually the real requirement is narrower:

  • Messages in one conversation appear in the same order for everyone.
  • Updates to one account are applied in order.
  • Price ticks for one symbol never go backwards.

Each of these is ordering per entity, which per-partition ordering gives you if the entity ID is the key. Messages in two different conversations have no meaningful order relative to each other, and paying for one is waste.

How per-partition order quietly breaks

  • Changing the partition count remaps keys. Records for conversation 42 written before the change sit in partition 1; new ones go to partition 5. A consumer can see new before old. Pick a generous count up front, or drain and cut over deliberately.
  • Producer retries. If record 1 times out and is retried after record 2 succeeded, the log holds 2 then 1. Limit in-flight requests per key, or use idempotent producers with sequence checks.
  • Parallelism inside a consumer. A consumer that hands records from one partition to a thread pool has thrown the order away. Parallelize across keys, not within one.
  • Consumer rebalances. When partition ownership moves between consumers, the old owner may still be processing. Commit offsets after processing, and make handlers idempotent, because some records will be seen twice. See queues, retries and dead letters.

A message queue with per-message acknowledgement and redelivery makes ordering harder still: a message that fails and is redelivered lands behind later ones. If order matters, you need per-key serial processing on top.

Sequence numbers per entity

Rather than trusting the transport, stamp order into the data. Give each entity its own counter: conversation 42 has messages 1, 2, 3 and so on. Assign the number where writes for that entity are already serialized, either the partition leader or a conditional write such as insert seq = last_seq + 1 only if last_seq is still 41.

Per-entity sequence numbers pay for themselves several times:

  • Clients sort by sequence, not arrival, so network reordering stops mattering.
  • A client that sees 41 then 43 knows it missed 42 and can fetch it.
  • A duplicate 42 is recognized and dropped, which makes delivery idempotent.
  • Sync becomes "give me everything after 41", a cheap range read on (conversation_id, seq).

Do not use wall-clock timestamps for this. Clocks on different servers drift by milliseconds or more, so two messages a few milliseconds apart can be stamped in the wrong order. Timestamps are fine for display; order comes from the sequence. Consistency and idempotency covers the retry side of this.

TAKE THIS TO YOUR NEXT SKETCH

  • Choose the partition key from the dominant queries and from what must be ordered or atomic, then name what crosses partitions.
  • Estimate the hottest key, not just the average. A key carrying a few percent of traffic can exceed one partition no matter how many nodes you add.
  • Avoid hash mod N. Use consistent hashing with virtual nodes, or a fixed partition count with an explicit map, and say which.
  • Ask for ordering per entity, not global ordering; key by that entity so one partition owns its order.
  • Stamp per-entity sequence numbers so clients can sort, detect gaps and drop duplicates regardless of transport behavior.

PRACTICE WITH THIS

Now sketch one.

OFF-SITE READING · NOT WRITTEN BY US

Further reading

Next: Queues, retries and dead letters