Pub/Sub
A messaging pattern where publishers emit events to topics and subscribers receive them without knowing each other. It decouples producers from many consumers. Redis Pub/Sub, Google Pub/Sub, SNS, and NATS implement it.
- Event notification to many independent consumers.
- Decoupling producers from unknown downstreams.
- Work distribution (one message → one worker) — use a queue.
- When you need guaranteed delivery to offline subscribers (use durable).
Definition
Publishers send messages to a topic/channel; the broker fans them out to all subscribers. Subscribers come and go independently. Contrast with a queue (one consumer per message).
Why it exists
To let many independent consumers react to the same events without the producer knowing who they are. It's the basis of event-driven decoupling.
How it works
Publisher → topic → broker → all subscribers. Redis Pub/Sub is fire-and-forget (no persistence); Google Pub/Sub and SNS persist and retry; NATS offers both. Subscribers acknowledge; unacked messages are redelivered (in durable variants).
Scaling limits
Fire-and-forget variants lose messages if a subscriber is offline. Fan-out multiplies broker load. Ordering across subscribers isn't guaranteed. Durable variants add retention and ack overhead.
Cost shape
Per-message + throughput. Blow-ups: huge fan-out to many subscribers and long retention.
Alternatives
- Queue — One consumer per message, load balancing.
- Kafka log — Durable fan-out with replay, heavier.
Failure modes
- Fire-and-forget losing messages to offline subscribers.
- Slow subscriber causing backpressure to all.
- Unbounded fan-out.