We are designing a real-time WebSocket system at scale. The key requirements are:
Connection fanout: When a message is sent to a user (or a group), it must be broadcasted to all their connected clients (which could be multiple devices).
Presence: Track which users are online and on which devices (connections).
Backpressure: Handle slow clients and prevent a single slow client from affecting others.
Shard/region routing: Distribute connections across multiple servers and regions for scalability and low latency.
Graceful degradation: If parts of the system fail, the system should continue to operate with reduced functionality.
We'll design a system with the following components:
WebSocket Servers (WS Servers): These handle the WebSocket connections from clients. They are stateless in terms of user sessions (but stateful in terms of open connections) and are responsible for:
Accepting WebSocket connections.
Authenticating the user (via a token, for example).
Maintaining a mapping of user IDs to connections (for fanout) and connection IDs to user IDs (for presence and cleanup).
Receiving messages from the client and forwarding them to the message broker (for server-to-server communication) or directly to other connections if the recipient is on the same server.
Message Broker (e.g., Kafka, NATS, or a custom solution): This is the central nervous system for inter-server communication. It handles:
Fanout: When a message is sent to a user (or group), the message is published to a topic (or queue) that the recipient's WS server(s) are subscribed to.
Decoupling: Allows WS servers to be stateless in terms of which users are on which server.
Presence Service: A distributed service (or a feature within the message broker) that tracks user connectivity. It could be:
A separate service with a fast in-memory store (like Redis) that maps user IDs to a set of connection IDs and the WS server they are connected to.
Alternatively, we can use the message broker to publish presence updates (connect/disconnect) and have each WS server update its local state and also update the presence service.
Sharding/Region Routing: We need to route users to the nearest (or least loaded) WS server. This can be done by:
Having a load balancer (like HAProxy or a cloud load balancer) that directs WebSocket connections to WS servers based on region and load.
The load balancer might use consistent hashing (based on user ID) to ensure that a user's multiple connections go to the same server? Not necessarily, because a user might connect from multiple devices and we might want them on different servers for resilience. But for presence and fanout, we need to know on which server(s) the user is connected.
Backpressure:
At the WebSocket server level: We can use per-connection buffering and flow control. If a client is slow, we can buffer messages up to a limit and then start dropping or applying other policies (like pausing the read from the broker for that connection).
At the broker level: We can use a broker that supports consumer groups and per-consumer flow control (like Kafka). However, for real-time WebSocket, we want low latency, so we might use a broker that allows high throughput and low latency (like NATS) and implement backpressure at the WS server.
Graceful Degradation:
If the message broker is down, WS servers can buffer messages locally (with a limit) and try to reconnect to the broker. For fanout, if the recipient is on the same server, we can deliver directly without the broker.
If a WS server goes down, the presence service should detect the disconnect (via heartbeats) and update the presence. Clients will reconnect (automatically by the browser) to another server (via load balancer). The new server will then fetch the user's presence from the presence service and re-establish any necessary state.
Detailed Design:
Step 1: Connection and Authentication
Client connects to the load balancer, which routes to a WS server.
WS server performs authentication (e.g., JWT token). After authentication, the WS server knows the user ID.
Step 2: Presence Registration
The WS server generates a unique connection ID (for this connection) and stores in memory:
connection_id -> user_id, ws_server_id (or just the server can be inferred by the server's identity)
Then, the WS server sends a "connect" event to the presence service (via the message broker or direct API call) with:
{ user_id: ..., connection_id: ..., server_id: ... }
The presence service (which is a distributed key-value store) updates the set of connections for the user.
Step 3: Incoming Messages from Client
When a client sends a message (to a user or a group), the WS server:
a) Validates the message (format, permissions).
b) If the recipient is on the same server (checked by querying the presence service for the recipient's server), then send directly via the server's in-memory map of user_id to connections.
c) Otherwise, publish the message to the message broker on a topic that is relevant (e.g., "user.<user_id>" for direct messages, or "group.<group_id>" for group messages).
Step 4: Fanout via Message Broker
The message broker has topics (or subjects in NATS) that are named by user ID (or group ID).
Each WS server subscribes to the topics for the users that are currently connected to it. So when a message is published for user X, all WS servers that have user X connected will receive the message (but only the server that has the connection will actually have the connection in its local map). However, note that a user might be connected to multiple servers (multiple devices). So each server that has at least one connection for user X should receive the message and then fanout to all connections for user X on that server.
Alternatively, we can have the message broker deliver to every server, and each server checks if it has any connections for the user. But that would be inefficient if we have many servers and each user is only on one. So we can use a hashing scheme to route messages to the specific server(s) that have the user. However, because a user can be on multiple servers, we need to deliver to all of them.
Option 1: Each WS server subscribes to all user topics (wildcard) but that is not scalable because the broker would have to route every message to every server.
Option 2: We use a consistent hashing ring for user IDs to a set of server nodes. But then if a user is on multiple servers, we have a problem because the hash would point to one server.
Option 3: We use the presence service to tell the message broker which servers have the user? But then the broker would need to maintain a mapping of user to servers, which is essentially the same as the presence service.
Alternatively, we can design the message broker to have a queue per user (or per user per server) and then have the WS servers consume from the queues for the users they host. But then when a user connects to a server, that server must start consuming from the user's queue.
Let's consider using a message broker that supports queue groups (like NATS) or consumer groups (like Kafka). We can have:
Each user has a topic (or queue) named by user ID.
When a WS server starts up, it does not subscribe to any user topics by default.
When a user connects to a WS server, that server subscribes (or starts consuming) from the user's topic (queue) for that user. But note: if the same user is connected to multiple servers, then multiple servers will be consuming from the same user queue? That would result in each server getting a subset of the messages (competing consumers). We don't want that; we want every server that has the user to get every message for that user.
So we need a publish-subscribe model per user. In NATS, we can have a subject per user and then each server that has that user subscribes to that subject. That would work because NATS will deliver every message to every subscriber.
However, if we have a million users and each server only has a fraction, then we would have a lot of subscriptions and the broker would have to maintain all these subscriptions and route messages accordingly. This might not scale to millions of users and thousands of servers.
Alternative: Instead of having a topic per user, we can have a few topics (sharded by user ID) and then each server subscribes to all topics (or a subset) and then filters locally. But then each server would receive every message for every user in the shard, which is wasteful.
Given the scale, we might need to use a different approach:
We can have a two-level system:
Level 1: When a message is sent to a user, we first look up the presence service to get the set of server IDs that have the user. Then, we publish the message to a topic that is named by the server ID (or a set of server IDs). But then the message broker would need to maintain a mapping of user to servers? That's the same as the presence service.
Alternatively, we can have the message broker maintain a routing table? That's complex.
Let's think about the requirements: We want to send a message to a user and have it delivered to all connections of that user, regardless of which server they are on.
We can do:
The WS server that receives the message from the client (the sender) publishes the message to a broker topic that is named by the recipient user ID (or group ID).
The broker then, for each message, looks up which servers have the user (by querying the presence service? or by having the presence service update the broker?) and then forwards the message to only those servers.
But then the broker becomes stateful and must maintain the routing table, which is a challenge at scale.
Alternatively, we can have the presence service be the one that routes the message?
Another idea:
We have a global, distributed, in-memory key-value store (like Redis Cluster) that maps user IDs to a set of server IDs (or connection IDs).
When a WS server receives a message for a user, it:
a) Looks up the set of server IDs for the user from the presence store (or from a local cache that is updated by the presence service).
b) For each server ID in the set, it sends the message to that server (via the message broker, but now we are sending to specific servers).
But then we are doing fanout from the sender's server to multiple servers. This might be acceptable if the number of servers per user is small (typically 1-5). However, if a user is connected to 100 servers (unlikely) then the sender's server would have to send 100 messages.
We can also have the presence service push the message to the servers? But then the presence service becomes a message broker.
Given the complexity, I think the simplest is to use a message broker that supports wildcard subscriptions and then have each WS server subscribe to the user topics for the users that are connected to it. But as noted, this might not scale to millions of users.
However, note that each user is typically connected to only a few servers (one per device). So the total number of subscriptions is (number of users * average connections per user). If we have 100 million users and each has 2 connections on average, that's 200 million subscriptions. That's a lot for a broker.
We need to shard the subscriptions. We can shard by user ID: have multiple broker nodes and each broker node is responsible for a range of user IDs. Then, each WS server would connect to every broker node? Or we can have the WS servers connect to the broker node that is responsible for the user they have. But then a WS server that has users from multiple shards would need to connect to multiple broker nodes.
Alternatively, we can use a broker that is designed for large scale pub/sub, like Redis Pub/Sub with sharding (Redis Cluster) or a custom solution.
Given the time, let's assume we use a broker that can handle the number of subscriptions (or we use a design that reduces subscriptions).
Revised approach:
We can have:
A set of broker nodes, each responsible for a shard of user IDs (by consistent hashing).
Each WS server, when a user connects, subscribes to the user's topic on the broker node that is responsible for that user (by routing the user ID to the broker node).
Then, when a message is published for a user, it is sent to the broker node responsible for that user, and that broker node then forwards to all WS servers that are subscribed to that user (on that broker node). But note: a user might be connected to multiple WS servers, and those WS servers might be connected to multiple broker nodes? Not if we route the user to a single broker node for subscription.
However, if a user is connected to multiple WS servers, and each WS server is connected to the same broker node (for that user's shard), then the broker node will have multiple subscriptions for the same user (from different WS servers). That's acceptable because the broker will then deliver the message to each WS server that is subscribed.
But what if the user's connections are spread across WS servers that are connected to different broker nodes? Then we have a problem because the user's topic is only on one broker node (by sharding). So we must ensure that all WS servers that have the user subscribe to the same broker node (the one responsible for the user). That means we need to route the user to a specific broker node for subscription.
Steps:
When a user connects to a WS server, the WS server determines the broker node for the user (by consistent hashing of user ID) and then subscribes to the user's topic on that broker node.
When a message is sent to a user, the sender's WS server (or the application server) publishes the message to the broker node responsible for the user (by hashing the user ID). That broker node then delivers to all WS servers that are subscribed to that user (which are all the WS servers that have the user and have subscribed to that broker node).
But note: the sender's WS server might not be connected to the same broker node? It doesn't matter because the sender's WS server is just publishing to the broker node for the recipient user.
This design requires that every WS server is connected to every broker node? Not necessarily. Each WS server only needs to be connected to the broker nodes for the users that are connected to it. But then if a WS server has users from many shards, it must connect to many broker nodes. Alternatively, we can have each WS server connected to all broker nodes (if we have a fixed small number of broker nodes, say 10, then it's manageable). Then, when subscribing to a user, we subscribe on the broker node that is responsible for that user.
This design scales because the number of broker nodes is fixed (or grows slowly) and each WS server maintains a connection to each broker node. The broker node then handles the subscriptions for the users in its shard.
But note: the broker node must handle all the subscriptions for its shard. If we have 10 broker nodes and 100 million users, then each broker node is responsible for 10 million users. And each user has an average of 2 connections, so each broker node has 20 million subscriptions. That's a lot, but maybe manageable with a broker that is designed for high number of subscriptions (like NATS or a custom solution).
Alternatively, we can have the broker node not track individual subscriptions per user, but instead use a hierarchy:
We have a two-level topic structure: first level is the shard (broker node) and second level is the user? Not necessary.
Given the complexity, let's stick with the following:
We have a set of broker nodes (say, N nodes). We shard users by user ID modulo N (or consistent hashing) to assign each user to a broker node.
Each WS server maintains a connection to every broker node (so N connections per WS server).
When a user connects to a WS server, the WS server:
a) Looks up the broker node for the user (by hashing the user ID).
b) Subscribes to a subject (or topic) that is unique to the user and on that broker node. For example, if we use NATS, we might subscribe to "user.<user_id>" on the specific broker node (by connecting to that node). But note: NATS does not have built-in sharding, so we would have to run multiple NATS servers and route subscriptions to the correct server.
We can use a single NATS cluster with multiple nodes and use subjects that are hashed to nodes? Not directly.
Alternatively, we can use a message broker that supports partitioning (like Kafka) and then have each user's messages go to a partition (by user ID). Then, each WS server would consume from the partitions for the users it hosts. But then we have the same problem: the WS server would have to consume from many partitions.
Given the constraints, I think we should use a custom solution or a broker that supports a large number of subjects (like NATS) and then scale horizontally by having multiple broker nodes and using a proxy that routes messages to the correct broker node based on subject (user ID). This is essentially a sharded pub/sub system.
However, for the sake of this design, let's assume we have a message broker that can handle the load (or we use a combination of techniques).
Given the time, I'll simplify:
We'll use a single message broker cluster (like Kafka) with a large number of partitions (more than the number of WS servers). Then, we assign each user to a partition (by user ID). Then, each WS server will consume from the partitions for the users it hosts. But then the WS server would have to maintain a consumer for each user? That's not feasible.
Alternatively, we can have:
Each WS server, for each user it hosts, seeks to the partition for that user and then consumes. But then we have many consumers (one per user per server) and that's too many.
We need to group users into the same partition to reduce the number of consumers. But then if we group users, then the WS server would receive messages for multiple users in the same partition and then have to filter.
So we can do:
Let the number of partitions be, say, 1000.
Assign each user to a partition by user ID modulo 1000.
Then, each WS server that has users in partition P will have one consumer for partition P (and then it will receive all messages for all users in that partition). Then, the WS server will filter the messages for the users it actually hosts.
This way, each WS server has at most 1000 consumers (one per partition) and each consumer gets messages for many users. The WS server then maintains a map of user ID to connections and delivers the message to the appropriate connections.
But note: if a user is connected to multiple WS servers, then each WS server that has the user must be consuming from the partition that the user is assigned to. So all WS servers that have the user will get the message for that user (because they are all consuming from the same partition). Then, each WS server filters and delivers to its local connections.
This design requires that we assign users to partitions in a way that is consistent and known to all WS servers. We can compute the partition by: partition = hash(user_id) % 1000.
Steps for this design:
When a user connects to a WS server, the WS server:
a) Computes the partition for the user.
b) Ensures it has a consumer for that partition (if not, creates one).
c) Adds the user to its local map (user_id -> list of connections) and also records that this user is on this partition.
When a message is sent to a user (or group of users), the sender's WS server (or the application server) publishes the message to the partition(s) of the recipient user(s). For a group message, we might have to publish to multiple partitions (one per user in the group) or we can have a separate topic for groups?
For group messages, we can have:
Each group has a set of users. We can compute the set of partitions for the users in the group and then publish the message to each partition? That would be inefficient for large groups.
Alternatively, we can have a separate topic for groups, and then each WS server subscribes to the group topics for the groups that its users are in. But then we are back to the same problem of many topics.
Given the complexity, let's focus on 1:1 messages. For group messages, we can treat them as multiple 1:1 messages (fanout to each user) and publish to each user's partition. This might be acceptable for small groups, but for large groups (like a public channel) we need a different strategy.
For public channels (with many users), we can have:
Each channel has a dedicated partition? But then we might have millions of channels and only 1000 partitions. So we would have to map channels to partitions (by channel ID). Then, each WS server that has users in the channel would have to consume from that partition and then filter for the users in the channel that are on that server.
This is getting complex.
Given the time, I'll stick to 1:1 messages and leave group messages as an extension.
So for 1:1:
We have a Kafka cluster with 1000 partitions.
Each user is assigned to a partition by hash(user_id) % 1000.
Each WS server, for each partition that it has at least one user, runs a consumer for that partition.
When a message is sent to user X, the sender's server publishes to partition = hash(X) % 1000.
The message will be delivered to all WS servers that are consuming from that partition (i.e., all WS servers that have at least one user in that partition). Then, each WS server checks if it has user X and delivers to the connection(s) for user X.
This works, but note: if a partition has many users and is consumed by many WS servers, then each WS server will receive all messages for all users in that partition and then filter. This could be wasteful if the partition has many users but each WS server only has a few of them.
We can try to reduce this by having more partitions (so that each partition has fewer users) but then each WS server might have to consume from more partitions (if its users are spread out). There is a trade-off.
Given the scale, we might need to adjust the number of partitions.
Now, back to the original requirements:
Connection fanout: Achieved by having multiple connections per user and delivering to all connections on the server that has the user.
Presence: We have the presence service that tracks user to connections and server.
Backpressure: We can implement at the WS server level by:
code
- Having a per-connection message queue (with a max size).
- If the queue is full, we can either drop messages (with a policy: drop oldest, drop new, or block the producer) or apply flow control (pause reading from the broker for that partition? but note: the partition consumer is shared by all users on that partition, so pausing for one user would pause for all users on that partition).
Alternatively, we can have per-user queues on the WS server. Then, if a user's connection is slow, we buffer for that user up to a limit and then start dropping for that user. But then the broker is still sending messages for that user and we are dropping on the server.
We can also have the broker support flow control per consumer? Kafka does, but it's per partition consumer, not per user.
Given that we are using a partition-based design, we cannot easily apply backpressure per user. So we might have to accept that if one user is slow, it doesn't affect others on the same partition because we are filtering per user. But note: the consumer for the partition is shared, so if the WS server is slow to process messages for one user (because that user's connection is slow and we are buffering and then dropping) it might not affect the processing for other users because we are processing messages in order per partition. So if we are processing a message for a slow user and we are blocked (because we are waiting to write to the connection?) then we might block the processing of the entire partition.
We need to design the consumer loop to be non-blocking for the entire partition. We can:
code
- Have a per-user queue (bounded) and a dispatcher that sends messages to the connections. If a user's queue is full, we drop the message for that user and continue.
- The consumer from the partition reads messages and puts them into the per-user queues. If the per-user queue is full, we drop and continue.
This way, a slow user only affects their own queue, and the partition consumer can continue processing messages for other users.
However, if the partition has a very high rate of messages for one user, and that user's queue is full, then we will be dropping a lot of messages for that user. But that's acceptable because the user is slow.
Now, graceful degradation:
code
- If a broker node goes down, the partitions it hosts will be unavailable. We can have replication in Kafka, so if one broker node fails, the leader for the partition will move to another node. The WS servers will have to handle the rebalance and start consuming from the new leader. During this time, messages for users in those partitions might be delayed or lost? We can configure Kafka for durability, but there will be a failover time.
- If a WS server goes down, the connections are lost. The presence service will detect the disconnect (via heartbeats or the WebSocket close event) and remove the server from the user's presence. Then, when the user reconnects (automatically by the client) to another WS server, the new server will add the user to its local map and start consuming from the user's partition (if not already). The user might miss messages during the reconnection? We can have the new server fetch the missed messages from the broker? But the broker might have already delivered the messages to the old server (and the old server might have dropped them if the user was disconnected). We need to design the message delivery semantics: at-most-once? at-least-once? exactly-once?
For real-time chat, at-least-once is acceptable, but we might have duplicates. We can have the client handle duplicates by message ID.
We can also have the presence service track the last delivered message ID per user per server? That's complex.
Given the complexity, we might accept that during a server failure, the user might miss messages that were sent while they were disconnected. We can have the client request missed messages on reconnect? But then we need to store messages per user for a while. That's a different requirement (persistence).
Since the requirement is real-time and at scale, we might not store messages. So we accept that messages during disconnection are lost.
For graceful degradation:
code
- If the message broker is down, the WS servers can buffer messages for users that are connected locally (if the recipient is on the same server) and try to deliver when the broker comes back. But for cross-server messages, they will fail. We can have the WS server retry publishing to the broker (with exponential backoff) and buffer the message if it's from a client (for sending to another user) until the broker is back.
- If the presence service is down, the WS servers can continue to operate with their local presence information. When the presence service comes back, they can synchronize. But note: the presence service is used for routing (to know which server the user is on). Without it, we cannot route cross-server messages. So we might have to rely on the broker's partition assignment? Actually, we don't use the presence service for routing in the partition design. We use the partition assignment by user ID. So if the presence service is down, we can still route messages to the correct partition (by user ID) and then the WS servers that have the user will get the message. But note: the presence service is also used for tracking which users are online. If the presence service is down, we don't know if the user is online, but we can still try to deliver to the partition and the WS servers that have the user (if any) will deliver. However, if the user is not connected to any server, then we are delivering to no one. That's acceptable.
So the presence service is not critical for message delivery in the partition design? Actually, we use the partition assignment by user ID, so we don't need the presence service for routing. But we do need it for knowing if the user is online? That's a separate requirement (presence). For message delivery, we don't need to know if the user is online; we just publish to the partition and the WS servers that have the user will deliver if they are connected. But if the user is not connected, then the message is lost (unless we have persistence). So the presence service is only for presence indication (online/offline) and for the sender to know if the user is online? Not necessarily; the sender might not care. But in a chat app, the sender wants to know if the message was delivered? That's a read receipt, which is a different feature.
So in summary, the partition design does not rely on the presence service for routing, but the presence service is used for:
code
- Tracking which users are online (for presence indicators).
- For the sender to know which servers the user is on? Not in our design because we route by partition.
However, note: if a user is connected to multiple WS servers, they are all in the same partition (by user ID). So they will all get the message. That's fine.
But what if we want to send a message to a user and we want to know if at least one of their connections is online? We can use the presence service to check if the user has any active connections.
Given the above, we can have:
The presence service is updated by WS servers on connect/disconnect.
The presence service is used by the application (or the sender) to check if the user is online (for example, to show a green dot). But it's not used for message routing.
So the system can function without the presence service for message delivery, but presence indicators will be stale.
Now, let's put it all together:
Components:
Load Balancer: Routes WebSocket connections to WS servers (by region and load). Also, does TLS termination.
WebSocket Servers (WS):
Stateless in terms of user sessions (but stateful for open connections).
For each connected user, stores:
user_id -> set of connection_ids
For each partition that has at least one user, runs a Kafka consumer for that partition.
When a message arrives from a client (for a user or group), the WS server:
a) For a 1:1 message: computes the partition for the recipient user and produces the message to that partition in Kafka.
b) For a group message: for each user in the group, compute the partition and produce to that partition? Or we can have a separate topic for groups and then have each WS server subscribe to the group topics for the groups that its users are in? Let's skip group for now.
When a message is consumed from a partition (by the Kafka consumer), the WS server:
a) Extracts the user_id from the message (or the message is addressed to a user, so we have the user_id in the message).
b) Checks if the user_id is in its local map (i.e., the user has an active connection on this server).
c) If yes, for each connection for that user, send the message (with backpressure handling: if the connection's buffer is full, drop or apply policy).
On connect:
a) Authenticate, get user_id.
b) Generate connection_id.
c) Add to local map.
d) Compute partition for user (if not already consuming, start a consumer for that partition? Actually, we might already have a consumer for that partition because of other users. We just add the user to the local map and then the existing consumer for that partition will deliver messages for this user to this server. But note: the consumer for the partition is shared by all users on that partition on this server. So we don't need to start a new consumer per user. We have one consumer per partition per WS server.
On disconnect:
a) Remove from local map.
b) If no more users on a partition, stop the consumer for that partition? But then if a new user in that partition connects, we have to start again. We can keep the consumer running for a while (idle) or stop it. But starting and stopping consumers is expensive. We might keep a pool of consumers for the partitions that we have seen users in, and if a partition has no users for a while, we stop the consumer.
Presence Service:
A distributed key-value store (like Redis Cluster) that maps user_id to a set of server_ids (or connection_ids with server info).
WS servers update the presence service on connect and disconnect (with a TTL for heartbeats).
The presence service can be used by the application to show online status.
Backpressure:
code
- Each connection has a bounded buffer (say 1000 messages).
- When sending a message to a connection, if the buffer is full, we drop the message (and maybe log) and continue. We don't block the consumer thread.
Graceful Degradation:
code
- If Kafka is down:
* For messages sent to users on the same server: we can deliver directly (bypassing Kafka). But in our design, we always use Kafka for cross-server. For same-server, we could optimize by checking the presence service to see if the user is on the same server and then deliver directly. But note: the presence service might be stale. We can also have a local in-memory map on each WS server of user_id to connections (for users connected to that server). So when a message is sent to a user, we first check if the user is on the same server (by looking at the local map). If yes, deliver directly. If not, send to Kafka. This way, if Kafka is down, we can still deliver to users on the same server.
* But note: the sender's WS server might not have the user in its local map because the user is on a different server. So we cannot deliver without Kafka.
* So if Kafka is down, cross-server messages fail. We can buffer the message on the sender's server and retry when Kafka comes back.
- If a WS server goes down:
* The connections are lost. The presence service will eventually remove the server (via TTL or disconnect event). The user will reconnect to another server (via load balancer). The new server will start consuming from the user's partition and will get new messages. Old messages that were sent while the user was disconnected are lost (unless we have persistence and the new server can read from the last committed offset? But the new server doesn't know the last offset for the user. We could store the last read offset per user in the presence service? That's complex).
- If the presence service is down:
* WS servers continue to operate and update the presence service when it comes back (with the current state).
* The presence indicators (online/offline) will be stale, but message delivery is unaffected because we don't use the presence service for routing.
This design is complex and has many trade-offs. We might need to adjust based on the exact requirements (like group messages, persistence, read receipts, etc.).
Given the time, I'll stop here and summarize the design in a diagram and key points.
Diagram:
[Client] -> [Load Balancer] -> [WS Server 1] -> [Kafka] (partitions)
-> [WS Server 2] -> [Kafka]
-> ...
Each WS Server:
- Maintains: user_id -> set of connection_ids
- For each partition that has users, a Kafka consumer for that partition.
Steps:
Client connects to LB, LB routes to WS1.
WS1 authenticates, adds user to local map, and if not already, starts a consumer for the user's partition (or uses existing).
When user sends a message to another user X:
a) WS1 checks if X is in its local map (same server). If yes, send directly.
b) Else, produce to Kafka partition for X.
Kafka delivers to all WS servers that are consuming from that partition (including WS1 and others).
Each WS server that receives the message checks if it has X in its local map. If yes, send to all connections for X.
This design should scale with the number of WS servers and the number of partitions. The number of partitions should be chosen based on the number of WS servers and the average number of users per partition.
We must also consider:
How to handle group messages? We can have each group assigned to a partition (by group_id) and then each WS server that has at least one user in the group subscribes to that partition. Then, when a group message is sent, it is published to the group's partition and all WS servers that have users in the group get the message and then filter for the users that are in the group and on that server.
But note: a user might be in multiple groups. Then the WS server would have to subscribe to multiple partitions (one per group the user is in). That could be a lot.
Alternatively, we can handle group messages by:
code
- For each group, we have a list of user IDs. Then, for each user in the group, we publish to the user's partition (as if it's a 1:1 message). This is inefficient for large groups because we are publishing N times (where N is the group size). But then we are using the existing 1:1 path.
We might need to optimize for large groups by having a separate topic for the group and then having WS servers subscribe to the groups their users are in. But then we are back to the problem of many topics.
Given the complexity, I'll leave group messages as a future extension.
This design is a starting point and would need to be adjusted based on the actual scale and requirements.
I'll design a scalable WebSocket system that handles real-time communication at scale with all the requirements you've mentioned. Let me break this down into core components and patterns.
Fanout Paths:
1. Same-Shard Fanout (Fast Path):
- User A & User B on same shard → Direct in-memory fanout
- Latency: <1ms
2. Cross-Shard Fanout (Normal Path):
- User A (Shard 1) → User B (Shard 2) → Via Message Router
- Latency: 2-5ms (regional)
3. Multi-Region Fanout:
- Cross-region → Via global message bus
- Latency: 50-200ms (WAN)
Implementation Pattern
javascript
// Shard-local connection manager
class ShardConnectionManager {
constructor(shardId) {
this.userConnections = new Map(); // userId → Set<WebSocket>
this.shardId = shardId
Kafka Cluster:
With a fixed number of partitions (say 1000).
Each partition is consumed by multiple WS servers (one consumer per WS server per partition that has users in that partition).
Load Balancer:
Uses a round-robin or least connections to route WebSocket connections to WS servers in the same region.