Sub topic 10
Ordering guarantees and their limits
This chapter assumes you know what producers, consumers, brokers, and queues are. It also assumes you understand acknowledgements, redelivery, and competing consumers from earlier chapters. Here you will learn what "ordered" means for a queue, where the guarantee breaks, and how to design around the breaks.
What a queue actually promises
A single queue is a first-in, first-out (FIFO) structure. If a producer publishes message A and then message B to the same queue over the same connection, the broker stores A ahead of B. It also hands A out ahead of B.
That promise covers only delivery order from the queue. It says nothing about the order in which your code finishes processing the messages. Three things sit between "stored in order" and "processed in order":
- Several consumers may take messages from the same queue at the same time.
- A failed message may go back to the queue and be delivered again.
- Several producers may publish at the same time, so "A before B" is not defined across them.
Most ordering bugs in production come from one of these three, not from the broker itself.
Where ordering breaks
Competing consumers
With competing consumers, the broker gives message 1 to consumer X and message 2 to consumer Y. Nothing makes Y wait for X. If message 1 takes 800 ms and message 2 takes 20 ms, message 2 finishes first.
A single consumer with a prefetch greater than one has a milder version of this problem. If it hands the prefetched messages to a thread pool, they can finish out of order.
Redelivery
Suppose a consumer receives message 1, crashes before acknowledging it, and the broker requeues it. Meanwhile message 2 has gone to another consumer and is already done. Message 1 now arrives after message 2.
The same thing happens with retries. A consumer rejects message 1 with requeue=True. RabbitMQ puts a requeued message back at its original position when it can, but with several consumers active the message can still be processed after later ones. Retry through a delay queue or a retry topic, which is the usual design, always puts the message behind newer ones.
Multiple producers
If two services publish to the same queue, the broker orders messages by arrival time at the broker. Network delay can make an "earlier" event from service A arrive after a "later" event from service B. No queue can fix an order that the producers never established.
Ordering in different broker types
The guarantee depends on the broker's design. The table summarizes the common cases.
| Broker model | What is ordered | What is not |
|---|---|---|
| Single queue, one consumer (RabbitMQ, SQS standard with one reader) | Delivery order, if there are no redeliveries | Order after a requeue or retry |
| Single queue, many consumers | Delivery order only | Processing and completion order |
| SQS standard queue | Nothing guaranteed (best-effort ordering) | Almost all ordering |
| SQS FIFO queue | Order within a message group ID | Order across different groups |
| Log-based broker (Kafka) | Order within one partition | Order across partitions |
Two points stand out. First, ordering is nearly always scoped: it holds inside a queue, a message group, or a partition, and never across the whole system. Second, the scoped designs share an idea. You choose a key, such as an order ID or user ID. The broker sends every message with that key to one place. That place is processed by one consumer at a time. This gives you order where you need it and parallelism everywhere else.
Ordering per key
You rarely need a total order over all messages. A shop does not care whether user 7's order is processed before user 9's. It does care that user 7's "created" event comes before user 7's "cancelled" event.
The standard technique is to route by key so that one key always reaches the same consumer. The next example does this in process. It uses one queue per worker and a stable hash of the key to choose the worker. Python's built-in hash() for strings changes between runs, so the example uses zlib.crc32, which is stable.
import queue
import threading
import zlib
NUM_WORKERS = 3
queues = [queue.Queue() for _ in range(NUM_WORKERS)]
results = []
lock = threading.Lock()
def worker(index):
while True:
item = queues[index].get()
if item is None:
break
key, seq = item
with lock:
results.append((key, seq))
def route(key, seq):
index = zlib.crc32(key.encode()) % NUM_WORKERS
queues[index].put((key, seq))
threads = [threading.Thread(target=worker, args=(i,)) for i in range(NUM_WORKERS)]
for t in threads:
t.start()
for seq in range(5):
for key in ("user-7", "user-9", "user-12"):
route(key, seq)
for q in queues:
q.put(None)
for t in threads:
t.join()
for key in ("user-7", "user-9", "user-12"):
seqs = [s for k, s in results if k == key]
print(key, seqs, seqs == sorted(seqs))Each key's sequence prints in order and the last column prints True. The interleaving between keys is not fixed, and that is fine.
Brokers implement the same idea in their own terms. Kafka hashes the message key to pick a partition. SQS FIFO uses the MessageGroupId. RabbitMQ offers a consistent-hash exchange plugin, or you can run a single-active-consumer queue.
The cost of strict ordering
Ordering limits parallelism. Within a key, work is serial. If one key is very busy (a "hot" key, such as one large customer), its single consumer becomes the bottleneck, and adding consumers does not help.
A failing message is worse. To keep order, a consumer must not skip a message that failed, because later messages for that key may depend on it. The key is blocked until the message succeeds or you move it aside. This is head-of-line blocking. A poison message that always fails can stall every message behind it for that key.
You then have a choice with no free option:
- Block the key and retry until it works. Order is kept, but progress stops.
- Send the failed message to a dead-letter queue and continue. Progress continues, but later messages are processed without the earlier one.
- Park all later messages for that key as well, until someone resolves the problem. This keeps both order and correctness, and it costs the most to build.
Designing so order matters less
Often the best fix is to make the consumer tolerant of disorder, so you do not depend on the broker for it. Three techniques help.
- Sequence numbers or versions. The producer attaches an increasing version to each update for an entity. The consumer applies an update only if its version is newer than the stored one. Late, stale messages are dropped.
- Commutative operations. Adding 5 to a counter and adding 3 give the same result in either order. Prefer such operations to "set the counter to 8".
- State in the message. Send the full new state rather than a delta. A late message then overwrites with old data, so combine it with a version check.
The next example applies a version check. It also gives you idempotency for free, because a duplicate has the same version as the stored one and is ignored.
import sqlite3
def apply_update(db, entity_id, version, value):
with db:
cur = db.execute(
"UPDATE entities SET version = ?, value = ? "
"WHERE id = ? AND version < ?",
(version, value, entity_id, version),
)
if cur.rowcount == 0:
exists = db.execute(
"SELECT 1 FROM entities WHERE id = ?", (entity_id,)
).fetchone()
if exists:
return False # stale or duplicate
db.execute(
"INSERT INTO entities (id, version, value) VALUES (?, ?, ?)",
(entity_id, version, value),
)
return True
db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE entities (id TEXT PRIMARY KEY, version INTEGER, value TEXT)")
print(apply_update(db, "order-1", 2, "shipped")) # True
print(apply_update(db, "order-1", 1, "created")) # False, arrived late
print(apply_update(db, "order-1", 2, "shipped")) # False, duplicate
print(db.execute("SELECT value FROM entities").fetchone()[0]) # shippedChecklist
- Decide which entities need ordered handling, and pick the key that identifies them.
- Route by that key to a partition, message group, or single consumer.
- Keep one in-flight message per key. Watch prefetch and thread pools inside the consumer.
- Decide what happens to a failed message before it happens: block, dead-letter, or park.
- Add version checks where a stale message could do damage.
Exercise
A queue has three competing consumers. Messages "set status=paid" and "set status=refunded" for the same order are published in that order, yet the final status is sometimes "paid". Name two causes and one fix for each.
Show answer
Cause 1: the two messages went to different consumers, and the "paid" handler finished after the "refunded" handler. Fix: route by order ID so that all messages for one order reach the same consumer (a partition, message group, or hash-based queue). Cause 2: the "refunded" message was processed first, or the "paid" message failed and was redelivered after "refunded" had been applied. Fix: store a version with each update and apply a message only if its version is higher than the stored one, so a late "paid" is ignored.
Exercise
Why is it risky to add a fourth worker to the hash-routing example while messages are still being published?
Show answer
The worker is chosen as crc32(key) % NUM_WORKERS. Changing the worker count from three to four changes the result for many keys. A key's old messages may still be waiting on its old worker while new messages go to a different worker, so two workers can process the same key at once and order is lost. Drain the queues first, or use a scheme that moves keys in a controlled way.