WebSockets vs Server-Sent Events vs Long Polling vs WebTransport: Real-Time Protocols Compared for Apps and IoT Dashboards (2026)
Most real-time dashboards push 95 percent or more of their bytes in one direction, from server to browser, yet teams still reach for a full-duplex socket by reflex. The websockets vs server-sent events decision is rarely decided by the browser API. It is decided by everything between the browser and your process: HTTP versions, load balancer idle timers, buffering proxies, mobile radios and the fan-out bus behind your gateways. In 2026 the field also changed shape. WebTransport became Baseline in March, when Safari 26.4 shipped it, and the W3C published it as a Candidate Recommendation in July. So the choice now has four serious options, not two. This guide compares all four at the mechanism level, with working server code, worked capacity numbers and the failure modes that actually page people.
What this covers: how long polling, SSE, WebSockets and WebTransport work on the wire; RFC 6455, RFC 8441 and RFC 9220; the HTTP/1.1 six-connection trap; proxy and load balancer timeouts; Node and Python servers; fan-out with Redis and NATS; reconnect storms; MQTT over WebSockets; and a decision matrix for apps and IoT dashboards.
Context and Background
The web was built on request and response, so every real-time technique is a workaround for that shape. Plain polling came first: the client asks every few seconds whether anything changed. Long polling improved it by having the server hold the request open until an event arrives or a timeout fires. The Bayeux protocol, Comet libraries and early chat systems ran on this pattern for years, and it is still the fallback inside Socket.IO and several commercial push services.
Server-Sent Events (SSE) standardised the “hold one response open and keep writing” idea. The format and the EventSource interface live in the WHATWG HTML Living Standard. It defines a text/event-stream media type, automatic reconnection, a retry field and a Last-Event-ID request header for resuming. SSE is one-way: server to client only.
WebSockets arrived as RFC 6455 in December 2011. A WebSocket starts as an HTTP/1.1 request with an Upgrade: websocket header, receives 101 Switching Protocols, and then stops being HTTP. From that point both sides exchange framed messages over the raw TCP connection. RFC 8441 (September 2018) defined how to bootstrap a WebSocket over a single HTTP/2 stream using extended CONNECT. RFC 9220 (June 2022) did the same for HTTP/3.
WebTransport is the newest member. It is a browser API, specified by the W3C WebTransport Working Group, plus an IETF protocol, draft-ietf-webtrans-http3, that runs sessions over HTTP/3 and QUIC. Unlike WebSockets, it offers many independent streams and unreliable datagrams inside one session. If you have read our QUIC and HTTP/3 protocol deep dive, WebTransport is essentially QUIC’s stream and datagram model exposed to JavaScript.
For IoT teams the field has one more wrinkle. Many dashboards do not speak a custom protocol at all. They connect straight to an MQTT broker using MQTT over WebSockets, which the OASIS MQTT 5.0 specification defines in its Section 6. That makes the WebSocket choice partly a broker choice, which we return to below. It also means the websockets vs server-sent events question has a third answer for IoT: let the broker protocol decide.
WebSockets vs Server-Sent Events, Long Polling and WebTransport: How Each Protocol Works
WebSockets give a full-duplex, message-framed channel over one TCP connection. Server-Sent Events stream text events one way over a normal HTTP response, with built-in reconnect and resume. Long polling repeats ordinary HTTP requests that the server holds open. WebTransport runs multiplexed reliable streams and unreliable datagrams over HTTP/3 and QUIC.

