Skip to content
Velloreth
Programming 5 min read

WebSockets vs Polling: Real-Time Communication Options

Polling, long polling, SSE and WebSockets each fit a different real-time need. Learn how each works and which to choose.

By

Short polling

The client asks on an interval.

setInterval(async () => {
  const res = await fetch('/api/messages');
  render(await res.json());
}, 5000);

The advantages: trivial to implement, works everywhere, and needs no special server support.

The disadvantages: most requests return nothing new, which wastes bandwidth and server capacity. The latency is up to the interval.

Use it when the update frequency is low and a delay of a few seconds is acceptable. A dashboard that refreshes every 30 seconds is a good fit.

Long polling

The client sends a request, and the server holds it open until there is data or a timeout.

async function poll() {
  const res = await fetch('/api/messages?wait=30');
  render(await res.json());
  poll();  // immediately send another
}
poll();

The advantages: near-real-time latency, and it works over plain HTTP, so no proxy configuration is needed.

The disadvantages: the server holds a connection per client, which consumes a worker or a file descriptor. A timeout is needed, or a dead connection is held forever.

Use it when you need low latency but cannot use WebSockets, such as behind a restrictive proxy.

Server-Sent Events

SSE is a one-way stream from server to client, over plain HTTP.

const source = new EventSource('/api/events');
source.onmessage = (event) => render(JSON.parse(event.data));

The server sends a stream of text events.

event: message
data: {"id":1,"text":"hello"}

event: message
data: {"id":2,"text":"world"}

The advantages: it is plain HTTP, so it works through a proxy and a CDN. The browser reconnects automatically, with a Last-Event-ID header so the server can resume. The implementation is simple.

The disadvantages: it is one-way. The client sends data with a normal request, not over the stream. There is a limit on the number of connections per domain in HTTP/1.1, though HTTP/2 removes it.

Use it when the server pushes and the client rarely sends: a notification feed, a live log, a progress bar, a stock ticker.

WebSockets

A WebSocket is a full-duplex connection, upgraded from an HTTP request.

const ws = new WebSocket('wss://example.com/ws');

ws.onopen = () => ws.send(JSON.stringify({ type: 'subscribe', channel: 'news' }));
ws.onmessage = (event) => render(JSON.parse(event.data));
ws.onclose = () => reconnect();

The advantages: two-way, low latency, and low overhead per message after the handshake.

The disadvantages: it needs its own protocol for messages, a heartbeat to detect a dead connection, and a reconnect strategy. A proxy may buffer or close it, and some CDNs do not support it. Scaling across servers needs a shared pub/sub layer.

Use it when the client also sends frequently: a chat, a collaborative editor, a multiplayer game, a trading interface.

Comparing

LatencyDirectionComplexityProxy-friendly
Short pollingIntervalClient → serverLowYes
Long pollingLowClient → serverMediumYes
SSELowServer → clientLowYes
WebSocketsLowBothHighSometimes

Reconnection

Every real-time transport needs a reconnect strategy, because connections drop.

Use exponential backoff with jitter.

let delay = 1000;

function reconnect() {
  const jitter = Math.random() * 1000;
  setTimeout(() => {
    connect();
    delay = Math.min(delay * 2, 30000);
  }, delay + jitter);
}

The jitter matters. Without it, every client reconnects at the same moment after an outage, which is a thundering herd that can take the server down again.

Reset the delay on a successful connection, or a client that reconnects after a long session waits 30 seconds for the next attempt.

For SSE, the browser reconnects automatically, and the retry field sets the interval.

retry: 5000

Heartbeats

A connection can be dead without the client knowing: a proxy closed it, or the network changed.

Send a heartbeat and expect a response.

setInterval(() => {
  if (ws.readyState === WebSocket.OPEN) {
    ws.send(JSON.stringify({ type: 'ping' }));
  }
}, 30000);

The server should also ping, and close a connection that does not respond. This is how a dead connection is detected rather than held open.

For SSE, a comment line keeps the connection alive.

: keep-alive

Scaling

A single server can hold the connections in memory.

Several servers need a shared pub/sub layer, so a message published on one server reaches the clients connected to another.

Publisher → Redis pub/sub → every server → its connected clients

Sticky sessions alone are not enough. They keep a client on one server, but a message that originates on another server still needs to reach it.

The connection count is the limit. A server holds a file descriptor per connection, so the practical limit is in the tens of thousands per node, depending on the configuration.

Choosing

Short polling for a low-frequency update where a delay is fine.

Long polling for low latency without WebSocket support.

SSE for a server-to-client push, which is the most common real-time need.

WebSockets for a genuinely two-way, high-frequency interaction.

The honest default: if the server pushes and the client rarely sends, SSE is simpler than WebSockets and does the job. Reach for WebSockets when the client also sends frequently.

Practical guidance

  • Start with polling if the frequency is low.
  • Use SSE for a server-to-client push.
  • Use WebSockets for two-way, high-frequency.
  • Always implement a reconnect with backoff and jitter.
  • Send a heartbeat to detect a dead connection.
  • Use a shared pub/sub layer to scale.
  • Check the proxy and CDN support.
  • Set an idle timeout on the server.

For the related guides, see rest-api-design-principles and http-status-codes-explained. For the broader context, nginx-basics-guide and how-cdns-actually-work.

Quotable summary

Short polling is the simplest and the most wasteful, because most requests return nothing new, while long polling holds a request open until there is data, which reduces the wasted requests. Server-Sent Events is a one-way stream from server to client over plain HTTP, and it reconnects automatically with a Last-Event-ID header so the server can resume. WebSockets is a full-duplex connection, which is the right choice when the client also sends frequently, but it needs its own heartbeat and reconnect handling. Every real-time transport needs a reconnect strategy with exponential backoff and jitter, because without the jitter every client reconnects at the same moment after an outage, which is a thundering herd.

Frequently asked questions

What is the difference between SSE and WebSockets?
SSE is one-way, from server to client, over plain HTTP, and it reconnects automatically. WebSockets is two-way and needs its own protocol handling, including a heartbeat and a reconnect.
When is polling good enough?
When the update frequency is low and a small delay is acceptable, such as a dashboard that refreshes every 30 seconds. It is the simplest option and it works everywhere.
Why does my WebSocket connection drop?
A proxy or load balancer closes an idle connection, a network change occurs, or the server restarts. Send a heartbeat and implement a reconnect with backoff.
Can I use WebSockets through a CDN?
Some CDNs support it, but many do not, and a proxy may buffer or close the connection. Check the support, and configure the idle timeout.
What is long polling?
The client sends a request and the server holds it open until there is data or a timeout, then responds. The client immediately sends another. It reduces the wasted requests of short polling.
How do I scale WebSockets across servers?
Use a shared pub/sub layer such as Redis, so a message published on one server reaches the clients connected to another. Sticky sessions alone are not enough.