Sub topic 8
Ordering, keys and partitions
This chapter assumes you know what a broker, a topic and a consumer are, and that delivery is usually at-least-once. It covers how to keep events in the right order when you also want to process them in parallel.
Why ordering is hard
A single queue read by a single consumer keeps order. That setup is slow, because one consumer is the throughput limit. To scale, brokers split a topic into partitions. A partition is an append-only log that preserves the order of the events written to it. Several consumers can read different partitions at the same time.
The catch is that order is only guaranteed inside one partition. Across partitions, the broker makes no promise.
Keys decide the partition
A key is a value you attach to an event, such as an account ID. The producer hashes the key and uses the result to choose a partition. Events with the same key always go to the same partition, so they stay in order.
Within a consumer group, each partition is assigned to one consumer at a time. That is what protects per-key order while still allowing parallelism.
A worked example
This code mimics key-based routing. It shows that events for the same account land in the same partition, in the order they were sent.
import zlib
NUM_PARTITIONS = 3
partitions = [[] for _ in range(NUM_PARTITIONS)]
def publish(key, event):
index = zlib.crc32(key.encode()) % NUM_PARTITIONS
partitions[index].append((key, event))
publish("acct-1", "deposit 100")
publish("acct-2", "deposit 50")
publish("acct-1", "withdraw 30")
publish("acct-1", "close account")
for i, log in enumerate(partitions):
print(i, log)All three acct-1 events end up in one list, in publish order. A consumer of that partition sees "deposit", then "withdraw", then "close". Without a key, the withdrawal could be processed before the deposit and fail.
Choosing a key
Pick the key that matches the entity whose events must stay ordered. Typical choices are an order ID, an account ID or a device ID.
- Too coarse a key (for example, a country code) puts most traffic on a few partitions. This creates a hot partition that one consumer cannot keep up with.
- Too fine a key gives good spread but gives up ordering you may need.
- You do not need global order. You need order per entity, and that is much cheaper.
Where ordering still breaks
- Retries. If event 1 fails and is retried while event 2 succeeds, the order is lost. Either block the partition until event 1 succeeds, or make handlers tolerant of out-of-order input.
- Changing partition count. Adding partitions changes the hash result. The same key may move to a new partition, so old and new events for it can be read in parallel.
- Multiple producers. Order is the order in which events reach the broker, not the order they happened. Two producers writing for the same key can interleave unpredictably.
- Parallelism inside a consumer. If a consumer hands events from one partition to a thread pool, it undoes the guarantee.
Summary of trade-offs
| Choice | Benefit | Cost |
|---|---|---|
| More partitions | More parallel consumers | Weaker ordering scope, repartitioning risk |
| Fewer partitions | Simpler ordering | Lower throughput |
| Key per entity | Per-entity order, good spread | Hot keys can overload one partition |
Exercise
An order service publishes "order.placed", "order.paid" and "order.shipped" events to a topic with six partitions. Consumers sometimes see "shipped" before "paid". What is the likely cause, and what is the fix?
Show answer
The events were probably published without a key, or with different keys, so they were spread across partitions that have no mutual order. Use the order ID as the key for all three event types so they go to the same partition. Adding a version number lets consumers detect any remaining stale events.
Exercise
Why can increasing a topic's partition count break ordering for existing keys?
Show answer
The partition is chosen by hashing the key modulo the partition count. Changing the count changes the result, so a key may map to a new partition while older events for it are still unread in the old one. Consumers can then process new and old events in parallel.