Pub/Sub
One message, many listeners.
A queue gives each message to one worker. But when an order is placed, several services care. The email service, the warehouse, and analytics. Publish subscribe, or pub sub, gives each of them a copy.

- Queue: one worker
- Many services care
- Pub/sub: everyone gets a copy
One event, many subscribers
In pub sub, the publisher sends a message to a topic, like order placed. Each subscriber registers interest in the topic, and gets its own copy. Run it. One published event reaches three different services. And the checkout service doesn't even know who's listening.
subscribers = {}
def subscribe(topic, name):
subscribers.setdefault(topic, []).append(name)
def publish(topic, message):
for name in subscribers.get(topic, []):
print(f"{name:>10} got: {message}")
subscribe("order.placed", "email")
subscribe("order.placed", "warehouse")
subscribe("order.placed", "analytics")
publish("order.placed", {"order": 7, "total": 30}) email got: {'order': 7, 'total': 30}
warehouse got: {'order': 7, 'total': 30}
analytics got: {'order': 7, 'total': 30}Queue vs pub/sub
So when do you use which? A queue shares work. Each job is done once, by one of many identical workers. Pub sub broadcasts news. Each subscriber gets every message, and does its own thing with it. Many systems combine them, with each subscriber reading its copy from its own queue.
Queue
- Shares workEach job done onceIdentical workers
Pub/sub
- Broadcasts eventsEvery subscriber gets itDifferent services
Summary
Pub sub sends each message to every subscriber of a topic. Use queues to share work, and pub sub to broadcast events. Next, a special kind of message system. Kafka.
Key takeaways- Publish to a topic
- Every subscriber gets a copy
- Publisher doesn't know who