An inventory service consumes stock events. A product is decremented to zero and then restocked to 50, in that order, a few milliseconds apart.
The consumer applies them in the opposite order. Stock reads 0. The product disappears from search for six hours until the next full reconciliation.
Both events were produced correctly. Kafka delivered both. The problem is that they went to different partitions, and Kafka never promised anything about the relative order of messages in different partitions.
The guarantee is narrower than the mental model
Kafka appends messages to a partition and assigns each an offset. Within that partition, every consumer reads them in the same order, always. That guarantee is strong and it is the whole of it.
Across partitions there is no relationship at all. Two messages produced a microsecond apart to different partitions can be consumed in either order, minutes apart, by different consumer instances.
flowchart TB
P["Producer: two events for SKU-42"] --> K{"Partitioner"}
K -->|"decrement -> partition 3"| P3["Partition 3<br/>consumed by instance A"]
K -->|"restock -> partition 7"| P7["Partition 7<br/>consumed by instance B"]
P3 --> R["No ordering relationship.<br/>Either can be applied first."]
P7 --> R
style R stroke:#ef4444,stroke-width:3px,color:#fff
So the design question is not whether the topic is ordered. It is which events need to be ordered with respect to each other, and making sure those share a partition.
The key is the decision
The partition is chosen from the message key: normally hash(key) % partitionCount. Same key, same partition, ordered. Different key, no guarantee.
// No key. Round robin. Ordering between these two is not defined.
producer.send(new ProducerRecord<>("stock-events", event));
// Keyed by SKU. Every event for this SKU lands on one partition, in order.
producer.send(new ProducerRecord<>("stock-events", event.sku(), event));
That one argument is the entire difference, and its absence produces a system that works perfectly under light load and reorders under concurrency, which is the worst possible testing profile.
Modern producers use sticky partitioning for null keys, filling one batch for a partition before switching. That improves throughput and makes reordering less frequent, which makes the bug rarer and harder to reproduce rather than less real.
Choosing the key means choosing the unit of ordering, and it is a modelling decision:
| Key | Ordered per | Risk |
|---|---|---|
null | nothing | reordering under any concurrency |
sku | product | a hot product concentrates load |
orderId | order | usually the right granularity |
customerId | customer | a large customer skews one partition |
region | region | very few distinct values, severe skew |
Coarser keys give stronger ordering and worse balance. A key with few distinct values puts most traffic on a few partitions, which is a hot key problem that no amount of partitioning fixes because the hash of a given key is fixed.
The other consequence of key-based partitioning: adding partitions changes the mapping. A key that hashed to partition 3 with 12 partitions hashes somewhere else with 24, so in-flight events for the same entity can be split across the old and new partitions during the transition. Increasing partition count on an ordered topic is a correctness event, not a capacity change.
Ordering is lost on the producer too
Before the message reaches a partition there is a second place ordering can break.
With retries enabled and more than one in-flight request per connection, a failed batch can be retried after a later batch has already succeeded, so messages arrive in the wrong order within the same partition.
props.put(ProducerConfig.ENABLE_IDEMPOTENCE_CONFIG, true);
props.put(ProducerConfig.MAX_IN_FLIGHT_REQUESTS_PER_CONNECTION, 5);
props.put(ProducerConfig.ACKS_CONFIG, "all");
The idempotent producer solves this properly: the broker deduplicates using a sequence number per producer and rejects out of order batches, so ordering is preserved with up to five in-flight requests rather than being limited to one. It has been the default since Kafka 3.0, and it is worth checking rather than assuming on any client that was configured earlier.
The consumer throws it away
This is the failure I have seen most often, because it is introduced deliberately as an optimisation.
// Kafka carefully ordered these. The pool immediately reorders them.
for (ConsumerRecord<String, Event> record : records) {
executor.submit(() -> handle(record));
}
The broker guaranteed order within the partition. Handing those records to a pool means they complete in whatever order the scheduler produces, and two events for the same SKU can be applied backwards inside a single poll batch.
Preserving order while still using threads means routing by key so each entity is always handled by the same worker.
// Same key, same worker, so per-key ordering survives the parallelism.
int worker = Math.floorMod(record.key().hashCode(), workers.length);
workers[worker].submit(() -> handle(record));
Offset commits get harder once processing is out of order, because message 105 finishing before 103 means you cannot commit 105 without risking the loss of 103 on a restart. The usual approach is to track the lowest un-acknowledged offset and commit only up to there, which is more bookkeeping than the naive version and is the actual cost of parallel consumption.
When you do not need it
Ordering has a price and a lot of systems pay it without needing to.
If the handler is idempotent and the events are commutative, ordering does not matter. Setting an absolute value is order independent in a way that applying a delta is not, which is a reason to prefer events carrying state over events carrying increments where you can.
If events carry a version and the consumer discards anything older than what it has already applied, reordering is handled at the application level and the transport does not have to guarantee anything. That is the same logical clock reasoning that orders events without trusting wall time, and it is more robust than relying on the pipeline, because it survives replays, DLQ redelivery and partition changes.
I would generally reach for that first. Making the consumer tolerant of order is a property that holds everywhere, and making the pipeline preserve order is a property that holds until somebody adds a thread pool.
// SPONSORSHIP
If this research saved you time or improved your architecture, consider sponsoring my work on GitHub. All sponsorships go directly toward infrastructure and further technical research.
[ Become a Sponsor ]