Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 36 ยท Scaling and Adapters

Scaling Socket.IO Servers

Why one Socket.IO process is not enough, what breaks when you add more, and how adapters and sticky sessions fix broadcasting across servers.

A single Node.js process can hold tens of thousands of idle WebSocket connections, so many Socket.IO apps never need more than one server. Sooner or later, though, you hit a limit: the CPU of one core, the memory of one machine, or the wish to deploy without dropping everyone. Then you run several Socket.IO processes, and two things stop working by themselves: the handshake and the broadcast.

This lesson explains why, and gives you the map for the rest of the chapter: sticky sessions fix the first problem, an adapter fixes the second.

The socket.io and redis packages are not available in the runner on this site. Real code appears in read-only blocks. The runnable examples use small hand-written stand-ins that show the same behavior with plain Node.js, and each one says so.

What one process knows

A Socket.IO server keeps its connected sockets and their rooms in memory. When you write io.to("lobby").emit("msg", "hi"), the server loops over the sockets it holds that are in the room lobby. It has no idea about sockets held by another process.

JavaScript
// server A and server B run this same code
io.on("connection", (socket) => {
  socket.join("lobby");
  socket.on("say", (text) => {
    io.to("lobby").emit("said", text); // only reaches clients connected to THIS process
  });
});

If Ana is connected to server A and Ben to server B, Ana's message never reaches Ben. Nothing is broken in the code. The state is simply split between two processes.

Two problems when you add servers

Handshake HTTP long-polling requests must reach the same process.
Broadcast Rooms live in memory, so each process only sees its own sockets.

Sticky sessions solve the first. An adapter solves the second.

1 / 2

Fix 1: the adapter

An adapter is the part of Socket.IO that tracks which socket is in which room and delivers broadcasts. The default one, the in-memory adapter, works inside one process. Swapping it for a different adapter makes every broadcast also travel through a shared channel (for example Redis pub/sub), so every process can deliver it to its own local sockets.

Node.js Broadcast with and without an adapter (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.

Without the bus, only ana receives the message. With the bus, ben and bo receive it too. The next two lessons show the real adapters: Redis adapter and pub/sub and cluster and alternative adapters.

Fix 2: sticky sessions

By default the client opens a connection with HTTP long-polling first and upgrades to WebSocket afterwards. The polling phase is several separate HTTP requests that all belong to one session, and the session lives in one process's memory. If a load balancer sends request 2 to a different process, that process answers Session ID unknown and the client fails to connect. The balancer must therefore keep one client on one server for the life of the session. That is called a sticky session or session affinity, and the next lesson covers it.

There is a shortcut: if you configure the client to use only WebSocket (transports: ["websocket"]), there is just one long connection, so no stickiness is needed. You lose the polling fallback, which matters for users behind restrictive proxies.

JavaScript
// client: WebSocket only, no sticky sessions required
const socket = io("https://example.com", { transports: ["websocket"] });

Vertical or horizontal?

Approach What you do Limit
Vertical Bigger machine, more RAM One process still uses one CPU core
More processes on one machine Node cluster or several containers Needs sticky routing and an adapter
Several machines Load balancer + adapter + shared store Network latency between nodes, more to operate

A single Node.js process runs JavaScript on one core. Because Socket.IO work is mostly I/O, one process goes a long way, but CPU-heavy handlers (JSON of big payloads, compression) will saturate a core first.

Things that stop working when you scale

Run through this list before you add the second process:

  • Server-side state in variables. An in-memory Map of online users is now per process. Move shared state to Redis or a database.
  • io.sockets.sockets and io.fetchSockets(). The first is local only. fetchSockets() goes through the adapter and works across nodes.
  • io.emit between processes. Works with an adapter. Without one, it is local.
  • Server-to-server messages. Use io.serverSideEmit("event", data), which every adapter supports, to talk to the other nodes.
  • Unique ids. socket.id is unique per connection, but counters in memory are not unique across nodes.
Node.js Why a plain in-memory counter breaks

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.

A minimal real setup

Here is the shape of a scaled app. Do not worry about every line yet; each piece is explained in the next lessons.

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

const httpServer = createServer();
const io = new Server(httpServer);

const pubClient = createClient({ url: "redis://localhost:6379" });
const subClient = pubClient.duplicate();
await Promise.all([pubClient.connect(), subClient.connect()]);

io.adapter(createAdapter(pubClient, subClient));

io.on("connection", (socket) => {
  socket.on("say", (text) => io.emit("said", text)); // now reaches every node
});

httpServer.listen(Number(process.env.PORT ?? 3000));

Start this on ports 3000 and 3001, put a sticky load balancer in front, and clients on either port see each other's messages.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Two Socket.IO servers run without an adapter. A client on server A emits to room lobby. Who receives it?

    Rooms live in each process's memory, so the default adapter only delivers to the sockets that process holds.
  2. 2. Why do HTTP long-polling clients need sticky sessions?

    The several polling requests belong to one session held in one process's memory. Another process answers "Session ID unknown".
  3. 3. Which setting lets you skip sticky sessions?

    With WebSocket only there is one long-lived connection, so the whole session stays on one server without any affinity rule.
  4. 4. What does an adapter add to Socket.IO?

    The adapter delivers broadcasts and tracks rooms. Replacing the in-memory one with Redis or similar connects processes.

Summary

  • Sockets and rooms live in the memory of one process, so scaling out splits that state.
  • Sticky sessions keep polling requests on the server that owns the session.
  • An adapter (Redis, Postgres, cluster, and others) relays broadcasts between servers.
  • Move shared state (online counters, user maps) out of process memory.
  • WebSocket-only clients avoid the stickiness requirement but lose the polling fallback.

Next: Sticky Sessions and Load Balancing