HomeBlogHow to Build a Real-Time Web...

Engineering Guide · 8 min read · October 17, 2026

How to Build a Real-Time Web Application Using WebSockets

Spinning up a Socket.IO demo takes fifteen minutes; keeping WebSockets stable behind load balancers during reconnect storms takes deliberate architecture. Learn when to pick WebSockets over SSE, how to authenticate handshakes securely, and how to fan out events with Redis.

Author
Smit Desai
Published
October 17, 2026
Read time
8 min read
Topic
Full-Stack Web
Services
Custom Web · Mobile Apps · All Services

Building a real-time chat or live dashboard locally feels effortless. You install a WebSocket library, wire up two event listeners, and watch messages appear across browser tabs in milliseconds. Then you deploy behind Nginx or a cloud load balancer, scale to two app containers, and everything starts dropping silently.

Unlike standard REST requests that finish in 40 milliseconds and release their memory, WebSockets keep thousands of stateful TCP connections open simultaneously. Every proxy timeout, container restart, and network blip becomes an edge case your architecture has to absorb gracefully.


Choosing the Right Real-Time Transport First

Before opening persistent sockets across your stack, verify that bidirectional WebSockets are actually the right tool for your product. Over-engineering transport early adds operational weight startups rarely need.

Transport Direction Proxy & Firewall Friendliness Auto-Reconnect Best Use Cases
Short Polling Client pulls Highest (plain HTTP) Built-in via timer Low-frequency status checks (every 15–30s)
Server-Sent Events (SSE) Server -> Client High (HTTP/1.1 & HTTP/2) Native browser EventSource AI streaming, live feeds, stock tickers, alerts
WebSockets Bidirectional Moderate (requires Upgrade) Manual implementation Chat, live dispatch, collaborative cursors, games
Managed Pub/Sub Bidirectional Handled by vendor SDK-handled Teams prioritizing speed over infra ownership

If your users only watch live updates—like a build log or delivery map—SSE gives you streaming over standard HTTP without custom heartbeat logic. When users actively publish rapid updates or share presence state, WebSockets earn their keep.


Authenticating the Upgrade Handshake Safely

Browsers do not let you attach arbitrary Authorization: Bearer ... headers from client JavaScript during the native new WebSocket(url) handshake. Because of that limitation, many tutorials recommend putting your JWT in the query string: wss://api.example.com/ws?token=eyJ....

Avoid that pattern in production. Nginx access logs, CDN edge logs, and error trackers routinely store full request URLs in plaintext, turning your access logs into a credential leak.

Instead, use a short-lived handshake ticket:

  1. The authenticated client calls POST /api/ws-ticket over HTTPS (using its normal HttpOnly cookie or Bearer header).
  2. The server generates a cryptographically random 32-byte ticket, stores { userId, orgId } in Redis with a 20-second TTL, and returns { ticket }.
  3. The browser opens wss://api.example.com/ws?ticket=TICKET_VALUE.
  4. On upgrade, the WebSocket server performs an atomic GETDEL in Redis. If valid, it upgrades the socket and binds userId and orgId to the connection state; if missing or expired, it aborts with 401.

Even if a proxy logs the URL, the ticket is single-use and dead within seconds.


Scaling Across Multiple Servers With Redis Pub/Sub

A single Node.js, Go, or PHP worker holds connections in local memory. The moment you run two backend instances behind a load balancer, a message posted to Instance A will not reach sockets connected to Instance B.

Introducing Redis Pub/Sub decouples where an event is created (your REST API, background queue, or webhook handler) from which socket server holds the recipient's TCP connection:

import { WebSocketServer, WebSocket } from 'ws';
import Redis from 'ioredis';

const pub = new Redis(process.env.REDIS_URL!);
const sub = new Redis(process.env.REDIS_URL!);

// Map channel name -> set of sockets on THIS instance
const localRooms = new Map<string, Set<WebSocket>>();

sub.psubscribe('org:*');
sub.on('pmessage', (_pattern, channel, payload) => {
  const clients = localRooms.get(channel);
  if (!clients) return;

  for (const socket of clients) {
    if (socket.readyState === WebSocket.OPEN && socket.bufferedAmount < 1_048_576) {
      socket.send(payload);
    }
  }
});

export function publishOrgEvent(orgId: number, event: object) {
  return pub.publish(`org:${orgId}`, JSON.stringify(event));
}

Notice the socket.bufferedAmount < 1_048_576 guard before calling socket.send(). That single line protects your server from slow-consumer memory exhaustion. If a mobile user enters an elevator and their TCP buffer stops draining, blindly pushing frames into socket.send() balloons Node heap memory until the process crashes with an OOM error. Dropping non-critical live frames (or disconnecting stale clients whose buffer exceeds 1 MB) keeps healthy users online.

Surviving Reverse Proxy Timeouts

Nginx and cloud load balancers routinely close idle HTTP connections after 60 seconds. If a dashboard tab sits quiet for two minutes, the proxy drops the socket silently while both browser and server think it is alive.

  • Configure Nginx with explicit upgrade headers and extended read timeouts (proxy_read_timeout 3600s;, proxy_http_version 1.1;, Upgrade and Connection headers).
  • Run a server-side heartbeat (ws.ping()) every 25 seconds and terminate connections that miss two consecutive pong responses.

