Ordering and partition keys
Get the order you actually need, per entity, without giving up parallelism.
15 min readGlobal order does not scale
A single, totally ordered stream must be consumed by a single consumer, so its throughput is capped by one machine. Fortunately almost no system needs global order. A bank account needs its deposits and withdrawals in order; it does not care how they interleave with someone else's account. A chat room needs its messages in order, not ordered against every other room. The real requirement is almost always order per entity, and that can be partitioned.
Partition keys
Log brokers assign each message to a partition by hashing its key: partition = hash(key) mod N. Choose the key as the entity whose events must stay ordered: account ID, order ID, chat room ID. All events for that key land in one partition, in order. Within a consumer group each partition is read by exactly one consumer, so the partition count is your maximum parallelism. SQS FIFO does the same with message group IDs.
Choosing the partition count
Size for future peak, because changing N later remaps keys to different partitions and breaks ordering during the transition.
- Partitions needed is at least peak messages per second divided by what one consumer handles: 100 000 / 5 000 = 20, so choose 32 or 64
- Watch for skew: one celebrity user or one huge tenant can make its partition hot while the others idle
- Split hot keys deliberately (key + bucket number) only if that entity can tolerate partial ordering
Things that quietly break order
Partitioning preserves order in the log, but the pipeline around it can still scramble it. A failed message retried later lands after newer ones. A consumer that processes a batch on parallel threads finishes out of order. A producer retrying a send can write message 2 before message 1 unless producer idempotence is enabled. Defend at the consumer: carry a version or sequence number in each event and ignore updates older than what you have stored.
Key takeaways
- You almost always need order per entity, not global order
- The partition key is the entity whose events must stay ordered; partitions cap parallelism
- Size partitions for future peak because repartitioning reshuffles keys
- Use version numbers so consumers can reject stale or reordered events
Sign in to track lessons and earn badges.