Real-Time Features: WebSockets, SSE and Polling Compared

When to use polling, Server-Sent Events or WebSockets, and how to scale them with Redis pub/sub, handle presence and build reconnection logic that survives real networks.

DIDatainter TeamAUG 21, 20259 MIN READTECHNOLOGY

Users now expect live interfaces: chat messages that appear instantly, order statuses that update without a refresh, collaborative cursors, price tickers, delivery maps. Delivering these features is not hard in a demo. It becomes hard when you have 50,000 concurrent connections, a rolling deployment, a flaky mobile network and a load balancer that closes idle connections after 60 seconds.

This article walks through the three main transport options, the scaling architecture that works for most products, and the unglamorous details of presence and reconnection that decide whether a real-time feature feels solid or haunted.

Start by asking whether you need real time

The first design question is how fresh the data really needs to be. Real time is a spectrum:

  • Hours: a daily report. Use a normal request.
  • Minutes: a dashboard. Polling every 30 to 60 seconds is fine.
  • Seconds: an order tracker, a notification badge. Polling or SSE.
  • Sub-second, bidirectional: chat, multiplayer, collaborative editing. WebSockets.

Many teams build WebSocket infrastructure for features that would have been perfectly served by polling every 10 seconds. Persistent connections carry operational cost: they complicate deployments, load balancing, observability and capacity planning. Pay that cost only when the product requires it.

The three transports

Short and long polling

Short polling means the client asks “anything new?” on a timer. It is stateless, works through every proxy, is trivial to cache and debug, and scales horizontally with no special infrastructure. Its costs are wasted requests when nothing changes and latency bounded by the interval.

Long polling holds each request open until the server has data or a timeout (often 25 to 30 seconds) is reached, then the client immediately re-requests. It reduces latency to near real time while still using plain HTTP. It was the basis of early chat systems and remains a reasonable fallback, although each waiting client holds a connection.

A cheap optimization for short polling is conditional requests: send an ETag or If-Modified-Since and return 304 Not Modified with an empty body. Combined with exponential backoff when the tab is hidden, polling is often good enough.

Server-Sent Events

SSE is a one-way stream from server to browser over a single long-lived HTTP response with the text/event-stream content type. The browser’s EventSource API handles parsing, automatic reconnection and resuming from the last event ID through the Last-Event-ID header.

Advantages are significant:

  • It uses standard HTTP, so it works with existing authentication, cookies, compression and most proxies.
  • Reconnection and event IDs are built into the protocol.
  • With HTTP/2 or HTTP/3, many streams multiplex over one connection, which removes the old six-connections-per-origin limit that hurt HTTP/1.1.
  • The server implementation is simple; any framework that can flush a response can do it.

Limitations: it is server-to-client only (client messages go through ordinary POST requests), text only, and EventSource cannot set custom headers, which complicates bearer-token authentication. Workarounds include cookie-based sessions, short-lived signed tokens in the query string, or using fetch with a streaming reader to build your own client.

SSE is an excellent default for notifications, activity feeds, progress bars, live dashboards and streaming responses from language models.

WebSockets

WebSockets upgrade an HTTP connection into a full-duplex, message-oriented channel. Both sides can send at any time with very low overhead per message, and binary payloads are supported.

Use them when you need:

  • Frequent bidirectional messages (chat, games, collaborative editing).
  • Very low latency from client to server, where a new HTTP request per action is too heavy.
  • Binary protocols.

The price is that you now own more of the stack. There is no automatic reconnection, no built-in message acknowledgment and no resume. You must implement heartbeats, authentication on connect, backpressure handling and message framing. Libraries such as Socket.IO, or lighter ones like ws plus your own protocol, supply parts of this. See the MDN documentation on the WebSocket API for protocol details.

Technology · Real-Time Features: WebSockets, SSE and Polling Compared

Comparison

Aspect Polling SSE WebSockets
Direction Client pulls Server pushes Both ways
Latency Interval-bound Near instant Near instant
Auto-reconnect Not needed Built in You build it
Proxy/firewall friendliness Excellent Very good Good, occasionally blocked
Server cost per client Low, bursty One open connection One open connection
Binary data Yes No Yes
Complexity Lowest Low Highest

A practical rule: start with SSE for server-to-client updates and plain POST for actions. Move to WebSockets only when you measure that client-to-server traffic is frequent enough to justify it.

Scaling beyond one server

A single Node.js or Go process can hold tens of thousands of idle connections, so a lone server takes you surprisingly far. The problem starts when you run two or more instances behind a load balancer. User A is connected to instance 1, user B to instance 2, and a message from A to B has nowhere to go.

The standard solution is a publish/subscribe backplane. Redis is the common choice:

  1. Each application instance subscribes to Redis channels relevant to its connected clients, such as room:42 or user:1001.
  2. When any instance receives an event, it publishes it to the channel.
  3. Every instance subscribed to that channel receives the message and forwards it to its local connections.

A minimal publisher and subscriber in Node looks like this:

import { createClient } from "redis";

const pub = createClient({ url: process.env.REDIS_URL });
const sub = pub.duplicate();
await Promise.all([pub.connect(), sub.connect()]);

// Each instance forwards channel messages to its own sockets
await sub.subscribe("room:42", (raw) => {
  for (const socket of localRoomMembers("room:42")) {
    socket.send(raw);
  }
});

