Startup — Scaling Applications

Scaling WebSockets for Real-Time Features

Direct answer

To scale WebSockets past one server, make each server stateless about who's connected elsewhere: clients connect through a load balancer to any socket node, and a shared message bus (Redis pub/sub for best-effort fan-out, or Redis Streams/a queue when messages must not be lost) delivers each event to whichever nodes hold the recipients. Then handle the parts that break in production: heartbeats so proxies don't close idle connections (nginx and AWS ALB default to 60 seconds), reconnect with backoff and missed-message catch-up on mobile, and auth on every connection. Persist important messages in the database first; the socket is a delivery hint, not the source of truth.

A single WebSocket server is easy: keep a dictionary of connected users and send them messages. It works perfectly in development and falls over the day you add a second server, put a proxy in front, or ship to phones that change networks on every walk to the train. This guide covers the architecture that holds up for chat, live order and driver tracking, presence and in-app notifications — what to build, the configuration details that cause most outages, and when paying for a managed service is the smarter move.

Phone A Phone B Web Load balanceridle timeout · TLS Socket node 1 Socket node 2 Socket node 3 Redispub/sub · streams API Postgres 1 · save 2 · publish 3 · deliver to local sockets

Key facts, with sources

  • The WebSocket protocol (RFC 6455) enables two-way communication over a single TCP connection, and its Ping frame may serve as a keepalive or to check that the other side is still responsive. (IETF RFC 6455)
  • Behind nginx, a WebSocket connection is closed by default if the proxied server sends no data within 60 seconds; proxy_read_timeout or periodic ping frames prevent it. (nginx docs)
  • Elastic Load Balancing sets an Application Load Balancer's connection idle timeout to 60 seconds by default (configurable from 1 to 4,000 seconds). (AWS docs)
  • Redis Pub/Sub has at-most-once delivery: a message a subscriber can't handle (for example, during a disconnect) is lost; Redis Streams persist messages and support at-least-once delivery. (Redis docs)

Why one server works and two don't

On a single server, "send this message to user 42" is a dictionary lookup: find user 42's socket, write to it. Add a second server behind a load balancer and user 42 might be connected to the other one. The server handling the event has no idea, so the message silently goes nowhere — the classic "chat works for some people" bug.

Every scalable design solves the same problem: decouple who produces an event from where the recipient happens to be connected. The common way is a shared message bus that every socket node subscribes to. When something happens, it is published once; each node delivers it to whichever of its local connections should receive it.

The core pattern: save, publish, deliver

The ordering matters more than the tools. First, the API saves the event (the chat message, the order status change) in the database — that is the source of truth. Second, it publishes a small notification to the bus on a channel for that conversation or user. Third, every socket node subscribed to that channel pushes it to its local connections.

Because the database write comes first, a lost socket message is an inconvenience, not data loss: the client can always fetch what it missed. That's why Redis pub/sub — which is explicitly at-most-once — is fine for fan-out here. If you need the bus itself to guarantee delivery (for example, events that drive billing or downstream jobs), use Redis Streams or a real queue instead, which persist messages and support at-least-once delivery.

FastAPI socket node: subscribe once, deliver to local connections
import asyncio, json
from collections import defaultdict
from fastapi import FastAPI, WebSocket, WebSocketDisconnect
import redis.asyncio as redis

app = FastAPI()
r = redis.from_url("redis://localhost:6379")
local: dict[str, set[WebSocket]] = defaultdict(set)  # room -> sockets on THIS node

@app.on_event("startup")
async def listen():
    async def pump():
        pubsub = r.pubsub()
        await pubsub.psubscribe("room:*")
        async for msg in pubsub.listen():
            if msg["type"] != "pmessage":
                continue
            room = msg["channel"].decode().split(":", 1)[1]
            for ws in list(local[room]):
                await ws.send_text(msg["data"].decode())
    asyncio.create_task(pump())

@app.websocket("/ws/{room}")
async def socket(ws: WebSocket, room: str):
    user = await authenticate(ws)  # verify token BEFORE accepting
    if not user or not await can_join(user, room):
        await ws.close(code=4401)
        return
    await ws.accept()
    local[room].add(ws)
    try:
        while True:
            await ws.receive_text()  # client pings / acks
    except WebSocketDisconnect:
        local[room].discard(ws)

# in the HTTP API, after saving the message to Postgres:
async def publish_message(room: str, message: dict):
    await r.publish(f"room:{room}", json.dumps(message))

