Tech challenge · Kafka

Order events arrive out of order

MediumKafka

A consumer sees order_shipped before order_created for some orders. The topic has 12 partitions, and producers send with no key. Why, and what guarantees can Kafka give?

Think it through or sketch an answer first, then open the hint or the solution.

Show a hint

Kafka orders messages within a partition, not across a topic.

Show the solution

Without a key, events for one order are spread across partitions, and consumers read partitions independently, so there is no order between them. Use the order id as the key: all events for an order then go to the same partition and are read in the order they were written. Enable the idempotent producer so retries cannot reorder or duplicate messages within a partition.

Example (Python)

from confluent_kafka import Producer

p = Producer({'bootstrap.servers': 'broker:9092', 'enable.idempotence': True, 'acks': 'all'})
p.produce('orders', key=str(order_id), value=payload)
p.flush()

Common mistakes

  • Using a single partition for the whole topic: it fixes ordering by giving up all parallelism.
  • Adding partitions later without thinking: keys are remapped, so ordering breaks for in-flight entities during the change.

Learn more

More Kafka challenges

Today's challenge and the full archive