Course contentsShow
← Node.js
Lesson 1126 of 1,98010. Real-time Communication and WebsocketsFree lesson

Designing Dynamic Room Discovery

You will build a registry service for finding available active rooms across a distributed system.

In this lesson, you will learn how to architect a global registry that allows users to discover active WebSocket rooms across a distributed cluster of Node.js servers.

When your application scales across multiple instances, a user connected to Server A has no inherent way of knowing which rooms exist on Server B. To solve this, we implement a Room Registry Service. This acts as a "source of truth" that keeps track of room availability, occupancy, and their host server metadata.

The Registry Pattern

Rather than letting servers manage room state in isolation, we use a centralized store—typically Redis—to maintain a directory. Whenever a room is created or a user joins, the specific server instance updates the registry.

Here is a simplified pattern for how a server registers a room:

// On the server managing the room
async function registerRoom(roomId, serverId) {
  const roomData = { roomId, serverId, timestamp: Date.now() };
  // Store in Redis with an expiration (TTL) to handle heartbeat/disconnects
  await redis.set(`room:${roomId}`, JSON.stringify(roomData), 'EX', 60);
}

The Discovery Flow

When a user wants to find a room, they don't query every server individually. Instead, the client requests the registry. The registry service returns a list of active rooms along with the serverId where each room resides.

If the user tries to join a room located on a different server, your WebSocket Proxy Layer (which you learned about in lesson 10) uses the serverId metadata to route the connection to the correct instance. By decoupling the "discovery" (where the room is) from the "connection" (the socket itself), you allow your cluster to grow dynamically without hardcoding room locations.

This design ensures that your room list is always live. If a server goes down, its rooms expire from the registry via the TTL, preventing users from attempting to connect to non-existent nodes.

Key Takeaway: By using a shared registry with TTL-based entries, you decouple room location from specific server instances, allowing your cluster to dynamically announce and discover active rooms in real-time.