What is the Pub-Sub Pattern?

Publish/subscribe is a messaging pattern where publishers emit messages on named topics (channels) and subscribers listen to topics, with a central event bus or broker in between, so neither side needs to know about the other.

How it differs from Observer

  • Observer: observers subscribe directly to a specific subject object.
  • Pub/Sub: communication goes through a broker using topic names. Publishers and subscribers are fully decoupled; there can be any number of each, and they can be added at runtime.

Where it is used

  • In-app event buses connecting unrelated parts of a UI (e.g. "cart:updated" refreshes the header badge).
  • Micro-frontends talking to each other.
  • Cross-tab messaging with BroadcastChannel.
  • Backends: Redis Pub/Sub, Kafka, Google Pub/Sub, AWS SNS, MQTT for IoT.
  • Real-time features over WebSockets.

Features of a good implementation

  • subscribe(topic, handler) returns an unsubscribe function.
  • once subscriptions.
  • Wildcard or namespaced topics (user.*).
  • Error isolation, so one failing handler does not stop the others.
  • Optionally async delivery, so publishers are not blocked by slow subscribers.

Trade-offs

Decoupling is powerful, but it makes the flow harder to trace ("who listens to this event?"), can hide errors, and leaks memory if subscriptions are not removed. Keep topic names documented and typed (e.g. a TypeScript map of topic → payload), and prefer explicit function calls or shared state for simple cases.

Code example

js
1function createPubSub() {
2 const topics = new Map(); // topic -> Set of handlers
3
4 return {
5 subscribe(topic, handler) {
6 if (!topics.has(topic)) topics.set(topic, new Set());
7 topics.get(topic).add(handler);
8 return () => topics.get(topic)?.delete(handler); // unsubscribe
9 },
10 once(topic, handler) {
11 const off = this.subscribe(topic, (data) => {
12 off();
13 handler(data);
14 });
15 return off;
16 },
17 publish(topic, data) {
18 const handlers = [...(topics.get(topic) ?? []), ...(topics.get("*") ?? [])];
19 for (const handler of handlers) {
20 try {
21 handler(data, topic);
22 } catch (e) {
23 console.log(`handler for "${topic}" failed:`, e.message);
24 }
25 }
26 return handlers.length;
27 },
28 };
29}
30
31const bus = createPubSub();
32const header = [];
33
34// Unrelated parts of the app, connected only by topic names
35const off = bus.subscribe("cart:updated", ({ count }) => header.push(`badge shows ${count}`));
36bus.once("cart:updated", () => header.push("first-add confetti"));
37bus.subscribe("*", (data, topic) => header.push(`analytics: ${topic}`));
38
39bus.publish("cart:updated", { count: 1 });
40bus.publish("cart:updated", { count: 2 });
41off();
42console.log(bus.publish("cart:updated", { count: 3 }), "handler(s) notified"); // 1 handler(s) notified (only analytics)
43console.log(header);
44// ["badge shows 1", "first-add confetti", "analytics: cart:updated", "badge shows 2", "analytics: cart:updated", "analytics: cart:updated"]

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.

Open in study app