Pub-Sub Pattern Fundamentals
What you'll learn: How publishers send messages to topics, allowing multiple subscribers to receive independent copies of each message.
Core Idea
The publish-subscribe (pub-sub) pattern is a messaging model where message producers (publishers) don't send messages directly to specific consumers. Instead, they publish messages to named topics. Multiple consumers (subscribers) can independently subscribe to these topics and receive their own copy of every message published.
This differs from the point-to-point queue pattern you learned previously. In a queue, each message is consumed by exactly one worker. In pub-sub, each message is copied and delivered to every active subscriber.
How It Works
Think of pub-sub like a newspaper subscription:
- The publisher is like a newspaper company that produces content
- The topic is like the newspaper title (e.g., "Tech Daily")
- Subscribers are readers who subscribe to that newspaper
- Each subscriber gets their own copy — reading doesn't prevent others from reading
When a publisher sends a message to a topic, the message broker:
- Identifies all active subscribers for that topic
- Creates a separate copy of the message for each subscriber
- Delivers copies independently to each subscriber's queue
Key Characteristics
- Fan-out: One published message reaches many subscribers
- Independence: Subscribers consume at their own pace without affecting others
- Dynamic subscriptions: Subscribers can join or leave without affecting publishers
- Topic-based routing: Messages are categorized by topic, not destination
Key Takeaway: Pub-sub enables one-to-many broadcast communication where publishers and subscribers are completely decoupled — publishers don't know who receives their messages, and subscribers don't know who published them.