Figure 1: The four real-time web protocols, from browser API down to the transport each one actually rides on.
Figure 1 traces each option from the JavaScript API to the wire. Three of the four share TCP and TLS, which means they share TCP’s head-of-line blocking: one lost packet stalls every byte behind it on that connection. Only WebTransport sits on QUIC over UDP. The middle layer matters as much. Long polling and SSE stay ordinary HTTP the whole time, so every proxy, CDN and observability tool understands them. A classic WebSocket leaves HTTP after the handshake, and intermediaries must treat it as an opaque tunnel. That single difference explains most of the operational gap in websockets vs server-sent events comparisons.
Long polling: HTTP requests that wait
In long polling the client sends a request, and the server does not answer until it has data or a timeout, often 20 to 30 seconds, expires. The client processes the response and immediately sends the next request. Delivery latency is low when an event arrives during a held request. However, every message still costs a full HTTP request and response, including headers and, on HTTP/1.1, possibly a new connection.
The subtle cost is the gap between responses. After the server answers, there is a window of roughly one round trip before the next request arrives. Events produced in that window must be queued server-side and keyed to the client, usually with a cursor such as “give me everything after sequence 1041”. Without that cursor, long polling silently drops events. Long polling is therefore never stateless in practice: correctness depends on a per-client or per-topic event log with replay.
Its strength is reach. Long polling works through nearly any proxy, needs no special headers and degrades gracefully. That is why it remains the bottom rung of most fallback ladders.
Server-Sent Events: one response that never ends
SSE is a single GET whose response has Content-Type: text/event-stream and simply never finishes. The server writes UTF-8 lines such as id: 1042, event: reading and data: {...}, with a blank line terminating each event. The browser’s EventSource parses these and fires DOM events. Lines beginning with a colon are comments, which the WHATWG specification suggests sending “every 15 seconds or so” to stop legacy proxies dropping an idle connection.
The killer feature is resume. When the connection drops because of a network error, EventSource waits for the reconnection time and reconnects automatically. The default delay is implementation-defined, “probably in the region of a few seconds” per the spec, and the server can change it with a retry: field. On reconnect the browser sends the last seen id in a Last-Event-ID header, so a well-built server can replay exactly what the client missed. No other option in this comparison ships a resume contract in the browser itself, and that is the most underrated point in any websockets vs server-sent events evaluation.
SSE also has hard edges. The specification only allows text, so binary payloads need Base64 or a separate fetch. A response status other than 200, or a wrong content type, fails the connection permanently; the browser will not retry. The server can deliberately stop reconnection with 204 No Content. And EventSource cannot set custom request headers, so token auth must ride in a cookie (withCredentials: true for cross-origin) or a query parameter.
WebSockets: an upgraded, framed TCP pipe
A WebSocket handshake on HTTP/1.1 is a GET with Upgrade: websocket, Connection: Upgrade, a random Sec-WebSocket-Key and an optional Sec-WebSocket-Protocol list. The server returns 101 Switching Protocols. After that, RFC 6455 framing takes over. Each frame carries an opcode (text, binary, close, ping or pong), a payload length and, for client-to-server frames, a 32-bit masking key that XORs the payload. Masking exists to stop cache-poisoning attacks on naive intermediaries, not for confidentiality.
WebSockets are symmetric. Either side can send at any time, in text or binary, and the protocol has built-in ping and pong control frames for liveness. What it lacks is everything above framing. There is no message acknowledgement, no resume, no replay and no topic model. Libraries such as Socket.IO, or protocols layered inside the socket such as MQTT, STOMP or GraphQL subscriptions, supply those semantics. When people frame websockets vs server-sent events as “raw power vs convenience”, this missing layer is what they mean.
Two newer RFCs change the transport underneath. RFC 8441 lets a WebSocket run on one HTTP/2 stream. The server advertises SETTINGS_ENABLE_CONNECT_PROTOCOL (code 0x8) with a value of 1. The client sends an extended CONNECT with :protocol set to websocket, and the server answers 200 rather than 101. RFC 9220 defines the same mechanism for HTTP/3. RFC 8441 is implemented in several servers and browsers, though support varies by stack and we did not verify a full matrix, so test your exact path. More importantly, we could not find a shipping browser implementation of RFC 9220 as of November 2026: Chromium filed only an “Intent to Prototype” in 2022, and Firefox’s tracking bug is still open. Treat WebSockets as a TCP protocol for planning purposes.
WebTransport: QUIC streams and datagrams for the browser
A WebTransport session begins with an HTTP/3 extended CONNECT whose :protocol is webtransport-h3, according to the IETF draft (draft-ietf-webtrans-http3-17, published 2 November 2026 and still an Internet-Draft). The server must advertise SETTINGS_WT_ENABLED, extended CONNECT and HTTP datagram support. Once accepted, either side can open unidirectional or bidirectional streams, and both can send datagrams, which travel in QUIC DATAGRAM frames with no retransmission.
Independence is the point. Each stream has its own ordering, so a lost packet on stream A does not stall stream B. Datagrams are capped by maxDatagramSize, which tracks the path MTU minus overhead, so they suit small, latest-value-wins updates. The W3C API exposes all of this through WHATWG Streams, which means backpressure is native: a writer’s ready promise does not resolve until there is room to send.
The W3C draft and Apple’s release notes both describe an HTTP/2 fallback. The API’s reliability attribute reports "supports-unreliable" on HTTP/3 and "reliable-only" on HTTP/2. The HTTP/2 mapping, draft-ietf-webtrans-http2, is a separate, still-unfinished draft, and server support for it is thin. Plan for that fallback to be your own WebSocket path, not the browser’s. WebTransport therefore extends the websockets vs server-sent events choice rather than replacing it.
WebSockets vs Server-Sent Events: The Comparison Table
The table below is the snippet-friendly summary. Statements are drawn from the specifications and vendor documentation linked in this post; “typical” entries describe common deployments rather than guarantees.
| Property | Long polling | Server-Sent Events | WebSockets | WebTransport |
|---|---|---|---|---|
| Direction | Client pulls, server answers | Server to client only | Full duplex | Full duplex, many streams |
| Spec status | Pattern, plain HTTP | WHATWG HTML Living Standard | RFC 6455, RFC 8441, RFC 9220 | W3C CR July 2026; IETF draft |
| Transport | TCP, any HTTP version | TCP, HTTP/1.1 or HTTP/2 | TCP; HTTP/3 mapping not shipped in browsers | QUIC over UDP |
| Payload | Any | UTF-8 text only | Text or binary messages | Binary streams and datagrams |
| Auto reconnect | You build it | Built in, retry field |
You build it | You build it |
| Resume after drop | Cursor you build | Last-Event-ID header |
You build it | You build it |
| Backpressure in browser API | Implicit, one request at a time | None, browser buffers | None in WebSocket; Chromium-only WebSocketStream |
Native via Streams |
| Proxy friendliness | Excellent | Good if buffering is off | Needs Upgrade support | Needs UDP 443 open |
| HTTP/1.1 tab limit | Shares six per origin | Shares six per origin | Not counted in that pool | Not applicable |
| Browser support | Universal | Universal | Universal | Baseline since March 2026 |
| Best fit | Fallback, rare events | Dashboards, feeds, AI token streams | Chat, collaboration, MQTT in browser | Games, media, mixed-priority telemetry |
The table hides one important nuance. In the SSE vs WebSocket comparison, SSE “losing” on bidirectionality matters less than it looks. A dashboard’s client-to-server traffic is usually rare commands, such as acknowledging an alarm or changing a filter. Those fit perfectly in ordinary POST requests on the same HTTP/2 connection the SSE stream already uses.
Walk-through: Servers, Capacity Math and Fan-Out Architecture
The fastest way to see the differences is to build the same feature four ways: a stream of sensor readings to a browser. Seeing websockets vs server-sent events side by side in code also shows where each one pushes complexity. The code below is deliberately minimal but runnable. Each example includes the production detail that most tutorials skip, such as heartbeats, buffering headers or backpressure.
Long polling in Node.js
This server keeps a small in-memory log and answers each poll with everything after the client’s cursor. If nothing is newer, it parks the response until an event arrives or 25 seconds pass.
// longpoll.js - node longpoll.js
const http = require('node:http');
const log = []; // [{seq, data}] - use Redis Streams or similar in production
let seq = 0;
const waiters = new Set(); // parked responses
function publish(data) {
log.push({ seq: ++seq, data });
if (log.length > 10000) log.shift();
for (const w of waiters) flush(w);
}
function flush(w) {
const events = log.filter(e => e.seq > w.after);
if (events.length === 0) return false;
clearTimeout(w.timer);
waiters.delete(w);
w.res.writeHead(200, { 'content-type': 'application/json', 'cache-control': 'no-store' });
w.res.end(JSON.stringify(events));
return true;
}
http.createServer((req, res) => {
const url = new URL(req.url, 'http://x');
if (url.pathname !== '/poll') { res.writeHead(404).end(); return; }
const w = { res, after: Number(url.searchParams.get('after') || 0) };
if (flush(w)) return;
w.timer = setTimeout(() => { // empty answer before proxies give up
waiters.delete(w);
res.writeHead(204).end();
}, 25000);
waiters.add(w);
req.on('close', () => { clearTimeout(w.timer); waiters.delete(w); });
}).listen(8080);
setInterval(() => publish({ t: Date.now(), temp: 20 + Math.random() }), 1000);
Note the 25-second hold. It is chosen to stay below the 60-second default idle timeout on AWS Application Load Balancers and nginx, discussed below. The after cursor is not optional; without it, events published between polls vanish.
Server-Sent Events in Node.js and Python
The SSE server is shorter because the browser does the reconnection work. The server’s jobs are to set the right headers, honour Last-Event-ID, and send comment heartbeats.
// sse.js - node sse.js ; browser: new EventSource('/stream')
const http = require('node:http');
const log = []; let seq = 0; const clients = new Set();
function publish(data) {
const ev = { id: ++seq, data };
log.push(ev); if (log.length > 10000) log.shift();
for (const res of clients) write(res, ev);
}
function write(res, ev) {
// returns false when the socket buffer is full: a slow client
return res.write(`id: ${ev.id}\nevent: reading\ndata: ${JSON.stringify(ev.data)}\n\n`);
}
http.createServer((req, res) => {
if (req.url !== '/stream') { res.writeHead(404).end(); return; }
res.writeHead(200, {
'content-type': 'text/event-stream',
'cache-control': 'no-cache',
'x-accel-buffering': 'no', // tells nginx not to buffer this response
});
res.write('retry: 5000\n\n'); // client reconnect delay in ms
const last = Number(req.headers['last-event-id'] || 0);
for (const ev of log) if (ev.id > last) write(res, ev); // replay the gap
clients.add(res);
const hb = setInterval(() => res.write(': hb\n\n'), 15000);
req.on('close', () => { clearInterval(hb); clients.delete(res); });
}).listen(8081);
setInterval(() => publish({ t: Date.now(), temp: 20 + Math.random() }), 1000);
The Python version uses Starlette, which FastAPI builds on. It streams from an async generator and checks for client disconnects so that dead generators do not leak.
# sse_app.py - uvicorn sse_app:app --port 8082
import asyncio, json, time, random
from starlette.applications import Starlette
from starlette.responses import StreamingResponse
from starlette.routing import Route
LOG: list[tuple[int, dict]] = []
SEQ = 0
NEW = asyncio.Condition()
async def producer():
global SEQ
while True:
await asyncio.sleep(1)
async with NEW:
SEQ += 1
LOG.append((SEQ, {"t": time.time(), "temp": 20 + random.random()}))
del LOG[:-10000]
NEW.notify_all()
async def stream(request):
last = int(request.headers.get("last-event-id", 0) or 0)
async def gen():
nonlocal last
yield "retry: 5000\n\n"
while not await request.is_disconnected():
for seq, data in [e for e in LOG if e[0] > last]:
yield f"id: {seq}\nevent: reading\ndata: {json.dumps(data)}\n\n"
last = seq
try:
async with NEW:
await asyncio.wait_for(NEW.wait(), timeout=15)
except asyncio.TimeoutError:
yield ": hb\n\n" # heartbeat comment
return StreamingResponse(gen(), media_type="text/event-stream",
headers={"Cache-Control": "no-cache",
"X-Accel-Buffering": "no"})
app = Starlette(routes=[Route("/stream", stream)],
on_startup=[lambda: asyncio.create_task(producer())])