Load balancers, proxies and the 60-second disconnect

The most common production outage with WebSockets isn't load — it's configuration. Proxies and load balancers close connections that look idle. Both nginx (proxy_read_timeout) and AWS Application Load Balancers default to 60 seconds, so a quiet chat screen drops every minute, reconnects, and drops again.

The fix is twofold. Send a heartbeat (a WebSocket ping or a tiny application message) every 20–30 seconds so the connection is never idle long enough to be cut, and raise the proxy timeout to comfortably exceed the heartbeat. Also make sure the proxy forwards the Upgrade and Connection headers — nginx does not pass them by default — or the handshake never becomes a WebSocket at all. Sticky sessions are only needed if you use a library that starts with HTTP long-polling before upgrading; pure WebSocket connections stay on the node they connected to.

nginx in front of socket nodes
map $http_upgrade $connection_upgrade {
    default upgrade;
    ''      close;
}

upstream sockets { server 10.0.0.11:8000; server 10.0.0.12:8000; }

server {
    location /ws/ {
        proxy_pass http://sockets;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $connection_upgrade;
        proxy_read_timeout 120s;   # longer than the app's 25s heartbeat
    }
}

Mobile clients: reconnects, backoff and catch-up

Phones are the hard part. They switch between Wi-Fi and cellular, go through tunnels, and get backgrounded — at which point the OS suspends the socket. A mobile real-time client needs to assume the connection is temporary.

Three rules. Reconnect with exponential backoff plus random jitter, so that when a server restarts, thousands of phones don't reconnect in the same second. On every reconnect, fetch what was missed since the last event the client saw (by message ID or timestamp) over plain HTTP — this is where saving first pays off. And don't rely on the socket while the app is in the background; use push notifications for that, and reconnect when the app returns to the foreground. On Streetgains, a social marketplace I worked on, the chat used WebSocket subscriptions with an offline message queue for exactly this reason: messages written while offline had to survive and send when the connection came back.

React Native: reconnect with backoff + catch-up
let attempt = 0;
let lastSeenId: string | null = null;

function connect(room: string, token: string) {
  const ws = new WebSocket("wss://api.example.com/ws/" + room + "?token=" + token);

  ws.onopen = async () => {
    attempt = 0;
    const missed = await fetchMessagesSince(room, lastSeenId); // HTTP catch-up
    missed.forEach(applyMessage);
  };

  ws.onmessage = (e) => {
    const msg = JSON.parse(e.data);
    lastSeenId = msg.id;
    applyMessage(msg);
  };

  ws.onclose = () => {
    const delay = Math.min(30000, 1000 * 2 ** attempt) * (0.5 + Math.random());
    attempt += 1;
    setTimeout(() => connect(room, token), delay);
  };
}

Capacity, presence and the numbers to watch

Each open WebSocket costs memory and a file descriptor on the node, and almost nothing in CPU while idle. Capacity planning is therefore mostly about concurrent connections and message fan-out, not requests per second. Raise the OS file-descriptor limit, keep per-connection state small, and measure how many connections a node holds comfortably under your real message rate before you need it.

Presence (online/typing indicators) is the feature that quietly gets expensive: if every typing event fans out to every member of a large room, traffic grows with the square of the room size. Throttle typing events, expire presence with short TTLs in Redis instead of tracking every disconnect perfectly, and only send presence for rooms a user is actually viewing.

MetricWhat it tells youAction when it climbs
Concurrent connections per nodeMemory and file-descriptor headroomAdd nodes; check FD limits
Reconnects per minuteNetwork trouble, timeouts or a bad deployCheck proxy timeouts and heartbeat
Publish-to-deliver latency (p95)Bus or node saturationShard channels, scale Redis
Messages per connection per minuteChatty features (typing, presence)Throttle and batch events
Catch-up fetches after reconnectHow often sockets miss eventsHealthy if small; investigate spikes
Real-time systems fail as reconnect storms and fan-out spikes far more often than as raw load.

Build it yourself or use a managed service?

Running your own socket layer is very doable with the pattern above, and it keeps costs low and data in your infrastructure. But it is a system you own on call: deploys that drop connections gracefully, Redis availability, reconnect storms, scaling nodes.

Managed real-time services (Supabase Realtime, Firebase, Ably, Pusher and similar) take that operational load away, at a per-connection or per-message price. For an MVP or a team without backend on-call, a managed service is usually the right first choice. Self-hosting starts to win when message volume makes per-message pricing painful, when you need custom server-side logic on every event, or when data residency rules require it.