// Any instance can publish
await pub.publish("room:42", JSON.stringify({ type: "msg", body: "hello" }));

Important caveats about Redis pub/sub: it is fire-and-forget. If a subscriber is disconnected for a second, it misses messages. If you need delivery guarantees or replay, use Redis Streams, which store messages with IDs so a consumer can resume from the last one it processed, or a broker such as Kafka or NATS JetStream. A hybrid approach is common: persist events to your database or a stream for history, and use pub/sub only as a low-latency wake-up signal.

Load balancing details

  • Sticky sessions are not required if you use a backplane, but they help with Socket.IO’s HTTP long-polling fallback. Prefer disabling the fallback and forcing the WebSocket transport.
  • Idle timeouts on load balancers (AWS ALB defaults to 60 seconds, for example) will silently kill quiet connections. Send application-level pings every 20 to 30 seconds, or configure higher timeouts.
  • Connection draining matters during deployments. When an instance shuts down, send a close frame with a “going away” code, and let clients reconnect with jitter so you do not trigger a thundering herd against the remaining instances.
  • File descriptors and memory: raise OS limits, and budget memory per connection. Each socket plus buffers might use 10 to 50 KB depending on your stack, so 100,000 connections can cost several gigabytes.

Presence: who is online

Presence seems simple until you think about failure. A user closes a laptop lid; no close frame is sent; the server keeps believing they are online. The reliable pattern is time-to-live heartbeats:

  • When a client connects, the server writes a key like presence:user:1001 in Redis with a TTL of 45 seconds.
  • Every 15 to 20 seconds the client heartbeat refreshes the TTL.
  • If heartbeats stop, the key expires and the user becomes offline without anyone explicitly deleting it.
  • Maintain a counter or a set per user because the same user may have several tabs or devices; mark them offline only when the last connection disappears.

For room-level presence, a sorted set with the last-seen timestamp as score lets you list active members and trim stale ones with ZREMRANGEBYSCORE. Publish presence changes over pub/sub, but debounce them: a flaky connection that flaps five times in a minute should not generate five “joined” notifications for everyone in the room. A grace period of 5 to 10 seconds before announcing “left” smooths this out.

Reconnection that survives real networks

Mobile networks drop. Wi-Fi hands off to cellular. Servers restart. A robust client assumes the connection is temporary and rebuilds state on every reconnect.

Core practices:

  • Exponential backoff with jitter. Start at 500 ms, double each attempt up to 30 seconds, and add random jitter so thousands of clients do not reconnect simultaneously.
  • Reset the backoff only after a connection has been stable for a while, not merely opened.
  • Resume from the last event ID. Every server event carries a monotonically increasing ID per stream. On reconnect, the client sends the last one it saw and the server replays what was missed, from a short buffer or a stream. If the gap is too large, the server instructs the client to refetch full state through a normal API call.
  • Make messages idempotent. Replays and retries mean a client may see an event twice. Deduplicate by ID.
  • Detect half-open connections. If no message or pong arrives within two heartbeat intervals, close and reconnect rather than waiting for the operating system’s TCP timeout, which can take minutes.
  • React to visibility and network events. Pause or lower activity when the tab is hidden, and reconnect immediately on the browser’s online event or when a mobile app returns to the foreground.
  • Show state honestly. A small “reconnecting” indicator is better than a UI that silently shows stale data.

A real-time feature is judged by how it behaves in the worst thirty seconds of the user’s network, not the best.

Authentication and authorization

Authenticate at connection time, but do not stop there. Tokens expire during long-lived connections, so either re-authenticate periodically with a message over the socket or close and reconnect when the token rotates. Authorize every subscription: a client asking to join room:42 must be checked against membership on the server, because channel names are guessable. Validate and size-limit every incoming message, and rate limit per connection; a single misbehaving client can otherwise flood a room. Also validate the Origin header on WebSocket upgrades to prevent cross-site WebSocket hijacking.

Observability

Track these metrics from the start: current connections per instance, connection and disconnection rates, reconnect rates, message throughput in and out, message fan-out latency from publish to client receipt, outbound buffer sizes and Redis pub/sub lag. A sudden spike in reconnects is usually the first symptom of a deployment problem, a load balancer timeout or a network event. Log a connection ID and user ID on every line so you can trace one user’s session.

Key takeaways

  • Choose the least powerful transport that meets the freshness requirement; polling and SSE cover more cases than most teams assume.
  • Use SSE for server-to-client updates with standard HTTP actions for the reverse path, and WebSockets only for genuinely bidirectional, high-frequency traffic.
  • Scale horizontally with a pub/sub backplane such as Redis, and add Streams or a broker when you need replay or delivery guarantees.
  • Implement presence with TTL heartbeats and a grace period, and count multiple connections per user.
  • Build reconnection with backoff plus jitter, event IDs for resume, idempotent handlers and honest connection-state UI.
  • Authorize every subscription, validate every message, and monitor reconnect rates as an early warning signal.
#websockets#server-sent events#redis#scalability
DI
Datainter TeamEngineers, designers and operators building software and fintech products from Medellín, Tigard and Luxembourg.

Building something in this space?

Talk to the team that ships and operates it. We reply within one business day.

Start a project
Chat with us on WhatsAppUSUALLY REPLIES WITHIN MINUTES