Publish-Subscribe Pattern
What you'll learn: How to implement pub-sub where multiple subscribers receive copies of events from a topic.
The Core Idea
The Publish-Subscribe (pub-sub) pattern is an event-driven messaging model where publishers send events to a topic without knowing who (if anyone) will receive them, and multiple subscribers can independently receive copies of the same event. Unlike queues where a single consumer processes each message, pub-sub ensures every interested subscriber gets their own copy.
Think of it like a newspaper subscription: when the publisher prints today's edition, every subscriber receives their own copy. The publisher doesn't need to know who the subscribers are, and subscribers don't need to coordinate with each other.
How It Works
- Publisher sends an event to a topic (a named channel)
- The topic maintains a list of subscriptions
- Each subscription delivers a copy of the event to its subscriber
- Multiple subscribers process the same event independently and simultaneously
This differs from the queue pattern you've learned: queues distribute work (one message → one consumer), while pub-sub broadcasts information (one message → many consumers).
When to Use Pub-Sub
- Broadcasting system-wide notifications (user signup, payment processed)
- Triggering multiple independent workflows from one event
- Real-time data distribution to multiple services
- Building loosely coupled microservices that react to shared events
For example, when a user completes an order, you might publish an "OrderCompleted" event that triggers email notifications, inventory updates, analytics recording, and shipping workflows—all independently.
Key Takeaway: The publish-subscribe pattern enables one-to-many event distribution where multiple subscribers each receive their own copy of every event published to a topic, allowing independent parallel processing without coordination between consumers.