OptionBest forTrade-off
Managed serviceMVPs, small teams, fast launchPer-message cost at scale; less control
Self-hosted + Redis pub/subBest-effort fan-out with DB as truthYou run it; messages can drop (by design)
Self-hosted + Streams / queueEvents that must not be lostMore moving parts, consumer management
PollingUpdates every few seconds are fineSimple and robust; not instant
Many products start managed or with polling, then self-host once volume and requirements are clear.

When to hire senior help

Bring in senior scaling expertise when growth becomes predictable rather than hypothetical, for example ahead of a marquee launch, an enterprise contract with an SLA, or sustained traffic doubling, because retrofitting performance under fire costs far more than a proactive audit. An experienced engineer can usually identify the two or three genuine bottlenecks in days, which prevents both outages and the overbuilding that inflates cloud waste. If your stack includes React Native + Python + AI, a senior engineer who owns the full product beats coordinating multiple juniors.

Bottom line

Dhairya Senjaliya ships Startup — Scaling Applications projects worldwide — book a scoping call to discuss your specific situation.

Common pitfalls to avoid

  • ✕Scaling infrastructure by throwing bigger instances at an unindexed database, paying 10x compute costs to mask a query problem a day of profiling would fix.
  • ✕Provisioning Kubernetes clusters and multi-region failover for a pre-product-market-fit app, joining the roughly 27 percent of cloud spend that benchmark reports classify as waste.
  • ✕Having no load testing before a launch or press moment, so the first real traffic spike doubles as the first capacity test in production.
  • ✕Ignoring N plus 1 queries and missing caches because pages feel fast with 100 test users, then hitting timeouts at 10,000 users when the fix requires schema changes.

Frequently asked questions

How do you scale WebSockets across multiple servers?

Let clients connect to any node through a load balancer and use a shared message bus — commonly Redis pub/sub — so an event published once is delivered by whichever nodes hold the recipients' connections. Save events to the database first so missed messages can be fetched.

Why do my WebSocket connections drop every 60 seconds?

Usually a proxy or load balancer idle timeout. nginx and AWS Application Load Balancers both default to 60 seconds. Send a heartbeat every 20–30 seconds and raise the proxy timeout above that interval.

Is Redis pub/sub reliable enough for chat?

Yes, if the database is the source of truth. Redis pub/sub is at-most-once, so a disconnected subscriber can miss a message — clients should fetch missed messages on reconnect. Use Redis Streams or a queue when the bus itself must guarantee delivery.

Do I need sticky sessions for WebSockets?

Not for plain WebSocket connections, which stay on the node they connect to. Sticky sessions matter when a library starts with HTTP long-polling before upgrading, because those polling requests must reach the same node.

Should a React Native app keep a WebSocket open in the background?

No — the OS suspends it. Use push notifications while the app is backgrounded, then reconnect and fetch missed events when it returns to the foreground.

At what point should a startup start investing in scalability?

Invest when you have evidence of demand, not before: Startup Genome data ties 74 percent of high-growth startup failures to premature scaling of some kind. The practical approach is to keep architecture simple, instrument everything, and fix the specific bottlenecks that monitoring reveals as real usage grows.

How much does slow performance actually cost?

The Deloitte and Google Milliseconds Make Millions study found even a 0.1 second mobile speed improvement lifted retail conversions by 8.4 percent, and downtime data shows outages costing five figures per minute at enterprise scale. For early products the cost shows up as bounce and churn rather than an invoice, which makes it easy to underestimate.

How do I keep cloud costs under control while scaling?

Flexera's 2025 data shows organizations waste roughly 27 percent of cloud spend, mostly on oversized instances, orphaned resources, and unused commitments. The highest-leverage steps are tagging resources by feature, rightsizing on a schedule, using savings plans for stable baseline load, and reviewing the bill monthly like any other major expense line.

Bottom line: Dhairya Senjaliya ships Startup — Scaling Applications projects worldwide. Book a scoping call at https://dhairyasenjaliya.com/#book-call.

Sources

Related guides

Keep up with new guides

New deep-dive guides on React Native, Python, and AI ship regularly. Subscribe via RSS or follow on LinkedIn.

Want help implementing this?

30-minute scoping call · Clear milestones · Senior engineer ownership