Why WebSockets don’t scale easily — and how AWS changes the game
From the publisher’s feed, collected in the ZeroLabs newsroom.
WebSockets are deceptively simple. Every connected user maintains a persistent connection to the server, and each connection continuously occupies server resources such as memory, CPU cycles, network buffers, and application state. Unlike traditional HTTP requests, WebSocket connections are long-lived and stateful, meaning resource consumption grows almost linearly with the number of users. You can, however, derive a simple mathematical model to introduce the problem.The fundamental problemEvery active WebSocket connection consumes server resources. For each connection, a Node.js process maintains:A TCP socketRead/write buffersEvent listenersUser session metadataHeartbeat/ping stateSo:Total Memory=N×McwhereN = number of concurrent usersMc = memory consumed per connectionResource usage assumptions for 1000 concurrent users establishing WebSocket connectionsThe following estimates assume:1,000 simultaneously connected clientsClients are mostly idle (heartbeat/ping messages only)Small text messages (less than 1 KB)No large binary payloadsOne Node.js processLinux serverTLS termination handled separately (or already accounted for)Figures represent application memory only, not total system memory(These are realistic ballpark figures (actual values vary by implementation).Resource Usage for Raw WebSocket (ws node.js package) implementationThe ws library is a lightweight implementation that exposes the WebSocket protocol with minimal abstraction.Typical per-connection memory consumption:Memory:1000 × 30KB = 30,0000KB≈ 29 MBResource Usage for Socket.IO package implementationSocket.IO builds on top of WebSockets (via Engine.IO) and adds higher-level functionality such asEngine.IO layerRoomsAcknowledgementsAutomatic reconnectionPacket encodingAdditional metadataTypical per-connection memory consumption:Memory:1000 × 600KB = 60,000KB≈ 58 MBVisual comparisonThis is approximately linear growth:Memory ∝ Number of ConnectionsBut memory isn’t the real problemMemory is only one dimension. Suppose an EC2 instance has:2 GB RAM1 vCPUIf your application itself consumes:500 MB for Node.js application code200 MB for caches300 MB OS overheadAvailable for WebSockets:2GB − 1GB = 1GBUsing raw WebSockets:1000MB ÷ 30KB ≈ 34,000 theoretical connectionsUsing Socket.IO:1000MB ÷ 60KB ≈ 17,000 theoretical connectionsIn reality, CPU, network bandwidth, and event-loop latency become bottlenecks much earlier (often around 5k — 20k connections per Node process depending on message frequency).The scalability challengeThe issue isn’t serving 1,000 users. The issue is serving 100,000 users.If one server holds 10,000 persistent connections:100,000 ÷ 10,000 = 10 serversNow you must manage:Load balancingSticky sessionsCross-instance pub/subConnection failoverRedis adaptersAuto scalingAt that point, WebSockets become a distributed systems problem rather than a networking problem.Scaling WebSockets with Node.js, Nginx, and Redis Pub/SubTo move beyond a single-server bottleneck, WebSocket connections are typically distributed across multiple Node.js instances running in a cluster behind a reverse proxy like Nginx.Figure: High-Level Architecture supporting scalable WebSocket with Redis Backplane.At a high level, the architecture looks like this:Nginx handles incoming WebSocket upgrades and load balances connections across Node.js upstream servers.Each Node.js instance manages only a subset of active connections.A Redis Pub/Sub layer synchronizes messages across all instances.This solves a key limitation: WebSocket connections are stateful, so without coordination, one server cannot notify clients connected to another server.We can model the scaling behavior as:N = n_1 + n_2 + n_3 + … + n_kWhere:N = total concurrent connectionsn_k = connections handled by each Node.js instanceIf each instance supports ~10,000 connections:100,000 users ≈ 10 Node instancesHowever, connection distribution alone is not enough. Message propagation requires cross-instance communication:Client A → Node A → Redis Pub/Sub → Node B, Node C → ClientsSo Redis acts as the “event backbone”, ensuring messages reach all subscribed instances regardless of which server holds the original socket.In practice, the system scales in two dimensions:Vertical (per node): limited by memory per connectionHorizontal (cluster): limited by coordination overhead (Redis + network hops)This architecture allows WebSockets to scale from thousands to hundreds of thousands of concurrent connections, but introduces a new tradeoff: distributed complexity replaces single-server simplicity.The operational cost of self-managed WebSocket scalingOnce WebSockets are distributed across multiple Node.js instances with a load balancer and a Redis Pub/Sub backbone, the system becomes functionally scalable but operationally heavy.At this stage, scaling is no longer just about handling connections; it requires continuous management of infrastructure behavior in real time.Engineers must now monitor and tune:Connection distribution across nodes (to avoid uneven load)Memory per instance (to prevent socket exhaustion)Redis Pub/Sub throughput and latencyMessage fan-out patterns across servicesNetwork hops introduced by inter-node communicationFailure recovery and reconnection storms during outagesIn essence, the system shifts from a simple connection model to a continuously evolving distributed system where every component becomes a potential bottleneck.The AWS approach: Offloading the complexityManaged AWS WebSocket solutions, such as API Gateway WebSockets, fundamentally change this model by removing the need to manage persistent connection infrastructure directly.Instead of maintaining Node.js servers for connection handling, AWS takes responsibility for:Maintaining persistent WebSocket connections at scaleHandling connection lifecycle (establish, reconnect, disconnect)Scaling underlying infrastructure automaticallyRouting messages to connected clients via managed APIsIntegrating with backend services through AWS Lambda, SQS, or EventBridgeIn this model, engineers no longer manage sockets as infrastructure primitives. Instead, they work with higher-level events:Client Event →AWS API Gateway → Compute Layer (Lambda / Service) → Event Routing Back to ClientsWhat this removes from engineering ownershipMoving to AWS-managed WebSockets shifts responsibility away from engineers in several critical areas:No server provisioning or horizontal scaling for WebSocket nodesNo load balancer tuning or sticky session managementNo Redis Pub/Sub coordination layerNo manual connection tracking or socket state distributionNo handling of connection spikes or reconnection stormsNo direct memory management per connectionSimple 1-to-1 Chat using AWS API Gateway WebSocketsThis is a minimal architecture for building a real-time 1-to-1 chat system using AWS-managed WebSockets. The goal is to avoid managing servers, connection state, or scaling logic manually.Create a WebSocket API in API GatewayIn AWS API Gateway, create a WebSocket API. You will be asked to define a Route Selection Expression, typically: request.body.actionThis means every incoming message is routed based on the action field in the JSON payload.Figure: Create a WebSocket API (websocket-1–1-chat) in API Gateway with a route selection expressionFigure: Define custom route key (sendMessage) for integrationOnce created, API Gateway provides:WebSocket Endpointwss://{api-id}.execute-api.{region}.amazonaws.com/{stage}Connection URL (HTTP POST)https://h7axxxxxxx.execute-api.us-west-2.amazonaws.com/production/@connectionsFigure: WebSocket Endpoint and @connection URL endpoint of websocket-1–1-chat APIWhat they mean:WebSocket Endpoint → used by clients to connect and stay connected in real timeManagement / POST endpoint → used by backend (Lambda) to send messages to a specific connected clientUnderstanding Route KeysAPI Gateway uses route keys to decide how messages are handled:Built-in routes:$connectTriggered when a client first connects→ Used for authentication and initialization$disconnectTriggered when a client disconnects→ Used for cleanup$defaultTriggered when no matching route is found→ Catch-all for messagesCustom route exampleIf a client sends:{ "action": "sendMessage", "toUserId": "user_2", "message": "Hello"}Then API Gateway routes it to:sendMessageYou must explicitly create this route in API Gateway.Wire Routes to Lambda FunctionsEach route is connected to a Lambda:This is done in API Gateway → Routes → Attach Integration.Figure: Attach integrations for $connect, $disconnect, $default and sendMessage route keysStore Connection IDs in DynamoDBEvery connected client gets a unique: connectionIdDuring $connect, store this in DynamoDB:Table: ConnectionsuserIDconnectionsuser_1abc123user_2xyz789This allows you to map:userId → connectionIdWithout this, you cannot target specific users.Sending a Message (1-to-1 Flow)Figure: Flow diagram for API Gateway and Lambda interactions based on route keysWhen user_1 sends a message to user_2:Step 1: User 1 sends a message{ "action": "sendMessage", "toUserId": "user_2", "message": "Hey!"}Step 2: Lambda receives the requestThe messageHandler Lambda:Reads sender (user_1)Reads recipient (user_2)Looks up user_2 in DynamoDBRetrieves connectionIdStep 3: Forward message using API Gateway Management APILambda calls:POST /@connections/{connectionId}Payload:{ "from": "user_1", "message": "Hey!"}This sends the message directly to user_2’s active WebSocket connection.$Disconnect CleanupWhen a user disconnects:$disconnect route triggersRemove their connectionId from DynamoDBThis prevents stale connections and ensures accurate routing.Final architecture flowUser 1 → WebSocket API Gateway → Lambda (sendMessage) → DynamoDB lookup (user_2 connectionId) → API Gateway Management API → User 2 receives messageFigure: Rough sequence diagram representing user_1 sending a message to user_2 involving API Gateway and Lambda IntegrationsAWS advantage with a tradeoffWith AWS API Gateway WebSockets, there are:No servers to manageNo Redis Pub/Sub requiredNo connection scaling logicNo load balancers or sticky sessionsYou only define:Routes ($connect, $disconnect, custom actions)Lambda logicConnection storage (DynamoDB)AWS handles persistent connections, scaling, and delivery infrastructure automatically, allowing you to focus purely on application logic rather than socket management.The tradeoffWhile self-managed architectures offer full control and lower per-request cost at scale, they require deep operational expertise in distributed systems.AWS-managed WebSockets reduce this burden by abstracting connection management entirely, but in exchange, they introduce constraints in protocol control, cost predictability at extreme scale, and platform dependency.In practice, the decision is not about capability, but about where you want complexity to live:Self-managed WebSockets: maximum control, maximum operational responsibilityAWS-managed WebSockets: reduced control, significantly reduced infrastructure burdenWhy WebSockets don’t scale easily — and how AWS changes the game was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.