Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 36 ยท Scaling and Adapters

Redis Adapter and Pub/Sub

Set up the Socket.IO Redis adapter, understand the pub/sub flow behind it, and use fetchSockets, serverSideEmit and sharded channels across servers.

The Redis adapter is the most common way to connect several Socket.IO servers. Each server keeps its own sockets, but every broadcast is also published on a Redis channel, and every other server that listens to that channel delivers the message to its own matching sockets. Redis only relays messages. It does not store your sockets, rooms or history.

Installing and wiring it up

Terminal
npm install @socket.io/redis-adapter redis
JavaScript
import { createServer } from "node:http";
import { Server } from "socket.io";
import { createClient } from "redis";
import { createAdapter } from "@socket.io/redis-adapter";

const pubClient = createClient({ url: process.env.REDIS_URL ?? "redis://localhost:6379" });
const subClient = pubClient.duplicate();

pubClient.on("error", (err) => console.error("redis pub error", err));
subClient.on("error", (err) => console.error("redis sub error", err));

await Promise.all([pubClient.connect(), subClient.connect()]);

const httpServer = createServer();
const io = new Server(httpServer, {
  adapter: createAdapter(pubClient, subClient),
});

io.on("connection", (socket) => {
  socket.join("lobby");
  socket.on("say", (text) => io.to("lobby").emit("said", socket.id, text));
});

httpServer.listen(3000);

You need two Redis connections. A connection in subscriber mode can only run subscribe commands, so publishing uses a separate client. duplicate() creates a second connection with the same settings. Handle the error events, or a dropped Redis connection will crash the process with an unhandled error.

Do not confuse this package with socket.io-redis, an old name of the same idea. Use @socket.io/redis-adapter.

What happens on io.to("lobby").emit(...)

One broadcast, four steps

Deliver locally Server A sends to its own sockets in the room.
Publish Server A publishes the packet on a Redis channel.
Receive Servers B and C are subscribed and receive it.
Deliver locally Each one sends to its own sockets in the room.

The sender never delivers twice to itself.

1 / 2

The channel names are derived from the namespace (and the room for single-room broadcasts), so a server only receives traffic for namespaces and rooms that matter to it. You never need to publish by hand.

Node.js A Redis-like broker and adapters (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Only members of lobby see the first message, on all three servers. The news message reaches bea on server B only. The sender's own local delivery is immediate, remote delivery takes one trip through the broker.

Cross-server APIs

Once an adapter is in place, a few APIs work across nodes:

JavaScript
// All sockets in a room, from every server (returns remote sockets with limited methods)
const sockets = await io.in("lobby").fetchSockets();
console.log(sockets.map((s) => s.id));

// Make every socket in a room (on any server) join another room
io.in("lobby").socketsJoin("announcements");

// Disconnect all sockets of a user, wherever they are
io.in(`user:${userId}`).disconnectSockets();

// Talk between servers (not to clients)
io.serverSideEmit("cache-invalidate", { key: "config" });
io.on("cache-invalidate", (payload) => cache.delete(payload.key));

Putting every socket into a room named after the user (socket.join("user:" + userId)) is a handy pattern: to message that person on all their devices and nodes, emit to the room. It also means disconnectSockets can log somebody out everywhere.

serverSideEmit sends to the other servers. With an acknowledgement callback it collects one answer per other node, with a timeout, which is useful for questions such as "how many users are online in total":

JavaScript
io.serverSideEmit("count-users", (err, answers) => {
  const remote = answers.reduce((sum, n) => sum + n, 0);
  console.log("remote users:", remote, "errors:", err ? err.message : "none");
});

io.on("count-users", (cb) => cb(io.of("/").sockets.size));
Node.js Collecting answers from other nodes (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Always handle the error argument. A node that is down, overloaded or still starting simply does not answer, and the callback fires after the timeout with whatever arrived.

Redis Cluster and sharded pub/sub

Classic pub/sub in a Redis Cluster broadcasts every message to every node of the cluster, which does not scale with the cluster size. Redis 7 added sharded pub/sub, where a channel lives on one shard. Socket.IO provides a matching adapter:

JavaScript
import { createShardedAdapter } from "@socket.io/redis-adapter";
import { createCluster } from "redis";

const pubClient = createCluster({ rootNodes: [{ url: "redis://10.0.0.1:7000" }] });
const subClient = pubClient.duplicate();
await Promise.all([pubClient.connect(), subClient.connect()]);

const io = new Server({
  adapter: createShardedAdapter(pubClient, subClient),
});

Use it when you run a real Redis Cluster on Redis 7 or newer. For a single Redis instance, the standard adapter is fine. The related adapters (Redis Streams, Postgres, MongoDB) are compared in cluster and alternative adapters.

Operating notes

  • Redis down: broadcasts between nodes are lost while it is down, but each node keeps serving its local sockets. Messages sent during the outage are not replayed.
  • Message size: every emit travels through Redis, so large payloads and very chatty events cost network time. Send ids, not blobs.
  • Rooms per user are cheap, but millions of tiny rooms increase memory on each node.
  • Latency: an extra hop of well under a millisecond on a local network. Keep Redis close to the servers.
  • Sticky sessions are still required for polling; see sticky sessions.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does the Redis adapter need two Redis connections?

    A connection in subscriber mode can only run subscribe-related commands, so a second connection (duplicate) publishes.
  2. 2. What does Redis store when you use the Redis adapter?

    The adapter uses pub/sub as a relay. Sockets and rooms stay in each server's memory, and messages are not stored.
  3. 3. What does io.serverSideEmit do?

    It is for server-to-server communication. With a callback you receive one acknowledgement per other server, or an error on timeout.
  4. 4. When would you use createShardedAdapter?

    Sharded pub/sub keeps each channel on one shard, which scales better than classic cluster-wide pub/sub.

Summary

  • The Redis adapter relays broadcasts between servers over pub/sub; sockets and rooms remain in each process.
  • Use two clients (publisher and subscriber) and handle their error events.
  • fetchSockets, socketsJoin, disconnectSockets and serverSideEmit work across nodes.
  • Use createShardedAdapter with Redis Cluster 7+.
  • Messages published during a Redis outage are lost; plan recovery separately.

Next: Cluster and Alternative Adapters