23. Pub/Sub and Fan-Out
1
The picture to keep in your head2
23.1 What's the difference between a queue and pub/sub?3
23.2 What are topics and subscribers?4
23.3 What are consumer groups?5
23.4 What are the fan-out strategies?6
23.5 What is event-driven architecture?7
23.6 How do you handle duplicates and ordering?8
23.7 How do you publish events reliably (the outbox pattern)?9
Memory card and where the analogy breaks10
Practice: five levels11
Interview questions12
Solutions13
Sources14
Code lab23. Pub/Sub and Fan-Out
23.1 What's the difference between a queue and pub/sub?
3 min read+10 XP
On the paper round: A job board says "someone please fix the leaking tap": one plumber goes, not five. A newspaper says "the budget was announced": every subscriber should read it.
In the system:
- Queue (Chapter 22): each message goes to one consumer. Workers share the work. "Send this SMS" should happen once.
- Pub/sub: each message goes to every subscriber. "Order 881 was placed" matters to the SMS service, the loyalty service and analytics, and each needs its own copy.
Figure: same message, two delivery patterns: shared work vs shared news.
The distinction is about intent:
- A command ("send SMS for order 881") belongs on a queue: it names one job for one handler.
- An event ("order 881 was placed") belongs on a topic: it states a fact, and anyone interested can react.
Most brokers support both. Google Pub/Sub, Amazon SNS and Kafka topics are pub/sub; SNS is often combined with one SQS queue per subscriber, which gives every subscriber both its own copy and queue features like retries and DLQs.
Memory code: "A job goes to one plumber; the news goes to every subscriber."