Preventing Reconnect Storms and Missed Messages

One of the hardest incidents I ever debugged happened on a live logistics dispatch board. A routine load balancer reload severed several thousand active sockets at the exact same millisecond. Every client ran setTimeout(connect, 1000)—meaning 100% of users hammered the authentication endpoint simultaneously every second, pinning database connection pools at 100% and locking out new traffic for ten minutes.

Two rules prevent reconnect storms and lost updates:

1. Exponential Backoff With Full Jitter

Spread client reconnect attempts across an expanding time window so your API recovers smoothly:

function getReconnectDelayMs(attempt: number, baseMs = 1000, maxMs = 30000): number {
  const exponential = Math.min(maxMs, baseMs * Math.pow(2, attempt));
  // Full jitter spreads load evenly across [0, exponential]
  return Math.floor(Math.random() * exponential);
}

2. Cursor-Based Replay After Disconnects

WebSockets are a delivery optimization, not a durable database. If a laptop sleeps for 45 seconds, Redis Pub/Sub will not hold missed messages for it. Tag broadcast payloads with a monotonically increasing event_id or timestamp, and on ws.onopen (after a reconnect), have the client call GET /api/events?after_id=lastSeenId to bridge the gap deterministically.

This pattern aligns with resilient event-driven boundaries discussed across Martin Fowler's architecture guides and modern cloud edge setups covered on the Vercel engineering blog.


Deployment Checklist Before Going Live

Before shipping a real-time feature to paying customers, verify these operational fundamentals:

  • Authorization on subscribe: Never trust a client sending { subscribe: "org:99" } without checking membership server-side.
  • Connection limits: Cap concurrent sockets per user and per IP at the edge to block socket-exhaustion abuse.
  • Graceful draining: On SIGTERM during deploys, stop accepting upgrades and close existing sockets with code 1001 (Going Away) so clients trigger jittered reconnects cleanly.
  • Separate worker pool: Keep WebSocket servers isolated from heavy CPU jobs (PDF generation, AI inference, large exports) so event loops stay sub-10ms.

Build Real-Time Systems That Stay Up Under Load

If your startup needs live collaboration, dispatch dashboards, or streaming workflows—and you want to skip months of trial-and-error debugging around Redis fan-out, Nginx tuning, and reconnect storms—SmitDev can architect and ship the system end to end. You can work directly with a senior full-stack engineer through dedicated hiring at $55/day (8–9 hours) or $1,999/month, or review our broader full-stack engineering services.

Have a real-time product feature or lagging WebSocket backend that needs stabilizing? Start a conversation on the contact page and share your traffic profile and stack.

Written by Smit Desai · Principal Full-Stack & FDSE

8+ years shipping production systems · 171 case studies · 300+ WordPress servers managed for Finland partners.

Next Steps and Recommended Resources

Next Steps · Recommended Resources

Pillar 1 · Custom Web & SaaS

Custom Web Application Development

Production Laravel, Next.js, API, and multi-tenant SaaS systems engineered end to end at $55/day (8–9 hrs) or $1,999/mo.

Comparison · Buyer Guide

SmitDev vs Software Agencies

See side-by-side economics, senior code ownership, and onboarding speed vs traditional dev shops and marketplaces.

01 — Frequently asked questions

full-stack web

When should I use Server-Sent Events (SSE) instead of WebSockets?

Use SSE when data flows strictly from server to browser—such as live notifications, AI token streaming, or order status feeds. SSE runs over standard HTTP, reconnects automatically, and requires less proxy tuning. Choose WebSockets when clients also push high-frequency messages back, like collaborative editing, chat, or multiplayer state.

Why do WebSocket apps fail when scaled to two or more backend servers?

Each WebSocket connection is a stateful TCP socket pinned to one server's memory. If User A connects to Server 1 and User B connects to Server 2, a message emitted inside Server 1's memory never reaches User B unless you introduce a shared pub/sub broker like Redis or NATS.

How should I authenticate WebSocket connections without leaking tokens?

Never pass long-lived JWTs or session secrets inside the WebSocket URL query string, because reverse proxies and load balancers log full URLs in plaintext. Instead, request a single-use, 30-second opaque ticket over an authenticated HTTPS POST endpoint and pass that ticket during the upgrade handshake.

Can serverless functions host persistent WebSocket servers?

Standard stateless serverless functions terminate after each request and cannot hold thousands of idle TCP sockets. If your API runs on serverless infrastructure, offload persistent sockets to a managed service or run a dedicated lightweight Node, Go, or Laravel Reverb worker behind a load balancer.

03 — Have an engineering need?

hire the right expertise

Let's talk tech.

Deciding between an embedded forward deployed engineer or a senior full stack developer? Share your technical context and timeline.

Solitaire Corporate Park, Makarba, Ahmedabad, Gujarat 380015, India · IST (UTC+5:30) · --:-- IST · Mon–Fri 09:00–18:00 IST · US & EU overlap daily

No newsletter, no CRM. Just a reply.