How to Preserve Message Ordering
Preserve the order where it matters: partition by key so one entity stays ordered, and accept the cross-key parallelism as the design.
On this page
Introduction
A message broker distributes the messages across the consumers for throughput, which means the order they arrive is not guaranteed unless the broker and the consumer cooperate. For events about the same entity, the order matters: an order confirmed before it is placed is wrong. For events about different entities, the order does not matter, and forcing it would cost the throughput. Preserving the order where it matters is the design: order per entity, parallel across entities.
This tutorial covers deciding the ordering that matters, partitioning by the entity key, consuming in order per partition, and testing the order and the parallelism. The examples use a partitioned log, and the design applies to any broker with a partition or a message-group concept.
Decide the ordering that matters
Global ordering is not achievable in a distributed system without a single sequence, which is a bottleneck and a single point of failure. What is achievable and what the consumers need is per-entity ordering: the events for one order, one account, or one user are in order, and the events for different entities need not be. Decide the entity whose order matters, and accept the rest.
For each consumer, the entity whose events it processes in order is the partition key. A consumer that updates an account balance needs the account’s events in order; the events for different accounts are independent. Naming the entity is what lets the design provide the order it needs without the global order it does not.
# the entity whose events must be ordered is the partition key
key = orderId # the order's events stay in order
# events for different orders may be processed in any order
Partition by the ordering key
Publish each event with a key, the entity id, and the broker routes all the events with the same key to the same partition. Within a partition, the events are ordered, so one entity’s events are ordered. Different keys go to different partitions, so the processing parallelises across the entities.
The key’s distribution matters: a skewed key, such as one that most events share, sends most events to one partition and concentrates the load. Choose a key with many distinct values, such as the order id, so the partitions are balanced. The order is preserved per key, and the balance comes from the number of distinct keys.
// publish with the entity id as the key: all events for one order to one partition
await producer.send({
topic: 'orders',
messages: [{ key: String(order.id), value: JSON.stringify(event) }],
});
Consume in order per partition
A consumer processes one partition at a time and in order, so the per-entity order holds. Multiple consumers each take some partitions, and the processing parallelises across the partitions while each partition’s order is preserved by a single consumer. A partition is processed by one consumer at a time, which is what makes the order hold within it.
Do not reorder within the consumer: process the messages in the order they arrive, and do not dispatch them to a pool that completes them out of order. Where the processing is slow, the parallelism is across the partitions, not within one partition’s sequence. This is the constraint that buys the order: one partition, one consumer, in order.
// one consumer per partition, processing in order
await consumer.run({
eachBatch: async ({ batch }) => {
for (const message of batch.messages) {
await process(JSON.parse(message.value)); // sequential within the partition
}
},
});
// scale by adding consumers for other partitions, not by parallelising one partition
Handle the partition count and the rebalance
The number of partitions caps the parallelism: a topic with ten partitions has at most ten consumers processing, and the per-key order holds within a partition. Choose the partition count for the expected parallelism, and know that adding partitions later changes the key-to-partition mapping, so some entities’ events may move between partitions during the change.
A consumer group rebalances when a consumer joins or leaves: the partitions are reassigned, and the order is preserved across the rebalance as long as the consumer commits its offsets and resumes from where it stopped. The rebalance moves a partition to another consumer, which continues from the committed offset, so the order holds. Test the rebalance, because a bug there reorders or skips events.
Test the order and the parallelism
Test that one entity’s events are processed in order, by publishing a sequence for one key and asserting the consumer processed them in that order. Test that different keys are processed in parallel, by publishing for several keys and asserting the processing overlaps. Test the rebalance, by adding a consumer mid-stream and asserting no event is skipped or reordered for a key.
# publish A1 A2 A3 for key A: assert the consumer processed them in order
node scripts/publish-seq.mjs --key A --events A1,A2,A3
node scripts/assert-order.mjs --key A # A1, A2, A3
# add a consumer mid-stream: assert no event is lost or reordered
Common pitfalls
Expecting a global order, a key with few distinct values that skews the partitions, parallelising within one partition’s sequence so the order breaks, ignoring the rebalance so a partition move reorders or skips events, and a consumer that acknowledges before processing so a crash loses the event are the recurring mistakes. Per-entity ordering, a high-cardinality key, a sequential per-partition consumer, a committed-offset resume, and an acknowledge-after-processing address them.
Conclusion
Preserve the order where it matters, per entity, and accept the parallel processing across the entities. Decide the ordering key, partition by it, consume each partition in order with one consumer, and handle the partition count and the rebalance. Self-check by publishing a sequence for one key and asserting the order, and by adding a consumer and asserting no event is lost or reordered. Then one entity’s events are in order and the entities process in parallel.
Sources: Kafka: Topic partitions and ordering, AWS SQS: FIFO queues and message groups, Confluent: Message ordering.
FAQ
- Can I have a global order?
- Not in a distributed system without giving up throughput and availability: a global order means a single sequence, which is a bottleneck. Order per entity is what the consumers actually need, and partitioning by the entity id provides it while different entities process in parallel.
- What if one partition is slow?
- The events for that partition's entities wait, but the other partitions proceed, so the slowness is contained to the entities in that partition. If the load is skewed, the partition key is uneven; a better key spreads the entities, at the cost of the order for the spread entities.
Report a problem with this articleOpens a pre-filled issue on GitHub.