A radio station transmits on one frequency, and anyone tuned to that frequency hears it. The station doesn't know who's listening, and listeners don't need to know where the studio is. But if your radio is off while the news is read, that news just passes by.
Pub/Sub (publish/subscribe) works the same way: news goes through a go-between. The sender (the publisher) sends a message to a topic at a go-between called the broker, and the receivers (subscribers) subscribe to that topic at the broker. Publisher and subscribers don't know each other: all they share is the broker and the topic's name.
The problem: the warehouse has to know every receiver
In the Observer lesson, tracker and its listeners lived in one program. Now the warehouse has its own service, separate from the notification and report services. The first version calls them one by one:
// warehouse.js, first version
function parcelArrived(trackingNo, city) {
notifications.sendSms(trackingNo, city) // the warehouse has to know notifications
reports.add(city) // ...and reports, and every new service
}
The billing service wants to know too? The warehouse code changes again. The notification service is down? The first call fails, and scanning parcels in the warehouse stops with it.
A broker in the middle: publish and subscribe
const broker = {
listeners: {}, // { "parcel.status": [fn, fn] }
subscribe(topic, fn) {
(this.listeners[topic] ??= []).push(fn)
return () => {
this.listeners[topic] = this.listeners[topic].filter((f) => f !== fn)
}
},
publish(topic, message) {
const fns = this.listeners[topic] ?? []
fns.forEach((fn) => fn(message))
return fns.length // how many subscribers received it
},
}
// warehouse.js: only knows the broker and the topic's name
function parcelArrived(trackingNo, city) {
return broker.publish("parcel.status", { trackingNo, status: "transit", city })
}
// notifications.js: only knows the broker and the topic's name
broker.subscribe("parcel.status", (m) => console.log("SMS: " + m.trackingNo + " in transit at " + m.city))
console.log(parcelArrived("KCL-0003", "Leeds"))
// SMS: KCL-0003 in transit at Leeds
// 1
a ??= bmeans "setatobifais stillnullorundefined", then the result is used. So a topic with no list yet gets a new array, andpushadds the function to it.a ?? bmeans "usea, unlessaisnullorundefined, then useb".this.listeners[topic] ?? []keeps a topic with no subscribers safe: its list is empty, not an error.publishcalls each subscriber of that topic with the message, then returns how many received it.subscribereturns a remover function. Keep it and call it when the service stops:const stop = broker.subscribe(...), laterstop().- The warehouse and notifications don't import each other. The report service joins with one
broker.subscribe("parcel.status", ...)in its own code, and the nextpublishreturns 2. The warehouse code isn't touched.
Many libraries call these methods on and emit. The shape is the same: emit reads bus.listeners[event] ?? [], then calls each function in it with the data.
How it differs from the Observer in lesson 3
Observer (tracker) |
Pub/Sub | |
|---|---|---|
| who holds the list of receivers | the subject itself | the broker |
| what receivers must know | the tracker object |
the broker and the topic's name |
| where it runs | one program | can be different programs, different servers |
Inside one program, a broker is just an ordinary object, much like EventEmitter. The browser even has a built-in bus: const bus = new EventTarget(), then bus.addEventListener("parcel.status", fn) and bus.dispatchEvent(new CustomEvent("parcel.status", { detail: message })). The difference only shows once publisher and subscribers live in different programs: the broker becomes a server of its own, such as Redis Pub/Sub, RabbitMQ or Kafka. Between browser tabs there's BroadcastChannel.
Messages are lost when nobody has subscribed yet
A pub/sub broker only passes a message to the subscribers there at that moment. It keeps nothing.
| message | subscribers at that moment | publish returns |
SMS |
|---|---|---|---|
| KCL-0001 Bristol | none yet | 0 | none |
| KCL-0002 Manchester | none yet | 0 | none |
| notifications subscribe | |||
| KCL-0003 Leeds | notifications | 1 | SMS: KCL-0003 in transit at Leeds |
A notification service that just finished restarting and subscribes after the second message sends only 1 SMS, for the third message. The first two messages are lost with no error. Redis is the same: PUBLISH returns the number of receivers, (integer) 0 when there are none, and the message is gone. A tab opened later doesn't get the BroadcastChannel messages sent before it either. A misspelled topic name, such as "parcel.stauts", ends the same way: 0 receivers, no error.
A queue keeps messages until they're taken
If messages must not be lost, use a queue: each service has its own queue, made up front, and messages wait there until they're taken.
const queues = { notifications: [] } // made up front
function publishToQueue(message) {
queues.notifications.push(message) // kept until taken
}
publishToQueue({ trackingNo: "KCL-0001", city: "Bristol" })
publishToQueue({ trackingNo: "KCL-0002", city: "Manchester" })
// notifications come up, then take what's waiting, oldest first
while (queues.notifications.length > 0) {
const m = queues.notifications.shift()
console.log("SMS: " + m.trackingNo + " in transit at " + m.city)
}
The two messages that were lost before now go out, late but complete. Real brokers keep them on disk: RabbitMQ queues, Redis Streams, Amazon SQS (keeps messages 4 days unless set otherwise, at most 14 days), or Kafka (7 days by default). The price: storage to look after, and messages that may arrive late.
When you don't need pub/sub
- The sender needs an answer. "Is this postcode valid?" has to come back with yes or no. Pub/sub only announces, it doesn't wait for an answer. Call it directly.
- One program, one fixed receiver. A direct call is easier to trace than hunting for who subscribes to which topic.
- Messages must not be lost. Plain pub/sub skips messages while a subscriber is down. Use a queue.
⚠️ Messages that vanish, double up, or stop halfway
- A misspelled topic.
"parcel.stauts"has no subscribers, sopublishreturns 0 with no error. Keep topic names in one constant. - Subscribing late. Messages published before the subscriber was ready are lost.
- Forgetting to remove a subscriber. Just like Observer listeners: they pile up, and messages get handled twice.
- A subscriber that throws, in a one-program broker.
forEachstops there, the subscribers after it get nothing, and the error reachespublishin the warehouse.
TL;DR: Pub/Sub sends messages through a broker: the publisher calls publish(topic, message), subscribers sign up with subscribe(topic, fn), and both only know the broker and the topic's name, not each other. That's how it differs from Observer, whose subject holds its own list of receivers. The broker keeps listeners[topic], makes the list with ??=, reads it with ?? [], and publish returns the number of receivers. A new receiver doesn't change the publisher's code. Plain pub/sub keeps no messages: subscribing after the second message means 1 SMS out of 3, and a misspelled topic means 0. If messages must not be lost, use a queue. If you need an answer, call directly.
⚡ A broker in the middle
Write:
// warehouse.js: only knows the broker and the topic's name
function parcelArrived(trackingNo, city) {
return broker.publish("parcel.status", { trackingNo, status: "transit", city })
}
// notifications.js: only knows the broker and the topic's name
broker.subscribe("parcel.status", (m) => console.log("SMS: " + m.trackingNo + " in transit at " + m.city))
Meaning: The publisher sends a message to a topic at the broker, subscribers subscribe to that topic. They don't know each other, only the broker and the topic's name. That's the main difference from Observer, whose subject holds its own list of receivers.
⚡ Messages are lost when nobody has subscribed yet
Guess first: the notification service finishes restarting and subscribes after the second message. Out of 3 messages, how many SMS go out?
1 SMS, for the third message. The first two are lost with no error, and publish returns 0.
Meaning: A pub/sub broker only passes a message to the subscribers there at that moment. A misspelled topic, such as "parcel.stauts", ends the same way: 0 receivers, no error.
⚡ A queue keeps messages until they're taken
Meaning: If messages must not be lost, use a queue: each service has its own queue, and messages wait there until they're taken. If the sender needs an answer, call directly.