Message Queues and Pub/Sub
A message queue lets one part of a system hand work to another without waiting for it. The producer puts a message on the queue and moves on; a consumer takes it off later and processes it. This decoupling in time is one of the most useful tools in system design.
web server --(enqueue "resize photo 42")--> [ queue ] --> worker 1
web server --(enqueue "resize photo 43")--> [ ] --> worker 2
returns "202 Accepted" immediately (process at their own pace)Why queues help
| Benefit | Example |
|---|---|
| Fast responses | Upload returns at once; thumbnails are generated in the background |
| Load levelling | A burst of 10,000 orders is drained steadily by 20 workers instead of overwhelming the database |
| Fault isolation | If the email service is down, messages wait in the queue instead of failing the checkout |
| Independent scaling | Add workers when the queue grows, remove them when it's empty |
| Fan-out | One "order placed" event feeds billing, shipping and analytics |
Load levelling, simulated
Traffic arrives in a burst; workers drain a fixed number of jobs per second. The queue absorbs the difference:
from collections import deque
arrivals = [50, 400, 600, 300, 100, 50, 0, 0, 0, 0] # jobs arriving each second
WORKERS, PER_WORKER = 4, 60 # each worker: 60 jobs/s
queue, done = deque(), 0
print("sec arrived processed queue depth")
for second, n in enumerate(arrivals):
queue.extend(range(n))
capacity = WORKERS * PER_WORKER
processed = min(capacity, len(queue))
for _ in range(processed):
queue.popleft()
done += processed
print(f"{second:3} {n:8} {processed:10} {len(queue):12}")
print("total processed:", done)sec arrived processed queue depth
0 50 50 0
1 400 240 160
2 600 240 520
3 300 240 580
4 100 240 440
5 50 240 250
6 0 240 10
7 0 10 0
8 0 0 0
9 0 0 0
total processed: 1500
Without the queue, 1,500 jobs arriving at up to 600 per second would have needed 10 workers or been rejected. With it, 4 workers finish everything a few seconds later. Queue depth (or the age of the oldest message) is the metric to watch and autoscale on.
Delivery guarantees
| Guarantee | Meaning | How |
|---|---|---|
| At most once | A message may be lost, never duplicated | Acknowledge before processing |
| At least once | Never lost, may be delivered twice | Acknowledge after processing; redeliver on timeout |
| Exactly once | Each message has effect once | At-least-once + idempotent processing or transactions |
Most queues (SQS, RabbitMQ, Kafka consumers) give at-least-once delivery. A worker that crashes after doing the work but before acknowledging causes a redelivery. So consumers must be idempotent: processing the same message twice must have the same effect as once.
from collections import deque
class Queue:
def __init__(self, visibility_timeout=3):
self.ready, self.in_flight, self.timeout = deque(), {}, visibility_timeout
def send(self, msg):
self.ready.append(msg)
def receive(self, now):
for msg_id, (msg, deadline) in list(self.in_flight.items()):
if deadline <= now: # not acked in time -> redeliver
del self.in_flight[msg_id]
self.ready.append(msg)
if not self.ready:
return None
msg = self.ready.popleft()
self.in_flight[msg["id"]] = (msg, now + self.timeout)
return msg
def ack(self, msg_id):
self.in_flight.pop(msg_id, None)
q = Queue()
q.send({"id": "pay-1", "amount": 30})
q.send({"id": "pay-2", "amount": 12})
processed_ids, balance = set(), 0
timeline = [(0, "crash"), (1, "ok"), (4, "ok"), (5, "ok")] # the first worker dies after charging
for now, outcome in timeline:
msg = q.receive(now)
if msg is None:
print(f"t={now}: queue empty")
continue
if msg["id"] in processed_ids:
print(f"t={now}: {msg['id']} is a duplicate, skipped")
else:
balance += msg["amount"]
processed_ids.add(msg["id"])
print(f"t={now}: charged {msg['id']} ({msg['amount']}), balance {balance}")
if outcome == "ok":
q.ack(msg["id"])
else:
print(f"t={now}: worker crashed before ack")
print("final balance:", balance)t=0: charged pay-1 (30), balance 30
t=0: worker crashed before ack
t=1: charged pay-2 (12), balance 42
t=4: pay-1 is a duplicate, skipped
t=5: queue empty
final balance: 42
The processed_ids set is the deduplication that turns at-least-once delivery into exactly-once effects. In production it lives in a database, often in the same transaction as the work itself.
Point-to-point vs publish/subscribe
Point-to-point (work queue) Publish / subscribe (topic)
producer -> [queue] -> one of the producer -> [topic] -> every subscriber gets a copy
workers |-> billing
|-> email
|-> analyticsIn pub/sub, each subscriber group receives every message. Kafka models this with a log: messages are appended to partitions and kept for days; each consumer group just remembers its own offset, so new consumers can even replay history.
class Topic:
def __init__(self):
self.log = [] # append-only
self.offsets = {} # consumer group -> next index to read
def publish(self, event):
self.log.append(event)
def poll(self, group, max_events=10):
start = self.offsets.get(group, 0)
events = self.log[start:start + max_events]
self.offsets[group] = start + len(events)
return events
orders = Topic()
for i in range(1, 4):
orders.publish(f"order-{i}")
print("billing :", orders.poll("billing"))
print("shipping :", orders.poll("shipping", max_events=2))
orders.publish("order-4")
print("billing :", orders.poll("billing"))
print("shipping :", orders.poll("shipping"))
print("analytics (new, replays everything):", orders.poll("analytics"))billing : ['order-1', 'order-2', 'order-3']
shipping : ['order-1', 'order-2']
billing : ['order-4']
shipping : ['order-3', 'order-4']
analytics (new, replays everything): ['order-1', 'order-2', 'order-3', 'order-4']
Ordering, partitions and dead letters
- Kafka keeps order within a partition only. Use a partition key (for example the order id) so all events of one entity stay in order.
- A message that fails again and again (a "poison pill") must not block the queue forever: after N attempts, move it to a dead-letter queue for inspection.
- Backpressure: if consumers can't keep up for long, the queue grows without bound. Alert on queue age, autoscale consumers, or shed load at the producer.
| RabbitMQ / SQS | Kafka / Pulsar / Kinesis | |
|---|---|---|
| Model | Queue: a message is gone once acknowledged | Log: messages kept for a retention period |
| Consumers | Compete for messages | Each group reads at its own offset |
| Replay | No | Yes |
| Best for | Task queues, RPC-style jobs | Event streams, high throughput, many subscribers |
Test yourself
With at-least-once delivery, what must consumers be?
- Stateless
- Idempotent
- Single-threaded
- Synchronous
In the queue model, why was pay-1 delivered a second time at t=4?
- The producer sent it twice
- The worker crashed before acknowledging, so the visibility timeout expired
- The queue was full
- Kafka replays all messages
What lets a new Kafka consumer group process events published before it existed?
- Dead-letter queues
- Messages are kept in a log and each group tracks its own offset
- Visibility timeouts
- Round-robin delivery