Skip to content
jshacks.dev
Patterns

The Pub/Sub Pattern in JavaScript Explained

Pub/sub lets publishers send messages to subscribers through a broker so neither knows the other. Build one in JavaScript and compare it to the observer.

8 min read
Summarize in AI
Flat illustration of a service container binding interfaces to classes, with the JavaScript, Vite, npm and Node.js logos.

The pub/sub pattern, short for publish and subscribe, lets one part of a program announce that something happened while other parts react, with neither side holding a reference to the other. A broker sits in the middle and routes messages by topic name. This post builds a small broker on Node.js 24, adds unsubscribe, wildcards and error isolation, and explains how pub/sub differs from the observer pattern and from Node's own EventEmitter.

The problem: components that should not know each other

An order service finishes an order. Billing wants to charge, the mailer wants to send a receipt, and analytics wants to log it. If the order service calls each directly, it must import all three, and adding a fourth consumer means editing the order service.

coupled.mjsJavaScript
const billing = { charge: (o) => console.log(`charge ${o.total}`) };
const mailer = { receipt: (o) => console.log(`receipt for #${o.id}`) };
const analytics = { track: (o) => console.log(`track order ${o.id}`) };

function completeOrder(order) {
  billing.charge(order);
  mailer.receipt(order);
  analytics.track(order);
}

completeOrder({ id: 7, total: 40 });
Text
charge 40
receipt for #7
track order 7

Every new reaction to an order lands inside completeOrder. The function has become a list of everything that cares about orders, which is the opposite of what it should know.

A minimal broker

A broker keeps a map from topic name to a set of handlers. subscribe adds one and returns a function that removes it. publish calls every handler registered for the topic.

broker.mjsJavaScript
function createBroker() {
  const topics = new Map();

  function subscribe(topic, handler) {
    if (!topics.has(topic)) topics.set(topic, new Set());
    topics.get(topic).add(handler);
    return () => topics.get(topic)?.delete(handler);
  }

  function publish(topic, message) {
    for (const handler of topics.get(topic) ?? []) {
      handler(message);
    }
  }

  return { subscribe, publish };
}

const broker = createBroker();
broker.subscribe("order.completed", (o) => console.log(`charge ${o.total}`));
broker.subscribe("order.completed", (o) => console.log(`receipt for #${o.id}`));

broker.publish("order.completed", { id: 7, total: 40 });
broker.publish("order.cancelled", { id: 8 });
Text
charge 40
receipt for #7

The second publish has no subscribers, so nothing happens and nothing fails. The order service now publishes one message and does not import billing or the mailer. A new consumer subscribes from its own module and the publisher never changes.

Unsubscribing

Returning an unsubscribe function from subscribe gives each subscriber a handle for cleanup. This matters more than it looks, because a handler that is never removed keeps its closure, and everything the closure references, alive for as long as the broker lives.

unsubscribe.mjsJavaScript
const broker = createBroker();

const off = broker.subscribe("tick", (n) => console.log(`handler saw ${n}`));
broker.publish("tick", 1);
off();
broker.publish("tick", 2);
console.log("done");
Text
handler saw 1
done

A component that subscribes when it starts must unsubscribe when it stops. Forgetting this is the usual cause of the memory growth people find in long-running pub/sub code.

Isolating handler errors

In the broker above, a handler that throws stops the loop, and later subscribers never run. One broken consumer should not block the others.

isolated.mjsJavaScript
function createSafeBroker(onError = console.error) {
  const topics = new Map();
  return {
    subscribe(topic, handler) {
      if (!topics.has(topic)) topics.set(topic, new Set());
      topics.get(topic).add(handler);
      return () => topics.get(topic)?.delete(handler);
    },
    publish(topic, message) {
      for (const handler of [...(topics.get(topic) ?? [])]) {
        try {
          handler(message);
        } catch (err) {
          onError(err, topic);
        }
      }
    },
  };
}

const broker = createSafeBroker((err, topic) =>
  console.log(`handler failed on ${topic}: ${err.message}`),
);
broker.subscribe("job", () => {
  throw new Error("boom");
});
broker.subscribe("job", (m) => console.log(`second handler got ${m}`));
broker.publish("job", "work");
Text
handler failed on job: boom
second handler got work

Copying the handler set with [...] before iterating also protects against a handler that unsubscribes itself during delivery, which would otherwise change the set while it is being walked.

Wildcard topics

Topic names with dots lend themselves to patterns. A subscription to order.* can receive order.completed and order.cancelled.

wildcard.mjsJavaScript
function matches(pattern, topic) {
  const p = pattern.split(".");
  const t = topic.split(".");
  if (p.length !== t.length) return false;
  return p.every((part, i) => part === "*" || part === t[i]);
}

console.log(matches("order.*", "order.completed"));
console.log(matches("order.*", "user.created"));
console.log(matches("*.created", "user.created"));
console.log(matches("order.*", "order.item.added"));
Text
true
false
true
false

To use this in the broker, store handlers as { pattern, handler } pairs and filter by matches on each publish. The cost is a scan of all subscriptions per message, which is fine for tens or hundreds and worth replacing with a tree for more.

Pub/sub versus observer

The two are close relatives, and the difference is the middle.

