Video in progress
How do you choose the Kafka partition key for order events, and what problem does a wrong choice cause?
Events whose order matters must share one key, usually the aggregate ID, such as orderId. With no key or the wrong one, OrderCancelled can be processed before OrderCreated; a key that is too "fat" overheats a single partition.
📖 Answer
Kafka guarantees order only inside a single partition. Messages with the same key land in the same partition, so with orderId as the key, the Created → Paid → Shipped sequence of one order is preserved.
If the key is null, the producer spreads messages across partitions. Created goes to partition 3, Cancelled to partition 7, and a different consumer may process it earlier. In prod this shows up as odd errors like "couldn't cancel an order that doesn't exist".
The opposite mistake is using a very large group as the key. If merchantId is the key and one big merchant produces 40% of the traffic, that partition and the single consumer reading it get clogged. The other consumers sit idle. Lag grows on just one partition, and that is exactly the sign you see in the metrics.
Two more things:
- If you increase the partition count later, the key → partition mapping changes, and ordering can break at that moment. So choose with some headroom at the start.
- To keep order across producer retries you need
enable.idempotence=true(on by default in Kafka 3.0+ clients).
If ordering isn't needed at all, sending without a key is also a fine choice: the load spreads evenly.
Sign up to mark studied questions and save your progress.