Pub/Sub: Map + conn.write fan-out
Before the code: messaging and replication, in plain English
Picture a group chat. One person publishes a message. The chat app knows who is in the room and forwards the message to each of them. That is publish and subscribe, and it is the simplest piece of Redis that is not a key-value store. Replication is the same idea pointed at a backup machine: the leader sends every write to a follower, who quietly replays them. Same plumbing, different audience. In Node we wire this with a Map of channel to Set of sockets and a plain iteration.
Fan-out and follow-the-leader
Quiz: Quiz
Loading practice…
PUBLISH iterates the subscriber Set and calls conn.write on each. No lock. No write pump. The event loop guarantees we are the only one touching the map.
Map of channel to Set of conns, fan-out via conn.write
function publish(ch, message) {
const set = SUBSCRIBERS.get(ch);
if (!set) return 0;
const payload = Buffer.from(`*3\r\n$7\r\nmessage\r\n$${Buffer.byteLength(ch)}\r\n${ch}\r\n$${Buffer.byteLength(message)}\r\n${message}\r\n`);
let delivered = 0;
for (const conn of set) {
if (conn.write(payload)) delivered++;
else delivered++;
}
return delivered;
}The whole fan-out. Buffer is built once, conn.write is called once per subscriber.
conn.write returns false when the socket buffer is full (backpressure signal). We ignore it here. Production would disconnect or buffer that subscriber. The exercises walk through both.