How does Kafka ensure message ordering within a partition?

Instruction: Explain the mechanism Kafka uses to maintain message order within a single partition.

Context: This question tests the candidate's knowledge of Kafka's partitioning and ordering guarantees, which are fundamental for ensuring data integrity in applications that rely on message order.

Updated

Official answer

A partition is an ordered log. Appended records receive increasing offsets, and a consumer reads its visible records in offset order. Offsets may have gaps because of compaction or transaction records; a gap is not by itself evidence of out-of-order delivery.

For per-customer ordering, route that customer's records to the same partition using a stable key and partitioning policy. This requires consistent serialization, partition count and routing. An explicit partition, a custom partitioner, or a change in the partition count can change that mapping. There is no topic-wide order across partitions.

The append order is not necessarily event-time order or a business-defined order between concurrent producers. If events must follow a business sequence, define and validate that sequence rather than inferring it from timestamps or producer start times.

Producer retries also matter. With idempotence disabled and multiple requests in flight, a later batch can succeed before an earlier failed batch is retried. Compatible idempotence settings preserve retry ordering and deduplicate the producer's retries within its documented scope; they do not deduplicate every application resend.

Finally, polling in order does not force concurrent worker tasks to finish in order. Process each partition sequentially when side-effect order matters, or use an explicit sequencing mechanism. Commit only completed work, and handle reassignment and replay safely.

Consumer offsets, producer ordering settings, partition-count changes

Related Questions