MessagingIntermediate

How do you keep events in order?

“Consumers sometimes see `OrderUpdated` before `OrderCreated`. Why does that happen in a partitioned log, and how do you choose a partition key?”

What this tests

  • Ordering is per partition, not per topic
  • Partition key tradeoffs: ordering vs throughput vs hot keys
  • Consumer-side defences: version numbers, buffering, idempotent upserts
  • Understanding of what changes on a key change or a partition count change

Answers by level

Read the beginner answer first and notice what is missing.

A topic is split into partitions, and the broker orders messages within a partition only. If OrderCreated lands on partition 0 and OrderUpdated on partition 2 — because the key was random, or absent, or changed between publishes — two consumers read them in parallel and the update can be processed first. Nothing is misconfigured; ordering across partitions was never promised.

The fix is the partition key: use the order id, so every event for one order goes to the same partition and is consumed in publish order. The tradeoff is throughput and skew: fewer distinct keys means fewer partitions doing work, and a hot key — one enormous customer if the key is customer id — concentrates traffic on one partition and one consumer. Random keys maximise throughput and destroy ordering. Ordering is also per producer; two services publishing about the same order are not ordered relative to each other.

Consumers should still be defensive: carry a version or sequence on the event, ignore updates older than the current state, and make handlers idempotent upserts. That protects against replays and against the day the key changes.

Green flags · Red flags

Strong green flag · Asks whether the consumer needs ordering or only convergence, and suggests versioned upserts as the ordering-free design.
Green flags
  • States ordering is per partition and per producer
  • Diagnoses the symptom as a key problem, not a broker bug
  • Chooses order id and explains the hot-key and throughput tradeoffs
  • Adds version checks and idempotent upserts on the consumer
  • Knows partition count changes remap keys
Red flags
  • "Kafka guarantees ordering."
  • Proposes a single partition for the whole topic to fix it
  • Adds more consumers than partitions to speed up a hot partition
  • Does not mention any consumer-side defence

Follow-up questions

F1
One partition has 40 minutes of lag; the others are current. What is wrong?
F2
You need to go from 12 to 24 partitions. What breaks?
F3
Two services both publish events about an order. Are they ordered?

Scenario

After a refactor, the producer stopped setting the message key to "improve throughput". Within an hour the inventory read model shows negative stock for some orders and consumers log "update for unknown order". Explain the causal chain, the fix, and how you would have caught it in review.

Learn this topic