Sub topic 4
Topics versus queues: fan-out and competing consumers
This chapter assumes you know what an event is, what producers and consumers do, and what a broker provides. You should also be comfortable with HTTP request/response APIs and basic database transactions. The chapter covers the two delivery models most brokers offer, publish/subscribe topics and work queues, and how to choose between them.
Two questions a broker answers
When a producer sends a message, the broker has to decide two things:
- Which consumers receive a copy of it?
- If several instances of the same consumer are running, which instance handles it?
Topics and queues answer these differently.
- A topic (publish/subscribe) delivers a copy of each message to every interested subscriber. This is fan-out.
- A work queue delivers each message to exactly one consumer among a group of workers. These workers are competing consumers, because they compete for the next message.
Real systems usually combine both. A topic fans out to several subscribers, and each subscriber reads from its own queue, with several worker instances competing on it.
Topics: fan-out
With a topic, the producer publishes an order_placed event and does not know who is listening. Each subscriber gets its own independent copy and processes it at its own pace.
The in-process bus below shows the idea. One event reaches two handlers, and the publisher knows about neither.
from collections import defaultdict
class EventBus:
def __init__(self):
self._handlers = defaultdict(list)
def subscribe(self, event_type, handler):
self._handlers[event_type].append(handler)
def publish(self, event_type, payload):
for handler in self._handlers[event_type]:
handler(payload)
bus = EventBus()
bus.subscribe("order_placed", lambda e: print("reserve stock for", e["order_id"]))
bus.subscribe("order_placed", lambda e: print("send receipt for", e["order_id"]))
bus.publish("order_placed", {"order_id": "o-1"})Adding a third subscriber, such as analytics, requires no change to the producer. This is the main benefit of fan-out.
This toy bus calls handlers one after another in the same process. A real broker does not. It stores a copy for each subscription, so a slow or failed subscriber does not block the others.
Work queues: competing consumers
A work queue spreads a stream of tasks across workers. Suppose image resizing takes two seconds per job and 100 jobs arrive per second. A single worker cannot keep up, so you run many instances reading from the same queue. The broker gives each message to one instance, so the work is shared and each job is done once.
The queue also gives you:
- Horizontal scaling. Add instances to raise throughput, and remove them when load drops.
- Load leveling. The queue absorbs bursts. Messages wait until a worker is free.
- Failure isolation. If a worker dies before acknowledging a message, the broker can give that message to another worker.
The last point matters for correctness. Because a message can be redelivered after a worker crash, a work queue normally gives at-least-once delivery. Consumers must therefore tolerate duplicates, which later chapters cover under idempotency.
Combining them: one queue per subscriber
A topic alone does not scale a subscriber, and a queue alone does not fan out. The usual design joins them. The producer publishes to a topic. Each subscribing service has its own queue (a subscription) attached to the topic. Within a service, instances compete for messages from that service's queue.
With this layout, every order reaches both inventory and billing exactly once per service (ignoring redelivery), and inventory can run two workers without double-reserving stock for the same message.
How common brokers name these ideas
The vocabulary differs between products, but the models map onto each other.
| Concept | Kafka | RabbitMQ | AWS SNS and SQS |
|---|---|---|---|
| Topic (fan-out) | Topic, read by many consumer groups | Fanout or topic exchange | SNS topic |
| Work queue | Partitions shared inside one consumer group | Queue with several consumers | SQS queue |
| Subscription unit | Consumer group | Queue bound to an exchange | SQS queue subscribed to SNS |
| Retention after read | Kept until retention expires | Removed after acknowledgment | Removed after delete or expiry |
Kafka differs most. A Kafka topic is a retained log. Each consumer group tracks its own position, and members of one group split the partitions between them, which gives competing-consumer behavior. A different group reads the same log independently, which gives fan-out. Because messages stay in the log, a new group can replay history. In RabbitMQ and SQS, a message is gone once it has been acknowledged.
Choosing between them
Ask what the message represents.
| Situation | Model | Reason |
|---|---|---|
| "Something happened, and several services care" | Topic with a queue per subscriber | Each service reacts independently |
| "This job must be done once, and load varies" | Work queue | Workers share the load |
| "Unknown future consumers may appear" | Topic | The producer needs no change |
| "Only one service should ever act on this" | Work queue | A topic adds no value |
Events usually suit topics, since they are facts that many parties may care about. Commands, such as "resize this image", usually suit queues, since one party must act on them.
Edge cases and common mistakes
Subscribing late. On a classic broker, a subscription only receives messages published after it exists. If a new service subscribes tomorrow, it misses today's events. A retained log such as Kafka lets it start from an earlier position. If you need history on another broker, you must provide it by other means, such as a snapshot.
Sharing one queue between different services. If inventory and billing read the same queue, they compete. Each order then goes to only one of them. This is a common misconfiguration. Different services need different queues.
Ordering breaks under competition. When several workers take messages from one queue, two messages for the same order can be handled at the same time, or in the wrong order. A slow worker can finish message 1 after a fast worker finishes message 2. If order matters per entity, use keys and partitions, which a later chapter covers. Otherwise, design handlers so that order does not matter.
Unbounded subscriptions. A queue for a stopped consumer keeps filling. Nothing fails visibly, but storage grows and a backlog waits when the consumer returns. Set retention limits and alert on queue depth.
Slow consumers and backlog. Fan-out isolates subscribers, but each one still needs enough capacity. Queue depth and message age are the main signals that a consumer is falling behind.
Poison messages. A message that always fails will be redelivered repeatedly and can block a worker or a partition. Retries and dead-letter queues, covered later, handle this.
Worked check
An online shop publishes order.placed. Three needs arise:
- Reserve stock. It runs on four instances and must not reserve twice for one order.
- Email a receipt. It runs on one instance.
- Update a sales dashboard. It may be added next month.
The design is one order.placed topic with three subscriptions, one each for inventory, email and the dashboard. The inventory queue has four competing workers. The dashboard subscription can be created later without touching the order service. Duplicates are still possible after a crash, so the stock reservation must be idempotent.
Exercise
A team has an invoice.created topic. Both the accounting service and the notification service were set up to read from a single shared queue bound to that topic. Accounting reports that it sees only about half of the invoices, and notifications reports the same. What is wrong, and how do you fix it?
Show answer
The two services are competing consumers on one queue, so each message is delivered to only one of them. Give each service its own queue (subscription) bound to the topic. The topic then copies every invoice to both queues, and each service receives all invoices. Instances of the same service can then compete within their own queue.
Exercise
A resizing service must process each uploaded image once, and upload volume spikes during the day. Would you use a topic with many subscribers or a work queue, and why? What must the worker still handle?
Show answer
Use a work queue with competing consumers. Only one worker should resize each image, and the queue absorbs spikes while you add workers. The worker must still tolerate duplicates, because a crash before acknowledgment causes redelivery under at-least-once delivery, so resizing the same image twice should be harmless.