AI Hints
Home›System Design Tutorial›Async and Queues
System Design · Lesson 66 of 120

Pub/Sub

One message, many listeners.

⏱ 2 min read▶ Video at 1:18:53🎓 Free
Watch this lesson in the System Design courseWatch on YouTube ↗Full System Design course

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.

Pub/Sub
From the video: Pub/Sub
  • 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.

pubsub.pypython
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})
Output
     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
Next up: Kafka and Logs — an ordered history