Socket.IO feels like "real-time that just works" right up until the first deploy with two server instances behind a load balancer, or the first user who walks through a tunnel and loses network for three seconds. Events vanish silently, notifications arrive twice, or some clients stop receiving anything at all after reconnecting. None of this is a library bug: it's the absence of an explicit design around reconnection and event distribution across instances.

What "connected" doesn't guarantee

A Socket.IO socket can disconnect for plenty of reasons: a network drop, a phone going to sleep, a ping timeout, or the server deliberately closing it (io server disconnect). The client reconnects automatically by default, but each reconnection creates a brand new session with a new socket id, unless you explicitly configure otherwise. During the disconnected window, any event the server emits to that socket is dropped, not queued.

// client
import { io } from "socket.io-client";

const socket = io("https://realtime.example.com", {
  reconnection: true,
  reconnectionAttempts: Infinity,
  reconnectionDelay: 1000,
  reconnectionDelayMax: 10000,
  randomizationFactor: 0.5,
  timeout: 20000,
});

socket.on("disconnect", (reason) => {
  console.log("disconnected:", reason);
  // "io server disconnect" means the server closed it on purpose,
  // auto-reconnect is skipped in that specific case, so reconnect manually
  if (reason === "io server disconnect") {
    socket.connect();
  }
});

socket.on("connect", () => {
  console.log("connected, socket id:", socket.id);
});

Exponential backoff with randomizationFactor isn't cosmetic: without it, a server restart triggers a synchronized wave of thousands of simultaneous reconnection attempts (a thundering herd) that can take down the server that just came back up.

Recovering missed events

Since Socket.IO 4.6, connection state recovery can restore a session's server-side state for a short window after disconnection, and replay events emitted during the outage, provided the server kept those events buffered.

// server
import { Server } from "socket.io";

const io = new Server(httpServer, {
  connectionStateRecovery: {
    maxDisconnectionDuration: 2 * 60 * 1000, // 2 minutes
    skipMiddlewares: true,
  },
});

io.on("connection", (socket) => {
  if (socket.recovered) {
    console.log("session restored, missed events replayed automatically");
  } else {
    console.log("fresh session (or the recovery window expired)");
  }
});

This mechanism covers short outages well (a tunnel, a wifi-to-4G switch). For business-critical events (payment confirmed, message sent), don't rely on it alone: the safer pattern is to persist the event with a monotonic id on the client side and do an explicit catch-up on reconnect (GET /events?since=lastSeenId), rather than trusting an in-memory buffer that disappears the moment the server process restarts.

The hidden problem with horizontal scaling

The moment there's more than one server instance, two clients connected to two different instances share no state by default. If instance A wants to notify a user connected to instance B, an io.to(room).emit(...) call fired from A never reaches B's socket, because each Node.js instance keeps its own in-memory room table.

// server, with a Redis adapter for cross-instance distribution
import { createAdapter } from "@socket.io/redis-adapter";
import { createClient } from "redis";

const pubClient = createClient({ url: process.env.REDIS_URL });
const subClient = pubClient.duplicate();

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

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

// io.to("room:42").emit(...) now reaches sockets connected
// to any instance in the cluster

The Redis adapter routes broadcast emissions and room events through Redis pub/sub, so every instance receives and forwards the messages meant for its own sockets. It's transparent from the application code's point of view; you keep writing io.to(room).emit(...) exactly as before.

Tuning the heartbeat: disconnect detection versus false positives

Socket.IO detects a dropped connection through a ping/pong mechanism: the server sends a ping every pingInterval milliseconds and considers the client gone if it doesn't respond within pingTimeout. The defaults (25s and 20s respectively) are a tradeoff, not a universal truth.

// server
const io = new Server(httpServer, {
  pingInterval: 10000, // ping every 10s
  pingTimeout: 5000,   // declare disconnection after 5s without a pong
});

Lowering these values speeds up detection of a genuinely lost client (useful for a real-time presence feature where "online" needs to reflect reality within a few seconds), but it raises the risk of false positives on a mobile network with variable latency: a 6-second latency spike on degraded 4G triggers a full disconnect/reconnect cycle, even though the underlying connection would eventually have responded. Raising the delays reduces false positives but delays detecting a genuinely dead client, which matters directly for features like "list of currently online users." The right setting comes from observing the actual latency distribution of production clients, not from copying a default value.

Authorizing room access, not just joining one

A common security trap: letting the client freely pick which room to join via a client-sent socket.join(roomName), with no server-side check. Any connected client can then join another user's room and start receiving their events.

// wrong: the server trusts whatever room name the client requests
socket.on("join", (roomName) => {
  socket.join(roomName); // no authorization check at all
});

// correct: the server resolves the room from the authenticated identity,
// never from an arbitrary value sent by the client
io.use(async (socket, next) => {
  const token = socket.handshake.auth?.token;
  try {
    socket.data.user = await verifyToken(token);
    next();
  } catch {
    next(new Error("unauthorized"));
  }
});

socket.on("join-conversation", async (conversationId) => {
  const allowed = await userCanAccessConversation(socket.data.user.id, conversationId);
  if (!allowed) return socket.emit("error", "forbidden");
  socket.join(`conversation:${conversationId}`);
});

The io.use() middleware runs on every connection, before any event handler, and it's the right place to authenticate the socket once for the whole lifetime of the connection, rather than checking a token on every individual event.

The detail that breaks everything: sticky sessions

Socket.IO first negotiates over HTTP long-polling before upgrading to WebSocket (unless you force transports: ["websocket"]). That multi-request handshake has to consistently reach the same server instance, or it fails outright. Without session affinity at the load balancer, connections fail intermittently, especially behind a round-robin reverse proxy.

upstream socketio_nodes {
    ip_hash;
    server app1:3000;
    server app2:3000;
    server app3:3000;
}

server {
    location /socket.io/ {
        proxy_pass http://socketio_nodes;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host $host;
    }
}

ip_hash works for a simple deployment but gets fragile with clients behind a shared NAT (a whole office ends up pinned to one instance) or with IPv6. In a Kubernetes setup, cookie-based affinity at the ingress is the more robust option, or forcing transports: ["websocket"] on the client to skip the multi-request polling phase entirely (at the cost of compatibility with networks that block WebSockets outright).

Diagnosing it in production

Poorly handled scalability has recognizable symptoms: notifications that only reach some users, seemingly at random (depending on which instance they landed on), abnormally high reconnection rates in the load balancer's metrics, or handshake errors that grow with the instance count. Turning on Engine.IO's server-side debug logs (DEBUG=socket.io:* node server.js) shows exactly which negotiation step a given connection is failing at.

When the easy fix isn't enough

Redis pub/sub solves event distribution, not guaranteed delivery: if an instance goes down between the emit and Redis's delivery, the event is gone, since pub/sub has no memory of what wasn't consumed. For cases where losing a message isn't acceptable (billing, syncing critical state), the "ephemeral broadcast" model isn't the right tool; reach for a durable message queue instead (Redis Streams, or a dedicated queue) consumed reliably, with Socket.IO scoped down to what it's actually good at: the last mile to the browser, not the guaranteed-delivery system itself.

Socket.IO handles casual real-time and non-critical UI updates very well once reconnection, state recovery, and the Redis adapter are configured correctly. For anything that needs guaranteed delivery, it's better to design for that explicitly from the start than to discover the limit in production.