Full answer
Publish and subscribe (pub/sub) decouples senders from receivers through a broker. A publisher sends a message to a topic name, such as order.created. A subscriber registers interest in a topic. Neither side holds a reference to the other. This differs from the plain observer pattern, where the subject keeps its own list of observers and calls them directly. It also differs from EventEmitter, which is a similar tool but usually has no wildcard matching.
Design:
- Store
patterns: Map<string, Set<handler>>. A Set prevents the same handler being added twice for one pattern. subscribe(pattern, handler)adds the handler and returns a function that removes it. Returning the remover is more convenient than a separateoffand works with anonymous handlers. Delete the empty Set so the Map does not grow without limit.- Wildcards: topics are segments separated by dots.
*matches exactly one segment, and#matches zero or more segments, as in AMQP and MQTT style brokers. Convert the pattern to a regular expression or compare segment by segment. Escape the dots. publish(topic, payload)loops over all patterns, calls the handlers of each match, and returns the number of handlers called. Take a copy of the handler set before calling, because handlers can unsubscribe themselves while running.- Error isolation: wrap each handler call in
tryandcatch, and report errors, so one bad subscriber does not break the rest. once(pattern, handler)is a subscribe that unsubscribes itself on the first call.
Choices to mention: synchronous or asynchronous delivery (asynchronous delivery with queueMicrotask avoids re-entrancy surprises), retained messages for late subscribers, and ordering guarantees. Across processes, use a real broker such as Redis or MQTT.
class PubSub {
#patterns = new Map();
subscribe(pattern, handler) {
if (!this.#patterns.has(pattern)) this.#patterns.set(pattern, new Set());
this.#patterns.get(pattern).add(handler);
return () => {
const handlers = this.#patterns.get(pattern);
if (!handlers) return;
handlers.delete(handler);
if (handlers.size === 0) this.#patterns.delete(pattern);
};
}
once(pattern, handler) {
const off = this.subscribe(pattern, (topic, payload) => {
off();
handler(topic, payload);
});
return off;
}
publish(topic, payload) {
let called = 0;
for (const [pattern, handlers] of this.#patterns) {
if (!PubSub.matches(pattern, topic)) continue;
for (const handler of [...handlers]) {
called++;
try {
handler(topic, payload);
} catch (error) {
console.log(`handler for "${pattern}" failed: ${error.message}`);
}
}
}
return called;
}
static matches(pattern, topic) {
const p = pattern.split('.');
const t = topic.split('.');
const walk = (i, j) => {
if (i === p.length) return j === t.length;
if (p[i] === '#') return walk(i + 1, j) || (j < t.length && walk(i, j + 1));
if (j === t.length) return false;
return (p[i] === '*' || p[i] === t[j]) && walk(i + 1, j + 1);
};
return walk(0, 0);
}
get patternCount() {
return this.#patterns.size;
}
}
const bus = new PubSub();
const seen = [];
const offExact = bus.subscribe('order.created', (topic, p) => seen.push(`exact ${p}`));
bus.subscribe('order.*', (topic, p) => seen.push(`star ${topic}`));
bus.subscribe('#', (topic) => seen.push(`all ${topic}`));
bus.subscribe('order.created', () => { throw new Error('bad subscriber'); });
bus.once('order.shipped', (topic) => seen.push('once ' + topic));
console.log('handlers called:', bus.publish('order.created', 'A1'));
console.log('handlers called:', bus.publish('order.shipped', 'A1'));
console.log('handlers called:', bus.publish('order.shipped', 'A2'));
console.log('handlers called:', bus.publish('order.items.added', 'A1'));
offExact();
console.log('after unsubscribe:', bus.publish('order.created', 'A3'));
console.log(seen);
console.log(['a.b', 'a.*', 'a.#', '#', '*', 'a.*.c'].map((p) => `${p}:${PubSub.matches(p, 'a.b')}`).join(' '));
console.log('patterns stored:', bus.patternCount);Run with Node.js v24.22.1 as js-117.js; two runs gave identical output. Output: handler for "order.created" failed: bad subscriber handlers called: 4 handlers called: 3 handlers called: 2 handlers called: 1 handler for "order.created" failed: bad subscriber after unsubscribe: 3 [ 'exact A1', 'star order.created', 'all order.created', 'star order.shipped', 'all order.shipped', 'once order.shipped', 'star order.shipped', 'all order.shipped', 'all order.items.added', 'star order.created', 'all order.created' ] a.b:true a.*:true a.#:true #:true *:false a.*.c:false patterns stored: 3
Key points
- A broker with Map of patterns to Sets of handlers decouples publishers and subscribers.
- subscribe returns an unsubscribe function; remove empty Sets.
- Wildcards: star matches one segment, hash matches many; match by segments.
- Copy the handlers before calling and isolate errors per handler.
- Choose sync or async delivery; use a real broker across processes.
Common mistakes
- Letting one failing handler stop delivery to the rest.
- Iterating the live handler Set while handlers unsubscribe themselves.
- Forgetting to remove empty entries, so unsubscribed topics leak memory.
- Building wildcard regular expressions without escaping the dots.
Follow-ups
- How is pub/sub different from the observer pattern and from EventEmitter?
- How would you add retained messages for late subscribers?
- How would you make delivery asynchronous without changing the order of messages?
Tips
- Contrast pub/sub with observer: the broker removes direct references.
- Return an unsubscribe function from subscribe.
- State the wildcard rules clearly before coding them.