Sub topic 8
Ordering, keys and partitions
What you need first
This chapter assumes you know the following:
- What a producer, a consumer and a broker are.
- The difference between a topic (fan-out) and a work queue (competing consumers).
- Why delivery is usually at-least-once, so consumers must tolerate duplicates.
Some examples use Python. Partitioned logs such as Kafka, Kinesis and Pulsar use the same ideas under different names.
Why ordering is a problem
An order moves through placed, paid and shipped. A consumer that sees shipped before paid may reject the event, or it may store the wrong final state.
On a single queue with a single consumer, order is easy: events leave in the order they arrived. That setup also limits throughput to one consumer. To scale, brokers split a stream into several independent pieces and process them in parallel. Once you do that, a single global order no longer exists.
The practical goal is therefore narrower: keep events in order where it matters, and accept no ordering elsewhere. Events about the same order must stay in sequence. Events about different orders can be handled in any sequence.
Partitions: order within a slice
A partition is one ordered, append-only sequence of events inside a topic. A topic with six partitions is six separate logs.
- Within one partition, the broker keeps events in the order they were written, and consumers read them in that order.
- Across partitions, there is no ordering guarantee. Partition 0 may be far ahead of partition 1.
This is the central trade-off. More partitions allow more parallel consumers, and ordering is guaranteed only inside each partition.
Keys choose the partition
A producer attaches a key to each event, usually the ID of the entity the event is about, such as orderId. The producer's partitioner hashes the key and takes the result modulo the number of partitions. All events with the same key land in the same partition, so they stay in order relative to each other.
import zlib
NUM_PARTITIONS = 3
def partition_for(key: str) -> int:
# Use a stable hash. Python's built-in hash() for strings changes
# between processes, which would break key-to-partition mapping.
return zlib.crc32(key.encode("utf-8")) % NUM_PARTITIONS
partitions = {i: [] for i in range(NUM_PARTITIONS)}
events = [
("order-1", "placed"),
("order-2", "placed"),
("order-1", "paid"),
("order-2", "cancelled"),
("order-1", "shipped"),
]
for key, kind in events:
partitions[partition_for(key)].append((key, kind))
for number, log in partitions.items():
print(number, log)Run this and look at the output. All order-1 events appear in one partition, in the order placed, paid, shipped. The order-2 events are in one partition too, possibly the same one. Their relative position to order-1 events does not matter.
Without a key, most brokers spread events across partitions round-robin or at random. That balances load well, but two events about the same order can then be read in either order.
Consumer groups and parallelism
Consumers that share a job form a consumer group. The broker assigns each partition to exactly one consumer in the group at a time. That rule preserves per-partition order: no two consumers ever process the same partition concurrently.
Two consequences follow:
- The number of partitions caps useful parallelism. With three partitions, a fourth consumer in the group sits idle.
- One consumer may own several partitions. It then interleaves them, and order holds only within each partition.
What can still go wrong
Keyed partitioning gives you ordering per key, but several failure modes remain.
- Retries inside the producer. If a producer sends event 1, event 2, and event 1 fails then succeeds on retry, the broker may store 2 before 1. Many brokers offer an idempotent or ordered producer setting, or a limit of one in-flight request per connection. Check your broker's documentation.
- Multiple producers for the same key. Two services publishing events about the same order have no shared sequence. The broker orders them by arrival time, not by the order of the real-world actions.
- Changing the partition count. The modulo changes, so a key may map to a new partition. Old events for that key stay in the old partition. New ones go elsewhere. For a while, two consumers may handle events for the same key. Plan the partition count in advance, or migrate with care.
- Consumer rebalancing. When a consumer joins or leaves, partitions are reassigned. Events that were processed but not yet acknowledged get redelivered to the new owner. Order still holds, but you will see duplicates.
- Parallel work inside a consumer. If your consumer reads events in order and then hands each one to a thread pool, you have discarded the ordering the broker gave you. Process serially per key, or shard work by key inside the consumer.
- Retry queues and dead-letter queues. If a failed event is moved aside and later events for the same key continue, those later events overtake it. Consumers must decide whether to block the key until the failure is resolved or to tolerate the reordering.
Hot keys and skew
Hashing spreads distinct keys evenly, but not events evenly. If one key produces most of the traffic, such as a single large customer or a null tenant, one partition carries most of the load and its consumer falls behind while others idle.
Options include choosing a finer-grained key (orderId instead of customerId), or adding a suffix to split a hot key. Splitting a key gives up ordering across the pieces, so only do it when you can accept that.
Handling out-of-order events anyway
Sometimes you cannot guarantee order: multiple producers, partition changes, or a broker with weak ordering. The usual defence is to put a version number or sequence on each event for an entity and have the consumer ignore anything stale.
state = {} # order_id -> (version, status)
def apply_status(event):
order_id = event["orderId"]
current_version = state.get(order_id, (0, None))[0]
if event["version"] <= current_version:
return False # stale or duplicate: ignore
state[order_id] = (event["version"], event["status"])
return True
apply_status({"orderId": "o-1", "version": 2, "status": "paid"})
apply_status({"orderId": "o-1", "version": 1, "status": "placed"}) # arrives late
print(state["o-1"]) # (2, 'paid'), not (1, 'placed')This also protects against duplicates, because a repeated version is not newer than the stored one.
The technique has limits. It works for events that carry the full new state, where the latest version replaces everything before it. It does not work for deltas such as "add 25 to the balance", where every event must be applied. For deltas, rely on partition order, or buffer events until the missing version arrives.
Choosing an approach
| Requirement | Approach |
|---|---|
| Events about one entity must be applied in order | Use the entity ID as the key, so they share a partition |
| No ordering needed, maximum throughput | No key, or a random key |
| Several producers write about one entity | Add version numbers and discard stale events in the consumer |
| One key dominates the traffic | Use a finer-grained key, or accept lost ordering when you split it |
| Strict global order across all events | Use a single partition, and accept one consumer as the throughput limit |
Exercise
A topic has four partitions, keyed by customerId. A consumer group has six consumers. A shipping service publishes shipped events about an order, and a payment service publishes paid events about the same order, both keyed by customerId. Name two problems with this design.
Show answer
First, only four of the six consumers receive work, because each partition is assigned to one consumer and two consumers stay idle. Second, two different producers publish events about the same order, so the broker orders them by arrival time. A shipped event can be stored before the paid event even if payment happened first. Adding a per-order version number and having the consumer ignore stale events, or having a single service own the order's event stream, fixes the second problem. Keying by customerId also risks a hot partition if one customer has much more traffic than the rest.