Sub topic 10
Ordering guarantees and their limits
This chapter assumes you know what producers, consumers, brokers, and acknowledgements are, and that you have seen competing consumers pull from one queue. Here you will see when a queue keeps messages in order, when it stops doing so, and what to do about it.
What a single queue promises
A queue is first-in, first-out (FIFO). If a producer publishes A and then B to one queue, the broker stores A ahead of B and hands out A first. With one producer and one consumer that processes each message to completion before taking the next, the consumer sees A then B.
That promise covers delivery from the broker. It says nothing about the order in which your code finishes the work.
Where order breaks
Order is lost in four common ways:
- Competing consumers. Two consumers take
AandBat nearly the same time. IfAis slower,Bfinishes first. - Redelivery.
Afails, is requeued, and arrives afterBhas already been handled. - Retries and dead-letter queues. A message sent to a retry queue comes back later than messages published after it.
- Multiple producers. Messages from different producers have no shared clock. The broker orders them by arrival, not by when each producer created them.
Keeping order where it matters
Most systems do not need global order. They need order for related messages, such as all events for one order ID or one user. Two techniques follow from that.
- One consumer per queue. Simple and strictly ordered, but throughput is limited to one worker.
- Partition by key. Route all messages with the same key to the same queue or partition, and give each one a single consumer. Different keys still run in parallel. Log-based brokers do this natively, and a later chapter covers them.
The sketch below shows the idea in plain Python. It hashes the key to pick a worker queue, so one key always lands on the same worker.
import queue
import threading
import zlib
NUM_WORKERS = 3
queues = [queue.Queue() for _ in range(NUM_WORKERS)]
def worker(index):
while True:
item = queues[index].get()
if item is None:
break
key, seq = item
print(f"worker {index} handled {key} #{seq}")
threads = [threading.Thread(target=worker, args=(i,)) for i in range(NUM_WORKERS)]
for t in threads:
t.start()
def publish(key, seq):
index = zlib.crc32(key.encode()) % NUM_WORKERS
queues[index].put((key, seq))
for seq in range(3):
publish("user-1", seq)
publish("user-2", seq)
for q in queues:
q.put(None)
for t in threads:
t.join()The code uses zlib.crc32 instead of hash() because Python randomizes string hashes between runs. A stable hash keeps a key on the same worker across restarts.
Designing around weak order
When you cannot enforce order, make the consumer tolerate it:
- Put a version number or sequence number in each message, and ignore a message older than the state you already stored.
- Send full state ("status is shipped") instead of deltas ("move to next status"), so a late message cannot corrupt the result.
- Accept that a retried message may arrive late, and decide whether that is harmless for the business operation.
Exercise
Three consumers share one queue. Messages "create account" and "update email" for the same user are published in that order, yet the update is sometimes applied first. Give the cause and one fix.
Show answer
Competing consumers may take the two messages at the same time, and the one handling "create account" can finish later. Fix it by routing all messages for the same user key to the same queue or partition with a single consumer. You could also add a sequence number so the consumer rejects or delays an update that arrives before its prerequisite.