Skip to content

System Design

Pub/Sub (Publish–Subscribe)

O(s) time per publish, where s is the number of subscribers on that topic. Each subscriber gets one delivery.

The idea, in plain English

Pub/Sub works like a radio station. The station (the publisher) broadcasts on a channel (a 'topic'). It doesn't know or care who's listening. Anyone tuned in (a subscriber) hears the broadcast. The publisher never talks directly to the listeners. A middleman (the 'broker') delivers the message to everyone who subscribed to that channel.

How it works

  1. 1Subscribers register interest in a topic by name — for example, 'orders'.
  2. 2A publisher sends a message to a topic. It doesn't know or care who — or how many services — are subscribed.
  3. 3The broker looks up every subscriber for that topic. It delivers a copy of the message to each one.

When you'd use it

Use pub/sub when one event needs to trigger several unrelated things, without those things knowing about each other. For example, a new order should notify billing, email, and shipping — but the order-placing code shouldn't need to know the details of all three.

Common beginner mistakes

  • Having the publisher call each subscriber directly, instead of going through a topic. That tightly links services together — exactly what pub/sub is meant to avoid.
  • Assuming a topic with no subscribers is an error. Often it's completely fine for nobody to be listening yet.

Try it — edit and run

Click the code to edit · press ⌘/Ctrl+↵ to run

Editable code. Tab and Shift+Tab indent. Press Escape, then Tab, to move focus out of the editor.

Expected output — hit Run to try it
billing-service: [orders] Order #101 placed | [orders] Order #102 placed
email-service: [orders] Order #101 placed | [shipping] Order #101 shipped | [orders] Order #102 placed

Not sure this is the right topic? See the learning paths → or where this leads →