<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Omkar Gade on Medium]]></title>
        <description><![CDATA[Stories by Omkar Gade on Medium]]></description>
        <link>https://medium.com/@omkargade?source=rss-210bff14ade3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*vo28oWxdPTaz8BcLHB_KSQ.jpeg</url>
            <title>Stories by Omkar Gade on Medium</title>
            <link>https://medium.com/@omkargade?source=rss-210bff14ade3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 18:28:20 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@omkargade/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Scalable WebSocket Server]]></title>
            <link>https://omkargade.medium.com/scalable-websocket-server-8ced3e0d772d?source=rss-210bff14ade3------2</link>
            <guid isPermaLink="false">https://medium.com/p/8ced3e0d772d</guid>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[redis-pub-sub]]></category>
            <category><![CDATA[kubernetes-hpa]]></category>
            <category><![CDATA[websocket-server]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <dc:creator><![CDATA[Omkar Gade]]></dc:creator>
            <pubDate>Mon, 28 Oct 2024 13:35:18 GMT</pubDate>
            <atom:updated>2024-10-30T18:54:53.308Z</atom:updated>
            <content:encoded><![CDATA[<p>Have you ever wondered how the backend of real-time applications, like <strong>multiplayer games</strong> (e.g., <a href="https://www.chess.com/"><em>Chess.com</em> </a>or <a href="https://www.gather.town/"><em>Gather.town</em></a>), <strong>trade exchange</strong> applications, or <strong>messaging</strong> platforms (e.g., <em>WhatsApp, Snapchat, or Instagram</em>) scales to support millions of users simultaneously? This article aims to break down the architecture of WebSocket server implementations for these types of real-time applications.</p><p>Let’s start by looking at the basic implementation of a <strong>WebSocket</strong> server in a messaging app scenario. Imagine two clients messaging each other over an <strong>HTTP</strong> server. Each time a client sends a message, an HTTP request is sent, a server thread is generated, and the message is processed and returned to the other client. This process is repeated for every message, which is inefficient as the threads are created and terminated repeatedly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/583/1*V5AOhDCksZJ_du0lGGKaEQ.jpeg" /><figcaption>HTTP Server</figcaption></figure><h4>Why Use a WebSocket Server?</h4><p>To overcome the limitations of HTTP in this context, a WebSocket server can be implemented. WebSocket is a bidirectional, full-duplex protocol ideal for client-server communication. After a successful handshake, clients are subscribed to the WebSocket server, creating a persistent connection.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/1*OhyHAjIltaxICKJ4ibbkjg.jpeg" /><figcaption>WebSocket Server</figcaption></figure><p>Now in a scenario of WebSocket server, how would we implement a messaging app? So in a WebSocket implementation, after the handshake between the client and the server is successful, the client is subscribed to the server.</p><p>Let’s say we have two clients subscribed to one WebSocket Server. When the client 1 sends a message to client 2, the server picks up the message and send it to the subscribed client 2 and this communication goes on until the connection terminates.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/824/1*Ct5Dzyfp1xDhhEq6O9e5Cg.jpeg" /><figcaption>WebSocket Messaging Server</figcaption></figure><p>Now the problem arises if there are a thousands of clients subscribed to a single WebSocket server. This would eventually increase the load on a single server and hence the performance of the application will slow down. Hence in this scenario, we will need to <strong>horizontally</strong> <strong>scale</strong> the instances i.e. we’ll need to increase the number of server(called <em>scale up event</em>) .</p><h4>Scaling WebSocket Servers with Kubernetes HPA</h4><p>For horizontal scaling, we can have an <a href="https://docs.aws.amazon.com/autoscaling/ec2/userguide/auto-scaling-groups.html"><em>AWS auto-scaling group</em></a> or <br><a href="https://kubernetes.io/docs/tasks/run-application/horizontal-pod-autoscale/"><em>Kubernetes’ Horizontal Pod Auto-scaler(HPA)</em></a>. Now that we have sufficient number of servers to handle the load, as the clients become active, they connect to a WebSocket server depending on the load present on each server. <br>However, a new challenge arises when clients are connected to different servers. For instance, if client 1 and client 2 are subscribed to WebSocket server 1 and client 3 is subscribed to WebSocket server 2, how does client 1 send a message to client 3?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/773/1*9haFh5GruY6e_CgaSUc_tg.jpeg" /></figure><p>A simple but impractical solution would involve having servers communicate through HTTP requests. But this approach is not advisable as its not a good practice for two WebSocket servers to communicate via a separate HTTP server.</p><p>Hence to resolve this problem, a better approach is to use a <strong>Publisher-Subscriber (Pub/Sub) broker</strong> to manage communication between multiple WebSocket servers.</p><h4>Using Redis Pub/Sub for Distributed Messaging</h4><p>In this approach, we will be using <a href="https://redis.io/docs/latest/develop/interact/pubsub/"><strong>Redis Pub/Sub</strong></a><strong> </strong>for message distribution across multiple server instances.</p><p>Whenever a new client connects to the server, they need to <strong>subscribe</strong> to <strong>Pub/Sub</strong> via a <em>channel </em>in this case, we will be creating <em>rooms</em>. And for two clients to chat among each other, they need to be subscribed to the same room, even if they are subscribed to different WebSocket server.</p><p>And when a client sends a message, the message is first sent to the server and the server then <strong>Publishes</strong> the message to all the <strong>Subscribed</strong> channels(in this case, <em>rooms</em>) across every WebSocket server instance. And eventually, the other client receives the message.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nKt2EsxDK__89IrFfltv5g.jpeg" /><figcaption>Pub/Sub Implementation via Redis</figcaption></figure><h4>Requirements of a scalable distributed signaling service</h4><p>Let’s recap the constraints of the problem that we are trying to solve:</p><ol><li><em>Distributedness constraint:</em> The system must guarantee that a message sent by a client will be correctly forwarded to its intended client<strong> </strong>even if they are <strong>not subscribed to the same instance</strong> as the sender.</li><li><em>Balance constraint:</em> In order for the system to be auto-scalable, the load (i.e. the number of active connections) across instances of the system must remain<strong> balanced</strong>, including when an instance is added or removed dynamically from the distributed service by Kubernetes’ HPA.</li></ol><p>The <strong>Distributedness Constraint</strong> is handled by using a <strong>Pub/Sub (Publisher/Subscriber) architecture</strong>. Here’s how it works: when a client connects to a WebSocket server, it subscribes to a channel, or <strong>room</strong>, in <strong>Redis Pub/Sub</strong>. This room acts as a shared space for messages between clients.</p><p>So, if Client 1 wants to send a message to Client 2, and they’re connected to different WebSocket servers, <strong>Redis Pub/Sub</strong> ensures the message still reaches its destination. Both clients are subscribed to the same Redis channel, or room, and Redis takes care of publishing the message to every server that has a client in that room. This way, even if clients aren’t on the same server, they can communicate as though they are.</p><p>The <strong>Balance Constraint</strong> becomes a challenge when we need to scale up our servers — meaning, when the demand on the system grows and we add more server instances to handle the extra load. Imagine a situation where we start with 2 WebSocket servers, each handling 100 client connections. As traffic increases, Kubernetes’ auto-scaling system(HPA) detects the higher load and spins up a 3rd server. It then informs the load balancer about this new server, which starts directing new WebSocket connections across all three servers.</p><p>Now, here’s the problem: If 30 new clients connect after this, they’re distributed evenly, but only among the servers with available capacity, leaving us with an imbalance: the first two servers now have 110 connections each, while the new server only has 10. This uneven distribution can cause resource management issues and would eventually affect the efficient scaling mechanism, especially when Kubernetes expects all server instances to have roughly the same load.</p><p>To address this, we need a load balancer that can manage the load more evenly by directing only new connections to the new instance while keeping existing connections where they are. This can be achieved using a load balancer like <strong>Nginx</strong> with the<a href="https://medium.com/@DanialEskandari/nginx-load-balancing-using-least-connection-algorithm-system-design-series-part-2-36068c1f7818"> <strong>least-connected</strong></a> algorithm rather than usual <strong>round-robin</strong> algorithm, which sends new connections to the server with the fewest active connections. This way, each server handles a fair share of the load, and new instances can gradually <strong>catch up</strong> with existing servers in terms of connection count.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ioKSwkYJrPD_2yKdjiqDRg.jpeg" /></figure><h4>Scaling the system for millions of concurrent users</h4><p>Now the above architecture would work fine if there are a thousand of users. But how can we make this system scalable to millions of concurrent users? Well to make it scalable and efficient earlier we would scale up the instances if the load increases, but just spinning up more instances would be enough to handle millions of users communicating frequently in an efficient manner?</p><p>One solution is to scale the <strong>Pub/Sub broker</strong> itself to increase throughput and reduce latency for message distribution. To accomplish this, we can use a <strong>Redis Cluster</strong>. Redis Cluster automatically manages load distribution and scaling of Pub/Sub brokers internally.</p><h4>Redis Cluster Architecture</h4><p><a href="https://redis.io/docs/latest/operate/oss_and_stack/management/scaling/"><strong>Redis Cluster</strong></a> enables us to run a Redis setup where data is automatically sharded across multiple Redis nodes. It also offers some level of availability during network partitions, allowing the system to continue functioning even if certain nodes go down. However, the cluster will become unavailable if a majority of its nodes fail.</p><ul><li><strong>Automatic Sharding and Replication</strong>: Redis Cluster handles data sharding and replication across multiple nodes, distributing the load efficiently and supporting failover.</li><li><strong>Multiple Redis Instances</strong>: Rather than relying on a single Redis instance for Pub/Sub, we can create multiple Redis instances. Messages are hashed by room/channel name to determine which Redis instance handles each, ensuring efficient load distribution.</li><li><strong>High Scalability</strong>: Redis Cluster can scale to thousands of nodes, abstracting the complexity of managing multiple Redis instances manually.</li></ul><h4>Introducing a Central Message Broker for Efficient Routing</h4><p>As the number of users and servers scales, relying solely on Redis Pub/Sub for message distribution becomes challenging. Redis Pub/Sub wasn’t designed to manage persistent, high-throughput messaging across numerous nodes. At this scale, a central <strong>message broker</strong> such as <a href="https://kafka.apache.org/"><strong>Kafka</strong></a> can act as an intermediary, providing durability, high throughput, and reliable message delivery. Kafka’s role is to manage message routing and offload Redis instances to reduce latency.</p><p>Here’s how this would work:</p><ol><li><strong>Message Broker as an Intermediary</strong>: Instead of publishing messages directly to Redis instances, servers publish them to Kafka. Kafka then routes messages to the appropriate Redis instances, which handle only a portion of channels.</li><li><strong>Room/Channel Subscription Queues</strong>: Each room/channel has a dedicated Kafka queue. Clients subscribe to the queue for their specific room/channel, while a pool of worker processes consumes these messages.</li><li><strong>Decoupling Publishing and Delivery</strong>: Workers broadcast messages to clients, decoupling the task of message publishing from delivery. This improves both reliability and scalability, as Kafka manages message flow while Redis serves as the final delivery point.</li></ol><p>By using Kafka as an intermediate message queue, we ensure messages are distributed to the correct Redis instance based on the channel or room. This architecture allows our WebSocket system to handle millions of concurrent users with greater efficiency and reduced latency.</p><p>Below is the final architecture for a Scalable WebSocket Server:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dTrMyV1cRHZ4ROuMCeTOAw.jpeg" /><figcaption>Final architecture</figcaption></figure><h4>Conclusion:</h4><p>In summary, building a scalable, distributed WebSocket server architecture for real-time applications like messaging, gaming, or live trading platforms involves addressing both distributed messaging and efficient load management. To achieve this, a combination of <strong>Redis Pub/Sub</strong> and <strong>Kafka</strong> as a central message broker ensures messages reach their intended recipients seamlessly, even across multiple server instances.</p><p>For load balancing, <strong>Kubernetes HPA</strong> dynamically scales the number of WebSocket servers based on demand, while a load balancer like <strong>Nginx</strong> with the least-connected algorithm distributes connections efficiently, ensuring all servers share the load evenly. For larger-scale applications, <strong>Redis Cluster</strong> manages sharded data across nodes, supporting automatic failover and maintaining high throughput.</p><p>This architecture — integrating Redis for distributed messaging, Kafka for efficient message routing, Kubernetes HPA for scaling, and Nginx for load balancing — creates a resilient, high-performing system. With these components, real-time applications can confidently support millions of users, providing low-latency, reliable connections across a global user base. This scalable setup ensures that, even as user counts increase, the system remains responsive, available, and able to deliver a seamless real-time experience to users worldwide.</p><p>I’ve built this system in Node.js and TypeScript with Redis for message distribution and designed it for scalability using Kubernetes’ Horizontal Pod Auto-scaler (HPA). The repository also includes scripts for deploying and configuring load balancing via K8s, allowing the WebSocket server to handle growing demand efficiently. Check out the code here: <br><a href="https://github.com/omkargade04/scalable-websocket-server"><strong>Scalable WebSocket Server</strong></a>.</p><p>Thank you for taking the time to read this post! Let me know your thoughts on this architecture and if there are any areas for improvement. I’d greatly appreciate your feedback!</p><p>You can contact me on<a href="https://x.com/OmkarGade04"> Twitter (@OmkarGade04)</a> or <a href="https://www.linkedin.com/in/omkar-gade-214b62253/">LinkedIn</a> if you have any question or comment.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8ced3e0d772d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>