16 / 17

How do you implement sticky sessions with Node.js clustering?

Sticky sessions ensure that requests from the same client always reach the same worker. This is achieved using Nginx ip_hash directive, the socket.io-sticky package, or Redis adapters for WebSocket applications, ensuring session continuity across requests.

By default, the cluster module distributes connections using round-robin, so the same client's requests can land on different workers each time. This breaks features that rely on in-memory state per worker, like WebSocket connections or server-side sessions stored in memory. Sticky sessions route each client consistently to the same worker based on IP or session cookie.

Sticky Sessions with Nginx ip_hash (Recommended for Production)
Sticky Session Strategies
  1. 1

    Nginx ip_hash — routes same client IP to same upstream server (most common)

  2. 2

    HAProxy source balance — similar to ip_hash but with more configuration flexibility

  3. 3

    socket.io-sticky npm package — lightweight sticky session support for cluster module

  4. 4

    Cookie-based routing — load balancer reads a session cookie to determine the target worker

  5. 5

    Redis adapter for Socket.IO — allows events to broadcast across all workers, reducing need for strict stickiness