Figure 2: How an SSE client resumes after a proxy or deploy drops the stream, using Last-Event-ID and a server-side event log.
Figure 2 is the resume loop that makes SSE attractive for dashboards. The proxy kills the connection, the browser waits its retry interval, and then reconnects with Last-Event-ID: 1041. The server reads events 1042 onward from a durable log and replays them before switching to live mode. Note that the guarantee is only as good as that log. If you hold ten seconds of history and the client was offline for a minute, the server must detect the gap and send a full snapshot instead.
WebSockets in Node.js and Python
The Node example uses the widely used ws package. It adds two things most samples omit: a ping-based liveness check and a backpressure guard using bufferedAmount.
// ws-server.js - npm i ws ; node ws-server.js
const { WebSocketServer } = require('ws');
const wss = new WebSocketServer({ port: 8083, perMessageDeflate: false });
const MAX_BUFFER = 1 << 20; // 1 MiB of unsent data per client
wss.on('connection', (ws) => {
ws.isAlive = true;
ws.on('pong', () => { ws.isAlive = true; });
ws.on('message', (msg) => {
// client-to-server commands, e.g. {"op":"subscribe","tags":["line3/*"]}
try { ws.filter = JSON.parse(msg).tags; } catch { ws.close(1003, 'bad json'); }
});
});
// liveness: terminate sockets that missed a pong, every 30 s
setInterval(() => {
for (const ws of wss.clients) {
if (!ws.isAlive) { ws.terminate(); continue; }
ws.isAlive = false; ws.ping();
}
}, 30000);
setInterval(() => {
const msg = JSON.stringify({ t: Date.now(), temp: 20 + Math.random() });
for (const ws of wss.clients) {
if (ws.readyState !== ws.OPEN) continue;
if (ws.bufferedAmount > MAX_BUFFER) continue; // slow client: drop or conflate
ws.send(msg);
}
}, 1000);
The Python equivalent uses the websockets library’s asyncio server. Its ping_interval and ping_timeout parameters implement the same liveness check for you.
# ws_server.py - pip install websockets ; python ws_server.py
import asyncio, json, random, time
from websockets.asyncio.server import serve
CLIENTS = set()
async def handler(ws):
CLIENTS.add(ws)
try:
async for message in ws: # client commands
ws.filter = json.loads(message).get("tags")
finally:
CLIENTS.discard(ws)
async def broadcaster():
while True:
await asyncio.sleep(1)
msg = json.dumps({"t": time.time(), "temp": 20 + random.random()})
for ws in list(CLIENTS):
try:
await asyncio.wait_for(ws.send(msg), timeout=0.5) # don't let one slow client stall all
except Exception:
pass
async def main():
async with serve(handler, "0.0.0.0", 8084, ping_interval=20, ping_timeout=20) as server:
asyncio.create_task(broadcaster())
await server.serve_forever()
asyncio.run(main())
Neither WebSocket server gives the client a way to resume. If you need that, include a sequence number in every message, have the client send {"op":"resume","after":1041} after reconnecting, and back it with the same log the SSE server used. You end up rebuilding SSE’s contract by hand, which is the hidden line item in many websockets vs server-sent events cost estimates.
WebTransport client and server options
On the browser side, WebTransport is pleasantly small. This client reads latest-value updates as datagrams and receives command acknowledgements on a reliable bidirectional stream.
// browser, HTTPS page
const wt = new WebTransport('https://telemetry.example.com:4433/live');
await wt.ready;
console.log(wt.reliability); // "supports-unreliable" on HTTP/3
// unreliable, latest-value-wins telemetry
(async () => {
const reader = wt.datagrams.readable.getReader();
for (;;) {
const { value, done } = await reader.read();
if (done) break;
render(new DataView(value.buffer)); // e.g. 16-byte binary sample
}
})();
// reliable command channel
const cmd = await wt.createBidirectionalStream();
const w = cmd.writable.getWriter();
await w.ready; // native backpressure
await w.write(new TextEncoder().encode('{"op":"ack","alarm":77}'));
wt.closed.catch(err => scheduleReconnectWithJitter(err));
Server support is the constraint in 2026. Go has quic-go/webtransport-go, and Python’s aioquic exposes the HTTP/3 primitives WebTransport needs. Node.js core does not, as far as we could verify, offer a stable WebTransport server API, so Node teams typically rely on community packages or put a Go or Rust service at the edge. Because the IETF protocol is still an Internet-Draft at version 17, check that your server library tracks the same draft revision your target browsers implement before you depend on it.
Worked numbers: connection memory and fan-out
The following numbers are illustrative, built from stated assumptions so you can substitute your own. They are not benchmarks.
Assume an IoT operations dashboard with 50,000 concurrent viewers. Each holds one persistent connection, whether SSE or WebSocket. Assume about 40 KB of memory per idle connection, covering kernel socket buffers, TLS session state and application objects. That gives 50,000 × 40 KB ≈ 2 GB across the gateway fleet. The figure is small enough that connection count is rarely the first bottleneck on modern hardware. Kernel tuning, such as file-descriptor limits and ephemeral port ranges on any proxy tier, usually bites before RAM does.
Fan-out is where the arithmetic gets serious. Suppose the plant has 4,000 sensors publishing at 1 Hz, and each dashboard subscribes to 60 tags. Naively forwarding every reading means 50,000 × 60 = 3 million messages per second leaving the gateways. At 150 bytes per JSON message, that is 450 MB/s, or about 3.6 Gbit/s, before TLS and framing overhead.
Now apply conflation: the gateway keeps only the latest value per tag per client and flushes one batched frame every 250 ms. Each client then receives four frames per second, carrying at most 60 values. Message count falls to 200,000 per second. Bytes fall less, because values still flow, but per-message framing, syscalls and TLS record overhead fall by more than an order of magnitude. That design choice dominates every protocol choice in this post, including websockets vs server-sent events. A slow client simply gets fresher frames less often, rather than an ever-growing queue.
Long polling changes the picture again. With a 25-second hold and quiet periods, 50,000 clients generate at least 2,000 requests per second just to stay connected. Each request carries cookies and headers, which commonly add several hundred bytes to a couple of kilobytes. When events are frequent, long polling degenerates into one full HTTP exchange per batch per client. That is why long polling vs websockets is not close for high-rate streams, even though it is perfectly fine for rare notifications.
Fan-out architecture behind the gateways

