In this lesson, you will learn how to maintain a consistent view of connected users across multiple server instances using an external data store.
The Challenge of Distributed Scaling
When you scale your Node.js application to multiple processes or servers, each instance maintains its own local memory of connected sockets. If a user is connected to Server A, and your load balancer directs a message request to Server B, Server B will have no idea that the user exists. To build a robust, horizontally scalable system, you must move your socket "presence" data out of server memory and into a centralized, fast-access store like Redis.
Centralized State Tracking
Instead of storing connection lists in a local Map or object, you treat your Redis instance as the "Source of Truth." Every time a socket connects, you add a record to Redis; when it disconnects, you remove it.
Here is how you might track a user's presence centrally:
// On 'connection' event
const userId = socket.handshake.query.userId;
const serverId = process.env.SERVER_ID;
// Track user location in Redis
await redis.hset('socket_registry', userId, serverId);
// On 'disconnect' event
await redis.hdel('socket_registry', userId);
Why Redis?
Redis is ideal here because of its atomic operations and sub-millisecond latency. When Server B needs to send a notification to a user, it queries the socket_registry hash in Redis. If the key exists, the value returned tells Server B exactly which server (e.g., "Server A") the user is connected to.
You can then utilize a Pub/Sub mechanism (or an inter-process communication bridge) to tell Server A to emit the message to that specific socket. By decoupling the connection from the server's local memory, your application becomes stateless, allowing you to spin up or terminate server instances without losing track of your users.
Key Takeaway: By moving socket state from volatile local memory into a centralized data store like Redis, you enable your real-time architecture to scale across any number of server instances while maintaining a global view of user connectivity.