Course contents

07. Messaging and Event-Driven Systems Lesson 7 of 10

Message Ordering

Why logs order only per partition, how keying by entity keeps events in sequence, how thread pools and retries break order, and how versions make it safe.

15 minIntermediate9 steps
Loading the interactive simulation…
Loading the knowledge check…

Summary

  • A single partition with a sequential consumer gives total order, and no parallelism.
  • With many partitions, order holds per partition; keying by entity keeps that entity’s events together.
  • Thread pools inside a consumer finish records out of order unless work is split by key.
  • Retrying in place keeps order but blocks the partition; retry topics keep it flowing but reorder.
  • Versions or sequence numbers let consumers reject stale events, making reordering harmless.
Deep diveHow it works, trade-offs, failure modes, misconceptions and the interview angle.

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: await forgotten 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.

The lesson as textEvery step of the simulation, written out.
  1. 1. One partition, one reader: total order

    All records go to a single partition, read by one consumer that handles one record at a time. The consumer reads offsets in sequence, so records are processed in exactly the order they were appended: not one is out of place.

    That is the strongest ordering a log offers, and the most limited: one partition means one consumer, so this order costs all parallelism.

    Scene: Producers append 30 records per second to a single partition. One consumer processes them one at a time, in exactly the order they were appended.

    Key idea: A single partition read by one sequential consumer processes records in append order.

  2. 2. Three partitions: order per partition only

    For throughput the topic gets three partitions, each with its own consumer. The consumers run at slightly different speeds.

    Inside each partition, records are still processed in append order. Across partitions there is no order at all: a record appended to P2 is often processed before one appended to P0 a few milliseconds earlier. Nothing is broken; the topic simply never promised a total order.

    Scene: Three partitions each have their own consumer, running at different speeds. Records are processed in order within each partition but out of order across partitions.

    Key idea: Order holds inside each partition and nowhere else.

  3. 3. An order’s events, scattered

    Order #42 produces three events: created, paid, shipped. Records have no key, so the producer spreads them: created lands on P0, paid on P1, shipped on P2.

    Consumer 2 happens to be idle and handles shipped first. Consumer 0 handles created next, and Consumer 1, busy with a backlog, handles paid last. A downstream service now sees an order shipped before it was created or paid, and may reject it, or worse, overwrite newer state with older.

    The moving records are a scripted illustration; the background traffic is simulated.

    Scene: A scripted illustration: order #42’s created, paid and shipped events go to P0, P1 and P2. Consumer 2 processes shipped first, then Consumer 0 processes created, and Consumer 1 processes paid last.

    Key idea: Without a key, one entity’s events land on different partitions and can be processed in any order.

  4. 4. Key by the entity that needs order

    The producer now sets the order id as the key. The partitioner hashes it, so every event of order #42 lands on the same partition, here P1, and Consumer 1 processes created, paid, shipped in that order.

    Other orders spread across all partitions, so parallelism is kept. The guarantee is per key: order #42’s events are ordered relative to each other, not relative to order #43’s. Choose the key as the smallest thing whose events must not be reordered.

    The animation is scripted; in the simulation every partition still processes its records in append order.

    Scene: Records are keyed by order id. In a scripted illustration all three events of order #42 go to P1 and Consumer 1 processes them in order. Each partition processes its records in append order.

    Key idea: Key by entity: same key, same partition, so that entity’s events stay in order while different entities run in parallel.

  5. 5. A thread pool inside the consumer

    To go faster, each consumer now hands records to a pool of 8 threads, and processing time varies a lot (some records call a slow API).

    The partition still delivers records in order, but they finish in a different order: a slow record at offset 100 is still running while offsets 101 and 102 complete. Order within a partition is now broken, even for the same key.

    The fix is to parallelise by key, not by record: hash the key to one of N single-threaded lanes inside the consumer, so one order’s events still go one after another (libraries such as Confluent’s Parallel Consumer offer this "key order" mode). Committing offsets also gets harder: only commit up to the lowest unfinished offset.

    Scene: Each consumer processes up to 8 records at once with highly variable processing time. Records within a partition now finish out of append order.

    Key idea: Parallel processing inside a consumer breaks partition order unless work is split by key.

  6. 6. Retrying in place blocks the partition

    Back to one thread per consumer. Now about 1 record in 20 fails on its first try (a flaky downstream call). The consumer retries it in place: it does not move on until that record succeeds, here after a 1-second timeout.

    Order is perfectly preserved: nothing overtakes the failing record. The price is head-of-line blocking: every record behind it in that partition waits. Backlogs that were a record or two now jump to 15 to 25 records behind failures, and a record that keeps failing (a "poison pill") would stall its partition indefinitely.

    Scene: About one in twenty attempts fails. Each consumer retries the failed record before moving on, so records are processed in order but backlogs spike behind every failure.

    Key idea: Retrying in place keeps order but stalls the whole partition behind the failing record.

  7. 7. A retry topic unblocks, and reorders

    To avoid blocking, a failed record is moved after a short 0.1 s timeout to a separate retry topic and the consumer carries on. A retry consumer polls that topic every half second and processes what it finds.

    Partitions no longer stall: backlogs stay small. But a retried record is now processed after records that were appended behind it on its partition. If those records belong to the same order, its events are out of order again.

    This is the standard trade-off: ordering or availability of the partition. Retry topics suit independent records; for ordered streams, park every later record of the same key too, or make the consumer tolerate reordering (next step).

    Scene: Failed records are moved to a retry topic after 0.1 s and processed later by a retry consumer. Partition backlogs stay small, but the retried records are processed after later records of their partition.

    Key idea: Moving failures aside keeps partitions flowing but processes the retried records out of order.

  8. 8. Sequence numbers make reordering harmless

    When order cannot be guaranteed end to end, make the consumer detect it. Each event carries the entity’s version (or a sequence number per key), set by the producer from the source of truth.

    The consumer applies an event only if it is newer than what it has: UPDATE orders SET … WHERE id = 42 AND version < 3. In the animation, Consumer 1 applies v3 (shipped); later the retry consumer delivers the stale v2 (paid), and the database rejects it. The final state is right regardless of arrival order.

    Kafka uses the same idea internally: an idempotent producer (the default since Kafka 3.0) numbers its batches per partition, and the broker rejects duplicates and out-of-sequence batches, so producer retries do not reorder a partition.

    The version check is a scripted illustration; the database is not simulated.

    Scene: A scripted illustration: Consumer 1 writes version 3 of order #42 to the database. Later the retry consumer tries to write the older version 2, and the database rejects it because its version is lower.

    Key idea: Version or sequence numbers let consumers reject stale events, so late arrivals cannot corrupt state.

  9. 9. How much order do you need?

    Logs order within a partition. Keep an entity’s events together by keying by that entity, and keep them in order by processing each key sequentially: one thread per partition, or per-key lanes. Retries force a choice between blocking the partition and processing out of order.

    Often the best answer is to need less ordering: make events carry versions, make handlers idempotent and reject stale updates. Then order becomes an optimisation instead of a correctness requirement.

    Scene: Keyed records flow through three partitions, each processed in order by its consumer. The flaky dependency is fixed, so the retry topic stays empty.

    Key idea: Order per key via keying and sequential processing; versions and idempotency for everything ordering cannot cover.