Courses / System Design Interview / Chapter 16
Module 3 · Building Blocks II: Monitoring, Caching and Messaging · Chapter 16 of 49
Distributed Message Queues
Builds on Core Concepts: RPCs, Consistency, Failures and Time and Building Blocks: The Parts Every Design Reuses. Next up: Publish-Subscribe Systems.
Part 1 · Why queues: decoupling and absorbing spikes
A line between two services
When a shop takes an order, it also has to charge a card, update stock and send a receipt. Doing all of that before replying makes the customer wait for the slowest step.
A message queue is a buffer that sits between the part of a system that creates work and the part that does it. The creator is the producer. It writes a message, a small record that describes one piece of work, such as an order number, and carries on. The doing is done by a consumer, also called a worker, which takes messages from the queue one at a time. The queue keeps each message until a consumer has dealt with it.
The queue separates the two sides in three ways. It separates them in time: the consumer can be slow, restarting or switched off, and the message waits. It separates them in rate: the producer can add messages faster than the consumer finishes them, for a while. And it separates them in knowledge: the producer does not know which consumer will do the work or how many of them exist, so you can add consumers without changing the producer.
Nothing is free. A queue adds delay, because the work now happens later. It adds a system to run and to watch. And it changes the shape of the answer: the producer can say only that the work was accepted, not that it is done, so the user may need a status page or a notification. Use a queue for work that can wait. Keep on the direct path anything that the user's next screen depends on.
A spike, with and without a queue
Suppose a shop normally gets 100 orders a second, and a sale brings 400 a second for three seconds. The workers can finish 200 orders a second. Without a queue, the order service calls the workers directly, and any order beyond 200 in a second has nowhere to go. With a queue, the extra orders wait.
The program below is a simulation, not a measurement of a real queue: it steps through fourteen seconds, counts how many messages are waiting at the end of each second, and computes how long the newest message would wait, which is the depth divided by the rate at which workers drain it.
CAPACITY = 200 # messages finished per second arrivals = [100] * 3 + [400] * 3 + [100] * 8 # 3-second spike depth = lost = 0 drained = None print("sec arrive done depth last waits direct call: lost") for sec, n in enumerate(arrivals): backlog = depth + n done = min(backlog, CAPACITY) depth = backlog - done lost_now = max(0, n - CAPACITY) # a direct call cannot wait lost += lost_now if depth == 0 and sec >= 3 and drained is None: drained = sec wait = depth / CAPACITY # seconds to drain what is queued print(f"{sec:>3} {n:>7} {done:>5} {depth:>6} {wait:>8.1f} s " f"{lost_now:>14}") print(f"queue : nothing lost, empty again at second {drained}") print(f"direct: {lost} of {sum(arrivals)} requests lost")
l1_spike.py: a three-second spike against workers that do 200 a second
It was run with Python 3.12.10. It is plain arithmetic, so it prints the same every time.
sec arrive done depth last waits direct call: lost 0 100 100 0 0.0 s 0 1 100 100 0 0.0 s 0 2 100 100 0 0.0 s 0 3 400 200 200 1.0 s 200 4 400 200 400 2.0 s 200 5 400 200 600 3.0 s 200 6 100 200 500 2.5 s 0 7 100 200 400 2.0 s 0 8 100 200 300 1.5 s 0 9 100 200 200 1.0 s 0 10 100 200 100 0.5 s 0 11 100 200 0 0.0 s 0 12 100 100 0 0.0 s 0 13 100 100 0 0.0 s 0 queue : nothing lost, empty again at second 11 direct: 600 of 2300 requests lost
During the spike the workers finish 200 a second and the depth grows by 200 each second, to 600. After the spike the arrivals fall to 100 a second, so the workers gain 100 a second on the backlog, and the queue is empty again at second 11. The last message to be queued during the spike waited about three seconds. With a direct call, 200 orders in each spike second were lost, which is 600 of the 2,300 orders in the run.
Reading the depth
The depth of a queue is the most useful number it has. A depth that rises and then falls, as above, means the system took a spike and recovered. A depth that rises and keeps rising means that on average the producers add messages faster than the consumers finish them, and the queue is only postponing the failure. The remedies are more consumers, faster consumers, or a limit on producers. The last lesson of this chapter measures more consumers and a limit on the queue.
The same arithmetic gives you a way to size a queue and its workers. If the spike is 300 messages a second above the workers' capacity for 10 seconds, the queue must hold 3,000 messages, and clearing them takes 3,000 divided by the workers' spare capacity, in seconds. A queue that holds more than the busiest burst, plus some margin, is enough. A queue whose backlog needs more than a few minutes to clear is a sign that the workers are too few.
Do not confuse the depth with the age of the oldest message. Depth counts how many are waiting. Age says how long the longest-waiting one has been there, and it is closer to what a user feels. Many teams alert on age.
What three things does a queue separate between the producer and the consumer?
- Time, because the consumer can be down while messages wait.
- Rate, because the producer can add faster than the consumer finishes for a while.
- Knowledge, because the producer does not know who consumes the messages or how many consumers there are.
In the run, the workers finish 200 a second and 400 arrive each second for three seconds. What is the queue depth after the spike, and when does it empty?
- 600 messages at the end of second 5, and it is empty again at second 11.
- Afterwards the arrivals are 100 a second, so the backlog shrinks by 100 a second.
A queue's depth rises steadily for an hour. What does that tell you?
- On average, messages arrive faster than consumers finish them, so the queue is only delaying the problem.
Part 2 · Acknowledgements and visibility timeouts
Not deleted until done
A queue that deleted a message the moment it handed it out would lose the message whenever the consumer crashed. So queues do not delete on delivery. The consumer receives the message, does the work, and then sends an acknowledgement, or ack, to say that the work is done. Only then is the message removed.
Between the delivery and the ack the message is in flight. The queue needs a rule for what to do if the ack never comes. There are two common designs.
In the first, the queue watches the consumer's connection. RabbitMQ works this way: its documentation says that any delivery that was not acknowledged is put back in the queue automatically when its channel or connection closes, including when the TCP connection is lost or the consumer process fails, and that it sets a redeliver flag on a repeat delivery. It also warns that a message may go to a different consumer from the first one, so consumers should be idempotent, which the next lesson explains.
In the second, the queue uses a clock. When a consumer receives a message, the queue hides it from every other consumer for a period called the visibility timeout. If the consumer deletes the message within that period, it is gone. If not, the message becomes visible again and the next request receives it. Amazon SQS uses this design. Its documentation gives a default timeout of 30 seconds, lets a consumer extend or shorten the timeout of one message, and sets a maximum of 12 hours from the first receipt.
The same page warns that, because SQS delivers at least once, a standard queue does not guarantee that a message is never delivered twice even inside the visibility timeout. The timeout makes duplicates rare, not impossible.
Both designs deliver a message again when the consumer does not finish. Neither can tell whether the consumer crashed before doing the work, crashed after doing it but before the ack, or is simply slow.
A broker with a visibility timeout
The broker below is a small model of the second design. It keeps a queue of ready messages and a table of messages in flight with their deadlines. receive first moves any expired in-flight message back to the ready queue. Each delivery returns a receipt that carries the number of the delivery, and ack is accepted only for the latest delivery. That last rule is a choice of this model, made so that a late ack from an older delivery cannot remove a newer one.
import time from collections import deque class Broker: def __init__(self, timeout): self.timeout, self.n = timeout, 0 self.ready, self.inflight = deque(), {} def send(self, body): self.n += 1 self.ready.append({"id": self.n, "body": body, "receives": 0}) def receive(self): now = time.monotonic() for mid, (msg, deadline) in list(self.inflight.items()): if now >= deadline: # timeout expired: visible again self.ready.append(self.inflight.pop(mid)[0]) if not self.ready: return None msg = self.ready.popleft() msg["receives"] += 1 self.inflight[msg["id"]] = (msg, now + self.timeout) return dict(msg) # the caller's receipt def ack(self, receipt): # True only for the latest receipt held = self.inflight.get(receipt["id"]) if held and held[0]["receives"] == receipt["receives"]: del self.inflight[receipt["id"]] return True return False
l2_broker.py: ready queue, in-flight table, receipts
The run has two cases. In the first, consumer A takes a message and crashes. In the second, consumer A is alive but slow: it needs 0.5 s for a message while the timeout is 0.3 s.
import time from l2_broker import Broker t0 = time.monotonic() def log(text): print(f"{(time.monotonic() - t0) * 1000:5.0f} ms {text}") b = Broker(timeout=0.3) b.send("charge order 17") m = b.receive() log(f"consumer A gets {m['body']!r}, receive #{m['receives']}") log("consumer A crashes before acking") log(f"queue offers it now? {b.receive()}") time.sleep(0.35) m = b.receive() log(f"consumer B gets it, receive #{m['receives']}") log(f"consumer B acks in time: {b.ack(m)}") b.send("resize photo 9") # a slow consumer m = b.receive() log(f"consumer A gets {m['body']!r}, takes 0.5 s") time.sleep(0.35) m2 = b.receive() log(f"consumer B also gets it, receive #{m2['receives']}") time.sleep(0.15) log(f"consumer A acks in time: {b.ack(m)}") log(f"consumer B acks in time: {b.ack(m2)}")
l2_run.py: a crash, then a slow consumer
Choosing the timeout
The second case is the common failure. The timeout was shorter than the real processing time, so every slow message produced a duplicate. Set the timeout above the time that your slowest normal message needs, with room to spare. The SQS documentation suggests starting from the maximum time your application typically needs to process and delete a message, and notes that extending a message's timeout does not reset the 12-hour limit.
A very long timeout has its own cost: after a real crash, the message stays hidden for the whole period, and the retry is delayed. The documentation says as much, that a timeout set too high delays the reappearance of unprocessed messages. For work with a wide range of durations, the answer is a short timeout and a heartbeat. The consumer extends the timeout of its message every few seconds while it is still working, so a crash is noticed after one short period, and a long job is not interrupted.
Whatever you choose, treat a redelivery as normal. Timeouts, crashes and network failures all produce it, and the next lesson shows how to make it harmless.
In the run, why did consumer B receive the message after consumer A crashed?
- A never acknowledged it, so after the 0.3 s visibility timeout the broker made it visible again.
- B saw it as receive number 2.
In the second case consumer A was healthy. Why did the message still go to B?
- A needed 0.5 s but the timeout was 0.3 s, so the broker assumed A had failed.
- The remedy is a timeout above the normal processing time, or a heartbeat that extends it.
What is the cost of a very long visibility timeout?
- After a real crash, the message stays hidden for the whole period, so the retry is late.
- A short timeout with a heartbeat avoids both problems.
Part 3 · Delivery semantics and idempotent consumers
At most once, at least once, exactly once
Because an ack can be lost, a queue has to choose what to do when it is unsure. Three promises are possible. At-most-once delivery never delivers a message twice, but a message can be lost. At-least-once delivery never loses a message, but a message can arrive more than once. Exactly-once delivery would mean that each message is processed one time and no more.
The Kafka documentation describes the first two in terms of what the clients do. Messages are at-least-once by default. At-most-once is possible if producer retries are turned off and consumers commit their position before they process a batch, since a crash then skips the batch. The same page says that exactly-once is supported inside Kafka, through a transactional producer and a consumer that reads only committed data, and in Kafka Streams. It also warns that other systems on the destination side have to cooperate, and that some exactly-once claims are misleading when producers or consumers fail.
The reason for caution is the lost ack. Suppose a consumer charges a card and the ack is lost on the way back. The queue cannot know whether the work was done, so it either risks losing the message, which is at-most-once, or sends it again, which is at-least-once. No broker can avoid that choice between two independent systems.
Most production systems choose at-least-once and make the consumer safe to repeat. A consumer is idempotent if processing the same message twice has the same effect as processing it once. At-least-once delivery combined with an idempotent consumer is often called effectively once.
Making a consumer idempotent
There are three standard ways. The best is to make the operation naturally idempotent: setting a status to shipped can be repeated safely, while adding 1 to a counter cannot. Second, keep a table of processed message ids and skip any id you have seen. Third, use a conditional update that applies only if the row is still in the state the message expects.
The table of ids works for anything, but only if the check and the work are one transaction. If the consumer records the id and then crashes before doing the work, the message is skipped forever. If it does the work and then crashes before recording, the work is repeated. Putting both in one database transaction makes them succeed or fail together. The message id here does the job of the idempotency key from the core concepts chapter: a label for one intended action that stays the same on every repeat. So the producer must give each message a stable id, such as an order number, not a random value generated at each attempt.
Watch for the second delivery of m1: the queue has not heard an ack for it
Read it as steps
The first consumer charges the order and crashes before it acknowledges. The message comes back and the repeat is skipped.
The scene shows the idea. Consumer A did its work and recorded the message, then crashed before the ack. Consumer B received the repeat, saw the message in the done list and acknowledged without charging.
The double charge, run
The program below makes the loss visible. A wallet starts at 1,000. The broker delivers a message for 500, then one for 300, then the first one again because its ack was lost. The naive consumer subtracts every time. The idempotent consumer inserts the message id into a table with a primary key, in the same transaction as the update, and treats a duplicate key as a sign that the work is done.
import sqlite3 # What the broker delivers: m1's ack was lost, so m1 comes twice. deliveries = [("m1", 500), ("m2", 300), ("m1", 500)] def naive(): balance = 1000 for msg_id, amount in deliveries: balance -= amount # charge, every time return balance def idempotent(): db = sqlite3.connect(":memory:") db.execute("CREATE TABLE wallet (balance INTEGER)") db.execute("INSERT INTO wallet VALUES (1000)") db.execute("CREATE TABLE done (msg_id TEXT PRIMARY KEY)") for msg_id, amount in deliveries: try: with db: # one transaction db.execute("INSERT INTO done VALUES (?)", (msg_id,)) db.execute("UPDATE wallet SET balance = balance - ?", (amount,)) except sqlite3.IntegrityError: print(f" {msg_id} already processed, skipped") return db.execute("SELECT balance FROM wallet").fetchone()[0] print("charged 500 + 300 = 800, so the balance should be 200") print("naive consumer: ", naive()) print("idempotent consumer:") print(" balance ", idempotent())
l3_dedupe.py: the same deliveries, two consumers
It was run with Python 3.12.10, using the SQLite that ships with it.
charged 500 + 300 = 800, so the balance should be 200 naive consumer: -300 idempotent consumer: m1 already processed, skipped balance 200
The two payments should leave 200. The naive consumer charged order m1 twice and ended at minus 300, a balance that no customer action produced. The idempotent consumer skipped the repeat and ended at 200. The database enforced the rule: the primary key on the message id made the second insert fail, so the whole transaction rolled back and the balance was not touched.
The cost is a table that grows with every message. Keep ids for as long as a redelivery can happen, and delete older ones. Stripe, for example, states in its API documentation that for version 1 of its API, stored idempotency keys may be removed after at least 24 hours. Pick a window that is longer than your queue's longest retry period.
Part 4 · Ordering and partitions
Order is not free
A single queue with a single consumer delivers messages in the order they were added. As soon as there are several consumers, order is lost: two consumers take two messages at the same time, and the one that gets the earlier message can finish later. For many jobs that is fine. For others it breaks things. If an order is created, paid and shipped, then a consumer that processes shipped before paid is wrong.
The usual answer is to partition the queue. A partition is one ordered sub-queue. A message goes to a partition by a rule, and one consumer reads each partition. The rule that preserves order is to hash a partition key, such as an order number, so that all messages with the same key land in the same partition. Messages for one order stay in order. Messages for different orders can be processed in parallel.
The Kafka documentation states this design. Each partition is totally ordered. The producer chooses the partition, either at random or by hashing a key, and records with the same key go to the same partition. Each partition is consumed by exactly one consumer in a consumer group at any time. Amazon SQS FIFO queues give the same effect with a message group id: messages with the same group id are processed in sequence, and while one message of a group is in flight the later ones are not handed out.
Per-key order, run
The program below produces three steps for each of four orders, interleaved: all the created events, then all the paid events, then all the shipped ones. It assigns them to three partitions first by a hash of the order number and then by round robin. The three partitions have consumers of different speeds, 10, 25 and 40 ms per message. The finish times are simulated, so the run is exactly repeatable.
import zlib from collections import defaultdict STEPS = ["created", "paid", "shipped"] KEYS = ["order-1", "order-2", "order-3", "order-4"] events = [(k, s) for s in STEPS for k in KEYS] # in produced order SPEED_MS = [10, 25, 40] # ms per message, per partition def consume(assign): parts = defaultdict(list) for i, (key, step) in enumerate(events): parts[assign(i, key)].append((key, step)) done = [(n * SPEED_MS[p], p, ev) # simulated finish time for p, ms in parts.items() for n, ev in enumerate(ms, 1)] return parts, [ev for _, _, ev in sorted(done)] def label(ev): # order number + first letter of the step return ev[0][-1] + ev[1][0]
l4_partitions.py, part 1: producing and consuming
def in_order(finished): seen = defaultdict(list) for key, step in finished: seen[key].append(step) return all(v == STEPS for v in seen.values()) rules = {"by key": lambda i, key: zlib.crc32(key.encode()) % 3, "round robin": lambda i, key: i % 3} for name, rule in rules.items(): parts, finished = consume(rule) print(f"{name}: per-key order kept = {in_order(finished)}") for p in sorted(parts): print(f" partition {p}:", *map(label, parts[p])) print(" finished :", *map(label, finished))
l4_partitions.py, part 2: the check and the two rules
It was run with Python 3.12.10. In the output, each message is shown as the order number and the first letter of its step, so 2p is order 2 paid.
by key: per-key order kept = True partition 0: 2c 2p 2s partition 1: 1c 1p 1s partition 2: 3c 4c 3p 4p 3s 4s finished : 2c 2p 1c 2s 3c 1p 1s 4c 3p 4p 3s 4s round robin: per-key order kept = False partition 0: 1c 4c 3p 2s partition 1: 2c 1p 4p 3s partition 2: 3c 2p 1s 4s finished : 1c 4c 2c 3p 2s 3c 1p 4p 2p 3s 1s 4s
With the key hash, order 2 went to partition 0, order 1 to partition 1, and orders 3 and 4 to partition 2. Each order's steps stayed in one partition, so they finished as created, paid, shipped. The overall finish order mixes the orders, with 2p finishing before 1c, but that does no harm: no single order was processed out of sequence.
What partitions cost
Partitions buy parallelism and per-key order, and take away two things. There is no order across keys, only within one, so a design that needs a global order has to use a single partition and a single consumer, which limits throughput to what one consumer can do.
The number of partitions also limits parallelism. In Kafka, a partition is read by only one consumer in a group, so a topic with four partitions can keep four consumers busy and no more. A hot key is a second limit: all messages for one key go to one partition, so a very busy key can saturate one consumer while the rest are idle.
Choose the key by the order you need. For an order's lifecycle it is the order number. For a user's actions it is the user id. For work with no ordering needs, no key at all gives the most even spread. Changing the number of partitions later moves keys between partitions, and during that change the order of a key's messages can be disturbed, so pick the count with room to grow.
Why can several consumers on one queue process messages out of order?
- Two consumers take two messages at once, and the one with the earlier message can finish later.
- Order is kept only if related messages go to the same single consumer.
In the run, what did the key hash do that round robin did not?
- It sent all steps of one order to the same partition, so each order was processed as created, paid, shipped.
- With round robin, order 3 was paid before it was created.
What is the cost of ordering by key?
- No order across different keys, and a hot key can overload the single consumer of its partition.
- Parallelism is also capped by the number of partitions.
Part 5 · Retries, backoff with jitter and dead-letter queues
When processing fails
A consumer can fail for two kinds of reason. A transient failure goes away if you wait: a database is restarting, a downstream service is slow, a network call times out. A permanent failure never goes away: the message is malformed, refers to a record that does not exist, or hits a bug. Retrying helps with the first kind and wastes time on the second.
For transient failures, retry, but not at once and not forever. A backoff policy waits longer after each failure, usually doubling the wait up to a cap. The cap stops the delay growing without limit. Backoff protects the thing that is failing, because the retry load goes down while it recovers.
Backoff alone has a flaw. If a thousand clients fail at the same moment, they all wait the same 200 ms, then the same 400 ms, and retry together every time. The failing service sees a wall of requests at each step. Jitter fixes that by adding randomness. The AWS Builders' Library article on timeouts, retries and backoff says that jitter spreads retries around in time, and that without it, calls that back off to the same time can overload the system again when they retry together. The article gives no formula. Here, full jitter means our own rule: each client waits a random time between zero and the capped exponential value.
Backoff and jitter, run
The program below makes a thousand clients fail at time zero. Each retries four times. Without jitter the wait before retry n is 0.1 s times 2 to the n, so 0.2, 0.4, 0.8 and 1.6 s. With full jitter, each wait is a random value between 0 and that figure. The program counts the most retries that fall into any single 50 ms window.
import random from collections import Counter BASE, CAP, CLIENTS, BUCKET = 0.1, 5.0, 1000, 0.05 rng = random.Random(3) def schedule(jitter): """Retry times for each client, all of whom failed at t=0.""" times = [] for _ in range(CLIENTS): t, row = 0.0, [] for attempt in range(1, 5): ceiling = min(CAP, BASE * 2 ** attempt) # 0.2 0.4 0.8 1.6 t += rng.uniform(0, ceiling) if jitter else ceiling row.append(t) times.append(row) return times print(f"busiest {BUCKET * 1000:.0f} ms window, {CLIENTS} clients") print("retry exponential exponential + full jitter") plain, jittered = schedule(False), schedule(True) for i in range(4): p = Counter(int(row[i] / BUCKET) for row in plain) j = Counter(int(row[i] / BUCKET) for row in jittered) print(f"{i + 1:>5} {max(p.values()):>13} {max(j.values()):>14}")
l5_backoff.py: retry times with and without jitter
It was run with Python 3.12.10, with a fixed random seed, so the counts repeat.
busiest 50 ms window, 1000 clients retry exponential exponential + full jitter 1 1000 260 2 1000 143 3 1000 71 4 1000 40
Without jitter every retry lands at the same instant: 1,000 in one window, each time. With jitter, the first retries spread out so that the busiest window held 260. By the fourth retry the busiest window had 40. The service sees a slope in place of a wall.
Retries also multiply load across layers. The same Builders' Library article gives an example: with five layers in a call stack and three retries at each layer, the database could see 3 to the power 5, or 243 times the load. Retry in one place, put a limit on retries, retry only operations that are idempotent, and do not retry errors that cannot succeed later.
Dead-letter queues
Permanent failures need a different ending. A poison message is one that fails every time it is tried. If the queue puts it back each time, it cycles forever and can block the work behind it. The standard fix is a dead-letter queue (DLQ): a separate queue to which the broker moves a message after a set number of failed attempts. The main queue goes on. People, or a repair job, inspect the dead letters later.
The program below keeps a count of attempts for each message. A message that fails three times goes to the dead-letter list.
from collections import deque MAX_RECEIVES = 3 queue = deque([("order-1", 0), ("poison", 0), ("order-2", 0)]) dead_letters = [] def handle(body): if body == "poison": raise ValueError("cannot parse message") print(f" processed {body}") while queue: body, receives = queue.popleft() try: handle(body) except ValueError as err: receives += 1 if receives >= MAX_RECEIVES: print(f" {body}: failed {receives} times, to the DLQ") dead_letters.append((body, str(err))) else: print(f" {body}: failed ({err}), try {receives + 1}") queue.append((body, receives)) # back of the queue print("main queue empty; dead letters:", dead_letters)
l5_dlq.py: a poison message and a limit of three attempts
processed order-1 poison: failed (cannot parse message), try 2 processed order-2 poison: failed (cannot parse message), try 3 poison: failed 3 times, to the DLQ main queue empty; dead letters: [('poison', 'cannot parse message')]
The good messages were processed on the way past, and the poison message failed three times and then left the queue. Real brokers support this directly. The RabbitMQ documentation says that a message rejected with requeue off goes to a dead letter exchange if one is configured, and is otherwise discarded. The SQS documentation recommends configuring a dead-letter queue for messages that fail after several attempts so that they do not circulate in the main queue. In SQS the limit is a count of receives, set on the queue's redrive policy as maxReceiveCount.
Two habits keep a DLQ useful. Alert on its depth, because a growing DLQ means something broke. And keep the original message intact with the error, so that the fix and a replay into the main queue are possible. Be careful on an ordered queue: once one message for a key moves to the DLQ, the later messages for that key go ahead without it, so per-key order is broken. The SQS documentation warns against a DLQ on a FIFO queue when the exact order matters.
Part 6 · Back-pressure, scaling consumers and durability
Scaling consumers
When the depth keeps rising, the first remedy is more consumers on the same queue, which is called the competing consumers pattern: each message goes to one of them, so the work is shared. Adding consumers helps only if the consumers are the bottleneck. If they all depend on one slow database, more of them make that database slower.
The program below measures it on this machine. A producer tries to add 100 messages a second to a queue for three seconds. Each consumer does 20 ms of work per message, which is at most 50 a second. It runs with one, two and four consumers and samples the depth every half second.
import queue import threading import time stop = threading.Event() def worker(q, done): while not stop.is_set(): try: q.get(timeout=0.05) except queue.Empty: continue time.sleep(0.02) # 20 ms of work: 50 a second done[0] += 1 def producer(q, put): # tries for 100 messages a second nxt = time.monotonic() while not stop.is_set(): q.put("job") # blocks when the queue is full put[0] += 1 nxt += 0.01 time.sleep(max(0, nxt - time.monotonic()))
l6_pipeline.py, part 1: a worker and a producer
def run(consumers, maxsize=0, seconds=3.0): stop.clear() q, done, put = queue.Queue(maxsize), [0], [0] jobs = [(worker, (q, done))] * consumers + [(producer, (q, put))] for fn, args in jobs: threading.Thread(target=fn, args=args, daemon=True).start() depths = [] for _ in range(int(seconds / 0.5)): time.sleep(0.5) depths.append(q.qsize()) # sample the backlog stop.set() return depths, put[0], done[0]
l6_pipeline.py, part 2: run and sample the depth
from l6_pipeline import run print("consumers depth every 0.5 s produced finished") for n in (1, 2, 4): d, p, f = run(n) print(f"{n:>9} {str(d):<22} {p:>8} {f:>9}") d, p, f = run(1, maxsize=20) print("one consumer, queue limited to 20 messages:") print(f" depth {d}") print(f" produced {p}, finished {f}")
l6_run.py: one, two and four consumers, then a limited queue
It was run with Python 3.12.10. The numbers vary a little on every run, on this machine, and the pattern does not.
consumers depth every 0.5 s produced finished 1 [25, 52, 76, 102, 128, 152] 301 148 2 [1, 2, 2, 4, 3, 5] 300 293 4 [0, 0, 0, 0, 0, 0] 300 298 one consumer, queue limited to 20 messages: depth [20, 20, 20, 20, 20, 20] produced 169, finished 148
What the depth shows
With one consumer, the depth climbs by about 25 every half second, from 25 to 152, because the producer adds 100 a second and the consumer finishes about 49. It finished 148 messages while 301 were produced. With two consumers the capacity is about 100 a second, which is just enough, and the depth stayed in single digits. With four consumers the depth was zero in every sample, and they finished 298 of the 300 produced, the rest being in their hands at the end of the run.
The last case limits the queue to 20 messages. Once it is full, the producer's put blocks, so the producer slows to the consumer's pace: it produced 169 messages, not 300, and the depth stayed at 20. This is back-pressure: the slowness of the consumer travels back to the producer through the limit, so the queue does not grow without bound and run out of memory. The producer must then decide what to do while it waits. Options are to make the user wait, to reject new work with an error such as HTTP 429, to drop the least important messages, or to spill to disk. Choose on purpose, because a full queue that nobody planned for fails in an unplanned way.
A queue that scales its workers automatically usually does so from the depth or from the age of the oldest message. Set a maximum, so that a flood does not start hundreds of workers that overload the database behind them.
Durability
A queue is only useful if it keeps messages through a crash. An in-memory queue loses everything when its process dies. A durable queue writes messages to disk and, in a cluster, copies them to other machines before it confirms to the producer.
Kafka's documentation describes one way. Each partition has a leader and followers. A message is committed once it is replicated to all in-sync replicas, and committed messages are not lost while at least one in-sync replica stays alive. The producer chooses how many acknowledgements to wait for, 0, 1 or all, which trades speed against safety. The page also says that Kafka does not require an fsync on every write. RabbitMQ's publisher confirms work in a similar way: for persistent messages on durable queues the confirm comes after the message is written to disk, and for quorum queues after a quorum of the replicas has accepted it.
So there are two acks in a queue's life. The producer's ack says that the broker has the message safely. The consumer's ack says that the work is done. Both can be lost, which is why the earlier lessons make messages repeatable.
| Term | Meaning |
|---|---|
| Producer, consumer | The side that adds messages, and the side that takes and handles them |
| Ack | A consumer's note that a message was handled and can be removed |
| Visibility timeout | How long a delivered message stays hidden before it is offered again |
| Idempotent | Safe to apply twice, with the same result as once |
| Partition key | The value whose hash picks the partition and so fixes the order |
| Dead-letter queue | Where messages go after too many failed attempts |
| Back-pressure |