What it is
Message ordering is the guarantee (or lack of one) that a consumer processes messages in the order they were produced. In a partitioned log such as Kafka, the guarantee is narrow and precise: records in one partition are stored and delivered in offset order. Everything beyond that, across partitions, across consumers, across retries, is up to your design.
Why it exists
Many events only make sense in sequence: an order is created before it is paid, a balance update builds on the previous one, a "user deleted" must not be followed by an older "user renamed". Processing them out of order produces wrong state that is hard to detect later. At the same time, ordering is the enemy of parallelism: a strict global order means one thing happening at a time. Systems therefore order only what must be ordered.
How it works
Per-partition order. A producer appends to a partition; each record gets the next offset. A consumer group assigns each partition to one consumer, which reads offsets in sequence. If that consumer processes records one at a time, it processes them in append order.
Keying. The producer chooses the partition from the record key (hash of key mod partitions by default). Same key, same partition, so all events of one entity are ordered relative to each other. Different keys run in parallel on different partitions. Records without a key are spread out and have no relative order.
Producer side. Without care, producer retries could reorder a partition: batch 1 fails, batch 2 succeeds, batch 1 is retried after it. The idempotent producer (enabled by default since Kafka 3.0) numbers batches per partition; the broker rejects duplicates and out-of-sequence batches, so order is preserved with up to five in-flight requests per connection.
Consumer side. Order survives only if the consumer keeps it. An unordered thread pool, asynchronous handlers or "fire and forget" calls let later records finish first. Per-key lanes (hash the key to one of N single-threaded workers inside the consumer) keep per-key order with more parallelism than partitions; libraries like Confluent’s Parallel Consumer implement this with careful offset tracking.
Retries. A failing record forces a choice. Retrying it in place (with backoff) keeps order, but every later record in the partition waits: head-of-line blocking, and a record that never succeeds (a poison pill) stalls the partition. Moving it to a retry topic or dead letter queue lets the partition continue, but the record is processed after later ones. A middle ground parks the failed record and every later record with the same key until it succeeds.
Detecting disorder. When order cannot be guaranteed end to end (multiple producers, cross-region replication, retry topics, CDC from several tables), include a version or per-key sequence number from the source of truth. Consumers apply an event only if it is newer than what they have (WHERE version < :v) and ignore or park older ones.
When to use it
- Strict per-entity order: state machines (order lifecycle), balance updates, change data capture applied to a replica.
- Per-key order with high throughput: key by entity and process each key sequentially.
- Total order: only for low volumes, or a single sequencer (one partition) where the volume allows.
When not to
- Independent records (emails, thumbnails, analytics hits): ordering costs parallelism for nothing; use a work queue.
- When consumers can be made order-insensitive with versions, commutative updates (counters, sets) or idempotent upserts.
- Across entities ("process all orders in global order") unless the business truly requires it.
Trade-offs
| Choice | You gain | You pay |
|---|---|---|
| One partition | Total order | One consumer, one broker’s throughput |
| Key by entity | Per-entity order with parallelism | Hot keys; no order across entities |
| Thread pool per consumer | Throughput beyond partition count | Order broken unless split by key; harder offset commits |
| Retry in place | Order preserved | Partition blocked during retries; poison pills stall it |
| Retry topic / DLQ | Partition keeps flowing | Retried records processed out of order |
| Versions on events | Reordering made harmless | Version must come from the source; intermediate states may be skipped |
Alternatives
- FIFO queues with groups: SQS FIFO message group ids and Azure Service Bus sessions order messages per group and let groups run in parallel, similar to keys.
- Single-writer per entity: route all commands for an entity to one actor or shard (actor frameworks, sharded workers), so ordering is local.
- Order-insensitive design: CRDTs, commutative operations, last-writer-wins by version.
Failure modes
- Silent reordering after repartitioning: adding partitions moves keys, so a key’s older records on the old partition can be processed after newer ones on the new partition.
- Poison pill: a record that always fails blocks its partition if retried in place forever.
- Async handler bugs:
awaitforgotten or work handed to an executor turns an ordered consumer into an unordered one. - Multiple producers per key: two services writing events for the same entity have no shared order unless they coordinate (or derive versions from one database).
- Rebalance redelivery: after a rebalance, uncommitted records are delivered again, after some later ones may already have had side effects elsewhere.
In production
Decide and document the ordering unit of every topic (usually the key). Enforce it in code review: no unordered executors in ordered consumers. Use idempotent producers (the default) and do not disable them to tune throughput without understanding the effect on order. Bound in-place retries, then park the key. Put versions on events that mutate state and make sinks reject stale versions. Test ordering with chaos: inject failures and delays and verify final state, not just throughput.
Common misconceptions
- "Kafka guarantees order." Per partition only.
- "Same partition means same order of side effects." Only if the consumer processes sequentially.
- "A retry topic is a free resiliency win." It reorders whatever it retries.
- "Timestamps can restore order." Clocks across producers drift; use versions or sequence numbers from one source.
- "We need global order." Usually you need per-entity order, which scales.
Interview angle
When an interviewer asks "what about ordering?", answer with the unit: "events are keyed by order id, so each order’s events are on one partition and processed sequentially; across orders there is no order and none is needed". Then cover the traps: consumer thread pools, retries (in place vs retry topic), and repartitioning. Mentioning versioned events with conditional writes as a safety net shows you design for failure rather than assuming perfect delivery.
Model assumptions
The simulation in this lesson is a simplified model, not a benchmark. Producers append 30 records per second at random (Poisson), without keys (round robin over partitions) until the keying step, then with 500 equally likely keys hashed to partitions. Each partition is a queue with one consumer; a consumer with one slot processes records one at a time (about 20, 28 and 12 ms for the three consumers, lognormal, cv 0.3). In the thread-pool step each consumer has 8 slots and highly variable work (mean 60 ms, cv 1). Order is measured from simulation events: the order records were appended to a partition versus the order they were first acknowledged. In the retry steps 5% of attempts fail. Retry in place: the failed record holds the consumer’s only slot until a 1-second timeout and is then delivered again first. Retry topic: after a 0.1-second timeout the record moves to a retry queue, which a retry consumer polls every 0.5 s (the poll is a scripted timed action). The keyless and keyed order #42 animations and the version check against the database are scripted illustrations, not simulated. Numbers show behaviour and orders of magnitude only.