Design a Kafka system that ensures message ordering in a multi-partition environment.
Instruction: Distinguish per-key order from global order. Propose a design for each and explain producer sequencing, consumer processing and partition-count changes.
Updated
Official answer
First define whether the requirement is per entity or global. Kafka guarantees partition order, not a total order across all partitions of a topic.
For per-account ordering, use a stable account key and consistent routing so all events for that account enter one partition. Process that partition's side effects sequentially, or enforce an explicit per-account sequence. Maintain compatible producer retry/idempotence settings and handle duplicate replay. Different accounts can then run in parallel across partitions.
A key alone is not a permanent routing guarantee if the partition count or routing policy changes. Plan a controlled migration or an explicit mapping/epoch scheme; do not assume that adding partitions redistributes old records into the new mapping. Concurrent producers also need a defined business sequence if their order matters beyond broker append order.
If every event must have one global order, a single output partition provides a straightforward serialization point, with corresponding throughput and availability constraints. Multiple input partitions can feed a sequencer, but that sequencer must establish the order and publish it to the ordered output.
A distributed merge based on global sequence numbers is another design, but allocating numbers is not enough. The merger must detect missing numbers, wait or resolve gaps, recover after crashes and deduplicate retries. Event timestamps alone do not establish a complete order when clocks differ or events arrive late. Bounded-lateness output is a stated approximation unless the application has a way to know all earlier events are complete.
For example, account A's events may be ordered within partition 0 while account B's events are ordered within partition 1; Kafka does not determine whether A's first event comes before B's first event globally.
Partition guarantees, routing changes, producer retry ordering
Related Questions
-
easy
-
hard
-
hard
-
hard
-
hard