Video in progress
How do you choose the partition key for a Kafka topic, and what problems does a wrong choice cause?
You choose it by the unit that needs ordering — usually orderId or userId, since order is guaranteed only within a partition. If the key has few distinct values or is skewed, one partition overheats and the consumer falls behind.
📖 Answer
Kafka preserves order within a partition, not across partitions. The CREATED → PAID → SHIPPED events of one order must land in the same partition, otherwise SHIPPED might be processed before PAID. So the key is orderId.
Common mistakes:
- Sending without a key. Order is lost. If you don't need order at all (logs, metrics), that's fine.
- Low cardinality. The key is
countryand 90% of the traffic isUZ. One partition does all the work, the other 11 sit idle, and consumer lag grows in just one place. - One big customer. The key is
merchantId, and one merchant produces half the traffic. If you make the keymerchantId + orderId, order within a merchant is lost but within an order it stays. Usually that's enough. - Increasing the partition count later. The default partitioner uses
hash(key) % partitions; after partitions are added, the same key lands in a different partition and order breaks during the transition. So choose the partition count with headroom from the start (for example, 2–3 times the expected number of consumers).
In monitoring, look at lag per partition, not the total lag — a hot partition is only visible that way.
Sign up to mark studied questions and save your progress.