Figure 3: A protocol-agnostic fan-out tier. Devices publish to MQTT; a conflation service feeds a pub/sub bus and a replay log; stateless gateways terminate whichever browser protocol each client uses.
Figure 3 shows the architecture that makes the protocol choice reversible. Devices publish to an MQTT broker cluster. An ingest service normalises and conflates readings, then publishes them to a fan-out bus and appends them to a replay log. Gateway nodes subscribe to the bus for the topics their connected clients need. On reconnect, a gateway reads the replay log to fill gaps before attaching the client to live traffic.
The bus and the log are deliberately separate, because their delivery semantics differ. Redis Pub/Sub has, in Redis’s own words, “at-most-once message delivery semantics”: a subscriber that is disconnected or too slow loses the message forever. Redis 7.0 added sharded Pub/Sub (SPUBLISH, SSUBSCRIBE) so channels can scale across cluster shards. Core NATS is likewise “at-most-once”, and JetStream is its persistence layer for replay. Redis Streams can serve the same replay role. Using an at-most-once bus for live traffic and a durable log for gaps gives you low latency without pretending the bus is reliable. This split is the same whichever side of websockets vs server-sent events your gateways land on.
Gateways should be stateless apart from their connection table. That lets you drain one node by closing its connections, relying on clients to reconnect elsewhere and resume from the log. If you already run MQTT at scale, the broker’s own clustering features matter here; our guide to MQTT 5 shared subscriptions, broker clustering and backpressure covers how to spread the ingest side across consumers.
MQTT over WebSockets: when the browser is just another client
Some dashboards skip the gateway tier and connect straight to the broker. MQTT 5.0 Section 6 requires MQTT control packets to travel in WebSocket binary frames, requires the client to offer the mqtt subprotocol, and warns that packets need not align with frame boundaries. Brokers such as EMQX, HiveMQ, Mosquitto and VerneMQ all expose WebSocket listeners for this.
The advantage is semantic richness for free: topics, wildcards, QoS 1 acknowledgements, retained messages for last-known values, and persistent sessions for resume. The drawbacks are security and fan-out. Every browser becomes a first-class broker client, so you need fine-grained topic ACLs per user, and you multiply broker connections by your viewer count. For internal engineering consoles this is often the right trade. For thousands of customer-facing viewers, a gateway tier that speaks SSE and translates from MQTT usually costs less to secure and scale. See our complete MQTT protocol technical guide for the QoS and retained-message mechanics referenced here.
Infrastructure: Proxies, Load Balancers and the Six-Connection Trap
In the websockets vs server-sent events debate, infrastructure decides more outcomes than code does. Each hop between browser and server has its own idle timer and buffering policy, and the shortest timer wins.
Idle timeouts you must outlive
AWS Application Load Balancers close a connection after it has been idle for the configured connection idle timeout. The ALB attribute documentation gives a default of 60 seconds and a range of 1 to 4,000 seconds. It also notes that ALBs do not support HTTP/2 PING frames and that PING frames do not reset the idle timer. Only real data does. So an SSE comment line or a WebSocket ping frame, which travels as data from the ALB’s viewpoint, is what keeps the connection alive.
nginx documents the same 60-second behaviour for WebSocket proxying: by default the connection closes if the upstream sends nothing for 60 seconds, unless you raise proxy_read_timeout or send pings. nginx also requires explicit Upgrade and Connection header forwarding for WebSockets, because they are hop-by-hop headers.
Cloudflare’s connection limits reference lists a Proxy Read Timeout of 125 seconds toward the origin, which returns a 524 error and is configurable only for Enterprise zones. Its WebSockets documentation says connections are closed after a period with no data in either direction, that only Enterprise customers can request a custom idle timeout, and that network-wide code releases “may restart servers, which terminates WebSockets connections.” Cloudflare’s page does not state the default WebSocket idle value; third-party guides commonly cite about 100 seconds, which we could not confirm from official documentation.
The practical rule follows directly. Send a heartbeat every 15 to 30 seconds. That comfortably beats a 60-second ALB or nginx default, matches the WHATWG SSE guidance, and costs almost nothing. More importantly, design for disconnects anyway, because restarts at the CDN or load balancer will cut long-lived connections regardless of heartbeats.
Buffering proxies break SSE silently
SSE relies on each event flushing to the client immediately. Any intermediary that buffers response bodies will hold events until a buffer fills, producing bursts several seconds late or nothing at all. nginx buffers proxied responses by default; you can disable it with proxy_buffering off or by sending X-Accel-Buffering: no from the upstream, as the sample servers do. Compression middleware is another culprit, because gzip encoders often wait for a block of data before emitting output. Disable compression for text/event-stream, or make sure your framework flushes the compressor after each event.
Corporate inspection proxies and some antivirus products also buffer, and you cannot reconfigure those. This is the strongest argument for keeping a fallback: if a client receives no event or heartbeat within, say, 45 seconds of opening a stream, switch it to long polling.
The HTTP/1.1 six-connection limit
Browsers cap concurrent HTTP/1.1 connections per origin, commonly at six. MDN’s EventSource documentation warns that SSE over HTTP/1.1 is limited to six connections per browser and domain, across all tabs, and that Chrome and Firefox marked the bug “Won’t fix.” An operator with seven dashboard tabs open finds the seventh tab frozen, along with every other fetch to that origin.
HTTP/2 removes the problem because all streams share one connection, and the concurrent stream limit is negotiated, commonly 100. WebSockets over HTTP/1.1 do not count against this pool in the same way, which is one historical reason teams chose them. In 2026 the better fix is to serve SSE over HTTP/2 end to end, or at least between browser and edge. If you cannot, share one stream across tabs with a SharedWorker or a BroadcastChannel leader election.
Mobile radios and battery
Persistent connections interact badly with cellular radios. Every packet, including a heartbeat, can promote the radio to a high-power state, which then lingers for a “tail” period before dropping back. Frequent heartbeats therefore cost battery out of proportion to their bytes. On mobile, prefer longer heartbeat intervals where your infrastructure allows, close streams when the app is backgrounded, and use platform push notifications for wake-ups rather than holding a socket open. QUIC’s connection migration can help WebTransport survive a Wi-Fi to cellular handover without a new handshake. TCP-based protocols must reconnect and resume.
Trade-offs, Gotchas, and What Goes Wrong
The most dangerous failure is the thundering reconnect. When a load balancer node, gateway or CDN location restarts, every client it held reconnects at almost the same moment. Take 50,000 SSE clients with a fixed retry: 3000: they all return within roughly three seconds, which is about 17,000 new TLS handshakes per second plus 50,000 replay queries against your log. Illustratively, that can be ten times your normal peak. The fix is jitter. Have the server send a randomised retry per client, or close with a 204 and let your own reconnect code apply exponential backoff with full jitter. Spread the same 50,000 clients over 30 seconds and the rate drops to under 2,000 per second.
The second is unbounded buffering of slow consumers. The browser WebSocket API has no backpressure: send() always queues, and bufferedAmount only reports the damage. On the server, a client on a weak link accumulates an outbound queue until the process runs out of memory. Cap per-client buffers, as the ws example does, and then either drop, conflate or disconnect. Chromium’s WebSocketStream adds stream-based backpressure, but Chrome remains the only browser implementing it, so you cannot rely on it.
Third, resume gaps. Teams adopt SSE for Last-Event-ID and then back it with a ten-second in-memory ring buffer on a single node. A client that reconnects to a different node, or after a longer outage, silently misses events. Store event IDs in a shared log, detect “ID too old” explicitly, and send a snapshot plus a fresh ID in that case.
Fourth, sticky-session assumptions. Long polling and some Socket.IO deployments require session affinity because the handshake and later polls must reach the same node. Affinity breaks during scale-out and node drains. Prefer designs where any gateway can serve any reconnecting client.
Fifth, WebTransport reachability. Some enterprise networks block or throttle UDP 443, and middleboxes vary in how well they handle QUIC. WebTransport is Baseline, but a meaningful slice of corporate users may still fail to connect. Always ship a WebSocket fallback, and measure the fallback rate rather than assuming it is zero. In other words, WebTransport adoption still runs through a websockets vs server-sent events decision for the fallback path.

