Sub topic 4
Topics versus queues: fan-out and competing consumers
This chapter assumes you know what an event, a producer, a consumer and a broker are from the earlier chapters. It covers the two delivery models a broker offers and when to choose each.
Two questions a broker answers
When a producer sends a message, the broker has to decide who receives it. There are two answers, and most systems need both.
- Fan-out: every interested party gets its own copy.
- Competing consumers: several workers share one stream, and each message goes to exactly one of them.
A topic (publish/subscribe) gives you fan-out. A work queue gives you competing consumers.
Topics: fan-out
A topic delivers each event to every subscription. The producer publishes order.placed once. Stock reservation, receipts and analytics each receive their own copy and process it at their own pace. Adding a fourth subscriber requires no change to the producer.
Each subscription keeps its own position and backlog. A slow analytics service falls behind without slowing down the receipt service.
Queues: competing consumers
A queue hands each message to one consumer. If receipt rendering is slow, you start more workers on the same queue. The broker spreads the messages across them, so throughput grows with the number of workers.
The trade-off is that workers on one queue are interchangeable. Any worker may get any message, so you can't assume one worker sees all messages for a customer. Per-key ordering needs partitioning, covered in the ordering chapter.
Combining them: consumer groups
Most brokers merge the two models. Kafka calls it a consumer group. In Amazon SNS with SQS, each subscriber has its own queue attached to a shared topic. The rule is:
- Between groups, the topic fans out. Every group gets every event.
- Inside a group, consumers compete. Each event goes to one member.
A runnable sketch
This in-process version has the same shape. Each group receives every event, and one member of the group handles it, chosen round-robin.
from collections import defaultdict
class Topic:
def __init__(self):
self._groups = defaultdict(list)
self._counts = defaultdict(int)
def subscribe(self, group, handler):
self._groups[group].append(handler)
def publish(self, event):
for group, handlers in self._groups.items():
index = self._counts[group] % len(handlers)
self._counts[group] += 1
handlers[index](event)
topic = Topic()
topic.subscribe("stock", lambda e: print("stock worker A:", e))
topic.subscribe("stock", lambda e: print("stock worker B:", e))
topic.subscribe("email", lambda e: print("email worker:", e))
for order_id in ("o-1", "o-2", "o-3"):
topic.publish(order_id)Running it shows email worker handling all three orders, while workers A and B alternate on the stock side.
Choosing between them
| Requirement | Use |
|---|---|
| Several independent services react to the same fact | Topic with one group per service |
| Spread heavy work across many workers | Queue, or many consumers in one group |
| Add a new reaction without touching the producer | Topic |
| One task must be done once, by any worker | Queue |
Common mistakes
- Two services sharing one group. They split the events, so each service sees only some of them. Give each service its own group or subscription.
- Expecting global order with many workers. Competing consumers can finish messages out of order.
- Forgetting duplicates. Both models usually deliver at least once, so consumers must be idempotent.
Exercise
A topic has one group named billing with three consumers. A new analytics service also needs every event. It joins the billing group to save setup effort. What goes wrong, and how do you fix it?
Show answer
Members of one group compete, so billing and analytics each receive only part of the events. Billing may miss events, and analytics sees an incomplete stream. Give analytics its own group, or its own subscription, so it receives every event independently.