AspectObserverPub/sub
Who knows whomObservers register directly on the subjectNeither side knows the other, both know the broker
RoutingEvery observer gets every changeSubscribers pick topics
CouplingSubject holds a list of observersPublisher holds only the broker
Typical scopeOne object and its listenersWhole application, or across processes
DeliveryUsually synchronousSynchronous in memory, often asynchronous across a network

Node's EventEmitter sits between them. It is an observer implementation that you can share as a global bus, which makes it work as an in-process pub/sub broker.

emitter-bus.mjsJavaScript
import { EventEmitter } from "node:events";

const bus = new EventEmitter();
bus.on("order.completed", (o) => console.log(`receipt for #${o.id}`));
bus.emit("order.completed", { id: 7 });
console.log(bus.emit("order.cancelled", { id: 8 }));
Text
receipt for #7
false

emit returns false when no listener was registered, which is a useful signal. One caution: an EventEmitter named error has special behavior. Emitting "error" with no listener throws, so a bus should either avoid that event name or always attach an error listener.

Synchronous versus asynchronous delivery

The broker above calls handlers synchronously, inside publish. The publisher waits for every handler and sees their exceptions, if you let them propagate. Often that is not what you want: a slow handler delays the publisher.

async-delivery.mjsJavaScript
const broker = createBroker();
broker.subscribe("saved", async (doc) => {
  await new Promise((resolve) => setTimeout(resolve, 10));
  console.log(`indexed ${doc}`);
});

console.log("publishing");
broker.publish("saved", "doc-1");
console.log("published");
Text
publishing
published
indexed doc-1

The handler is async, so publish does not wait for it: the second log appears first. This also means a rejected promise from a handler is an unhandled rejection unless the broker catches it. A broker that accepts async handlers should call Promise.resolve(handler(message)).catch(onError).

Pitfalls

Invisible flow. With direct calls, your editor can jump from caller to callee. With pub/sub, the link is a string. Define topic names as constants in one module, so search and rename tools can find both ends.

Ordering assumptions. Handlers run in subscription order here, but a design that depends on that order is fragile. If billing must run before the receipt, that is a sequence, and a function that calls them in order says so more honestly than two subscriptions.

Message shape drift. The publisher and subscriber agree only on a topic name and an object shape, and nothing enforces it. In TypeScript, a map from topic to payload type restores the check.

Leaks. Every subscription needs a matching unsubscribe when its owner goes away.

Testing

Test the broker with a handler that records what it received, and test publishers by giving them a broker they can inspect.

broker.test.mjsJavaScript
import assert from "node:assert/strict";
import { test } from "node:test";

test("a handler receives published messages until it unsubscribes", () => {
  const broker = createBroker();
  const seen = [];
  const off = broker.subscribe("n", (v) => seen.push(v));
  broker.publish("n", 1);
  off();
  broker.publish("n", 2);
  assert.deepEqual(seen, [1]);
});
Text
✔ a handler receives published messages until it unsubscribes (0.9ms)
ℹ tests 1
ℹ pass 1
ℹ fail 0

When not to use it

Pub/sub is a poor fit when the sender needs an answer, because the pattern is fire and forget. It also hides control flow, so a sequence of steps that must happen in order reads better as a function. Use it for notifications where the publisher truly does not care who listens.

Designing topics and messages

The part of pub/sub that ages worst is the vocabulary. Topic names and message shapes are a contract between code that never imports each other, so decisions made casually in week one become constraints in year two.

Name topics for facts that already happened, in the past tense, such as order.completed or user.registered, and not for instructions such as send.receipt. A fact has any number of interested parties, while an instruction names a single intended receiver, and if only one receiver is intended then a direct call is honest about it. Facts also age well: you can add a subscriber to order.completed next year without changing anything about what the topic means.

Keep messages small and self-contained. Include the identifiers a subscriber needs and the few fields most of them will want, and let the rare subscriber fetch more. A message that carries a whole database row couples every subscriber to that row's shape, so a column rename becomes a breaking change across the application. A message that carries only an orderId forces every subscriber to load the order and risks a stampede of queries, so the right size is somewhere between the two.

Version a message when you must change it. Adding a field is safe, because existing subscribers ignore it. Renaming or removing one is not, and the safe route is to publish both shapes for a while, or to introduce a new topic name and retire the old one after every subscriber has moved.

Ordering, duplicates and delivery guarantees

Inside one process, the in-memory broker delivers each message once to each subscriber, in subscription order, and nothing is lost unless the process dies. Those guarantees disappear when you move to a network broker. Messages can arrive out of order, arrive twice after a retry, or never arrive if a subscriber is offline and the system does not store them. Subscribers that may see duplicates should be idempotent, meaning that handling the same message twice has the same effect as handling it once. A common technique is to store the id of each handled message and skip ones already seen. Treat this as a design requirement from the start, because retrofitting idempotency into handlers that assumed exactly-once delivery is difficult.

Share

Keep reading

Flat illustration of two options weighed side by side, with the JavaScript, Vite and Node.js logos.
Functions

Classes vs Factory Functions

Classes vs factory functions in JavaScript compared on private state, this, instanceof, inheritance, memory, JSON and testing, with exact output.

7 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.