Figure 4: A decision flow for picking a real-time web protocol. Start from traffic direction and network path, not from the API you know best.
Figure 4 encodes the questions in order of how often they settle the decision. Most IoT dashboards exit at the first branch toward SSE, which is why the websockets vs server-sent events question usually resolves faster than teams expect. The WebTransport branch requires three conditions together: loss-tolerant or multi-stream data, UDP reachability and a server stack you are ready to operate.
Decision Matrix for Apps and IoT Dashboards
The matrix below scores common workloads. “Primary” is our recommended default; “Fallback” is what to serve when the primary fails. These are opinions grounded in the mechanisms above, not measured results.
| Workload | Primary | Fallback | Why |
|---|---|---|---|
| Plant or fleet monitoring dashboard | SSE over HTTP/2 | Long polling | One-way, resume via Last-Event-ID, proxy-friendly |
| Alarm console with acknowledgements | SSE plus POST commands |
WebSocket | Commands are rare; ack via normal HTTP with auth headers |
| Engineering console on MQTT broker | MQTT over WebSockets | None, internal network | Topics, QoS and retained values come free |
| Collaborative editor or chat | WebSocket | Long polling | Frequent bidirectional messages |
| LLM token streaming | SSE | Chunked fetch | One-way text, short-lived streams |
| Multiplayer game or remote robot teleoperation | WebTransport | WebSocket | Datagrams avoid stale retransmits; streams avoid HOL blocking |
| Video or point-cloud digital twin viewer | WebTransport streams | WebSocket binary | Independent streams per asset or layer |
| Very low-rate notifications | Long polling or SSE | Platform push | Minimal infrastructure |
The real-time web protocols debate often resembles API style debates. As with our comparison of gRPC vs REST vs GraphQL vs Connect, the winning move is usually to separate the delivery semantics you need from the wire format that carries them.
Practical Recommendations
Start from the direction and shape of traffic. If the server talks and the client mostly listens, the websockets vs server-sent events choice should default to SSE over HTTP/2, with ordinary HTTP requests for the occasional command. You inherit reconnection, resume and full compatibility with HTTP tooling, from authentication middleware to access logs and tracing.
Pick WebSockets when clients genuinely send frequent messages, when you need binary framing in both directions, or when the browser must speak a broker protocol such as MQTT. Budget time for everything WebSockets do not give you: resume, acknowledgements, backpressure and authorisation per message.
Treat WebTransport as a targeted upgrade, not a default. It shines where head-of-line blocking or stale retransmissions hurt, such as teleoperation, live media and multi-stream telemetry. Ship it behind feature detection with a WebSocket fallback, and track the IETF draft revision your server library implements.
Whatever you choose, invest in the fan-out tier first. Revisit websockets vs server-sent events only after conflation and replay are in place, because they change the numbers. Conflation, a shared replay log and stateless gateways deliver more capacity and resilience than any protocol switch.
A short checklist before launch:
- Heartbeat every 15 to 30 seconds, below the shortest idle timeout on the path.
- Disable proxy buffering and compression for
text/event-stream. - Serve SSE over HTTP/2, or share one stream across tabs.
- Put a sequence ID on every message and keep a shared replay log.
- Cap per-client outbound buffers; conflate or disconnect slow clients.
- Add jitter to every reconnect path, server-sent
retryincluded. - Load-test a full gateway drain, not just steady state.
- Measure the fallback rate for WebTransport users on real networks.
Frequently Asked Questions
Is SSE better than WebSockets for dashboards?
For most dashboards, yes. Dashboards mostly receive data, and SSE delivers server-to-client streams over plain HTTP with built-in reconnection and Last-Event-ID resume. It passes through proxies and HTTP/2 multiplexing without special configuration, apart from disabling buffering. User actions such as acknowledging alarms fit naturally in normal POST requests. Choose WebSockets instead when the client sends frequent messages, needs binary data in both directions, or connects directly to an MQTT broker. In the websockets vs server-sent events trade-off, traffic direction is the deciding factor.
Is long polling still used in 2026?
Yes, mainly as a fallback. Long polling works through almost every proxy and firewall because each exchange is an ordinary HTTP request. Libraries such as Socket.IO keep it as a transport of last resort, and some services use it for low-rate notifications where holding a stream open is unnecessary. Its weakness, often skipped in websockets vs server-sent events guides, is overhead at high event rates, because every batch costs a full request with headers. It also needs a server-side cursor and event log to avoid losing events published between polls.
Do WebSockets work over HTTP/2 and HTTP/3?
RFC 8441 defines WebSockets over HTTP/2 using extended CONNECT, where the server enables SETTINGS_ENABLE_CONNECT_PROTOCOL and the client sends :protocol: websocket on a single stream. RFC 9220 defines the equivalent for HTTP/3. HTTP/2 bootstrapping is implemented in several browsers and servers, but support varies by stack, so test your exact path. This matters for websockets vs server-sent events planning, because SSE already rides HTTP/3 wherever your server does. However, as of November 2026 we could not find a browser shipping RFC 9220 by default; Chromium only announced an intent to prototype, and Firefox’s tracking bug remains open. Plan WebSocket capacity as TCP-based.
What is WebTransport and is it production ready?
WebTransport is a browser API for multiplexed reliable streams and unreliable datagrams over HTTP/3 and QUIC. It became Baseline “newly available” on 24 March 2026, when Safari 26.4 joined Chrome 97, Edge 97 and Firefox 114 in supporting it. The W3C published a Candidate Recommendation in July 2026, while the IETF protocol remains an Internet-Draft. The browser side is production-ready; the server ecosystem and UDP reachability on corporate networks are the remaining risks, so always keep a WebSocket fallback.
Why does my SSE connection drop after 60 seconds?
Something on the path has a 60-second idle timeout and saw no data. AWS Application Load Balancers default to 60 seconds, and nginx closes proxied streams after 60 seconds of upstream silence by default. Send an SSE comment line, such as : hb, every 15 to 30 seconds, or raise the timeout. If events arrive late in bursts rather than dropping, a proxy or compression layer is buffering the response; send X-Accel-Buffering: no and exclude text/event-stream from compression.
How many SSE connections can a browser open?
Over HTTP/1.1, browsers typically allow six concurrent connections per origin, and MDN notes this limit applies across all tabs for EventSource. A seventh SSE stream will hang and also block other requests to that origin. Over HTTP/2, all streams share one connection and the concurrency limit is negotiated, often 100 streams. Serving SSE over HTTP/2 is therefore the main fix. Alternatively, share a single stream across tabs using a SharedWorker or BroadcastChannel.
Further Reading
- QUIC and HTTP/3 deep dive: handshake, streams, loss recovery and congestion control — the transport that WebTransport exposes to the browser.
- MQTT 5 shared subscriptions, broker clustering and backpressure — scaling the ingest side that feeds your real-time gateways.
- gRPC vs REST vs GraphQL vs Connect API comparison — the request-response half of the same architecture decision.
- IoT protocol latency benchmarks: MQTT, CoAP, AMQP and HTTP/3 — device-side protocol trade-offs behind the dashboard.
- WHATWG, HTML Living Standard: Server-sent events.
- IETF, WebTransport over HTTP/3, draft-ietf-webtrans-http3-17, and W3C, WebTransport Candidate Recommendation, 30 July 2026.
By Riju — about
