Pub/Sub with Redis — Realtime

Socket.IO rooms live in one Node process's memory, so an emit from process A does not reach sockets connected to process B. Redis Pub/Sub (publish/subscribe)…

Mrs. Rini's Laundry keeps growing. So its realtime server now runs as two Node processes: A on port 3000 and B on port 3001. Both sit behind a load balancer (a server that sends each new connection to A or B). Eko's tablet is connected to A, and Mr. Darto's phone happens to be on B. News from A has to reach the phones on B, and that is what Pub/Sub is for.

Pub/Sub (publish/subscribe) is a messaging pattern. A sender publishes a message to a channel (a name) without knowing who is listening. Everyone currently subscribed to that channel receives it right then. Redis (a server that keeps data in memory) can be the go-between (a message broker) for processes or servers.

Pub/Sub is like the loudspeaker at a market. The announcer says "laundry #12 is ready for pickup" on the announcement line, and everyone in the market hears it. Whoever went home hears nothing, because announcements are not recorded. The announcer is the sender, the loudspeaker is Redis, the announcement line is the channel, and the people in the market are the processes that are subscribed. If you need a recording, use a logbook that can be read later: that is Redis Streams.

A process only knows its own sockets

Guess first: Mr. Darto's phone is in the room order:12 and connected to B. Process A runs io.to('order:12').emit('order:status', ...). Does the news reach Mr. Darto's phone?

The answer: no. Socket.IO rooms (from the Rooms & Namespaces lesson) live in the process's memory, as a Map from a room name to a set of sockets. Process A has no list of B's sockets, and there is no path between the two.

Tried with socket.io 4.8.4: two servers on two ports, each with one client in the room order:12. An emit from A reaches only the client connected to A. Mr. Darto's phone on B receives nothing, and there is no error. With one process everything works, so this problem only appears when the app grows.

The fix: every process sends its news to a go-between, and every process listens to that go-between and passes it on to its own sockets.

PUBLISH and SUBSCRIBE in Redis

Two terminals running redis-cli, the program that sends commands to Redis 7.2.7. Terminal 1 subscribes to the channel board:

127.0.0.1:6379> SUBSCRIBE board
1) "subscribe"
2) "board"
3) (integer) 1

Terminal 2 sends to the same channel:

127.0.0.1:6379> PUBLISH board '{"id":12,"status":"Ready for pickup"}'
(integer) 1

Terminal 1 shows right away:

1) "message"
2) "board"
3) "{\"id\":12,\"status\":\"Ready for pickup\"}"
import { createClient } from 'redis' // redis 6.3.0

const pub = createClient({ url: 'redis://localhost:6379' })
const sub = pub.duplicate()                   // a second connection, only for listening
await pub.connect()
await sub.connect()

// every process (A and B) listens, then passes it on to its own sockets
await sub.subscribe('board', (message) => {
  const d = JSON.parse(message)
  io.to(`order:${d.id}`).emit('order:status', d)
})

// whichever process receives Eko's change
await pub.publish('board', JSON.stringify({ id: 12, status: 'Ready for pickup' }))

Channels and patterns

A channel is just a name, created when used. PSUBSCRIBE subscribes to a pattern: a name with * that matches many channels, so order:* matches order:12 and every other order channel. Terminal 1 runs PSUBSCRIBE order:*, terminal 2 runs PUBLISH order:12 '{"status":"Ready for pickup"}' (the reply is (integer) 1). What a pattern subscriber receives has one more line: the pattern.

1) "pmessage"
2) "order:*"
3) "order:12"
4) "{\"status\":\"Ready for pickup\"}"

In Node: await sub.pSubscribe('order:*', (message, channel) => ...). Redis matches every PUBLISH against every registered pattern, so use patterns sparingly.

When you need replay: Redis Streams

Redis Streams is a list of messages stored in Redis. Each message has an id <milliseconds>-<sequence>: the time the message was added, then a sequence number for messages in the same millisecond. A reader can start from any id. So a reader that was down can continue from the last id it read. For example, with the stream board:log:

127.0.0.1:6379> XADD board:log * id 12 status "Ready for pickup"
"1791686460000-0"
127.0.0.1:6379> XREAD COUNT 10 STREAMS board:log 0
1) 1) "board:log"
   2) 1) 1) "1791686460000-0"
         2) 1) "id"
            2) "12"
            3) "status"
            4) "Ready for pickup"

Pub/Sub is for "whoever is listening, right now". Streams are for "nothing may be missed".

Socket.IO across processes: the Redis adapter

For Socket.IO, you do not need to write the bridge (the code that subscribes, then passes messages on) yourself. A Socket.IO adapter is the part that keeps the rooms and broadcasts emits. The Redis adapter passes every emit through Redis:

import { createClient } from 'redis'
import { createAdapter } from '@socket.io/redis-adapter' // 8.3.0

const pub = createClient({ url: 'redis://localhost:6379' })
const sub = pub.duplicate()
await Promise.all([pub.connect(), sub.connect()])
io.adapter(createAdapter(pub, sub))

io.to('order:12').emit('order:status', { id: 12, status: 'Ready for pickup' }) // reaches A and B

⚠️ Why do half the clients get nothing?

TL;DR: Socket.IO rooms live in one Node process's memory, so an emit from process A does not reach sockets connected to process B. Redis Pub/Sub (publish/subscribe) is the go-between for processes: PUBLISH sends a message to a channel (a name) and replies with the number of receivers, SUBSCRIBE listens to one channel, and PSUBSCRIBE listens to a pattern such as order:*. All of it is fire-and-forget: Redis keeps no messages, so whoever is down misses them. Redis Streams keep messages for replay: XADD adds, XREAD reads from the last id, and consumer groups (XREADGROUP, XACK) share messages among several readers. For Socket.IO, set up an adapter (the part that broadcasts emits). @socket.io/redis-adapter 8.3.0 connects every process through Pub/Sub, with no connection state recovery (the feature that sends missed news when a client reconnects). @socket.io/redis-streams-adapter 0.3.1 goes through a stream, with that feature.

⚡ A process only knows its own sockets

Guess first: the realtime server runs as two Node processes, A and B. Mr. Darto's phone is in the room order:12 and connected to B. Process A runs io.to('order:12').emit('order:status', ...). Does the news reach Mr. Darto's phone?

No, and there is no error. Socket.IO rooms live in one process's memory, and A has no list of B's sockets.

Meaning: With one process everything works, so this problem only appears when the app grows to several processes.

⚡ Redis as the go-between

Write:

await sub.subscribe('board', (message) => {
  const d = JSON.parse(message)
  io.to(`order:${d.id}`).emit('order:status', d)
})

Meaning: Redis Pub/Sub (publish/subscribe) is the message broker (the go-between) for processes. Every process sends its news to Redis, and every process listens to Redis and passes the news on to its own sockets. In this code, sub is a Redis connection only for listening, and board is the channel (a name) it listens to.

⚡ Fire-and-forget

Meaning: Pub/Sub in Redis is fire-and-forget (send, then forget): Redis keeps nothing, so whoever is down misses the message. Pub/Sub is for "whoever is listening, right now". When nothing may be missed, use Redis Streams: a list of messages kept in Redis that can be read again from the last message read.

⚡ No need to write the bridge yourself

Meaning: You do not need to write the subscribe code from the step "Redis as the go-between" yourself. A Socket.IO adapter is the part that keeps the rooms and broadcasts emits. The Redis adapter (@socket.io/redis-adapter) passes every emit through Redis, so io.to('order:12').emit(...) reaches sockets on A and B.

What you will learn