The server has something to say and HTTP does not let it
HTTP was born as question and answer: the client asks, the server replies, and if the server has news it has to wait for someone to ask it something. A dashboard that must show a value the moment it changes, a notification, a chat, a shared editor all break this scheme. The three most used solutions are polling, Server-Sent Events (SSE) and WebSockets, and the right question is not which one is the best but which one costs the least for your problem.
This guide puts them to the test with code that I ran or compiled. Where the example would require a
server listening on a port, I ran the logic with fake requests and responses and injected
timers, and the text says so; the Angular code and the ws code are compiled, not
connected to a server. You will find fewer figures than in a typical guide: latencies and "tens of thousands of connections"
depend on your machine, and I did not measure them here.
Polling: the solution that needs nothing new
In short polling the client repeats a request at fixed intervals. The server has no special
code: an ordinary route that returns the latest value. All the logic lives in the client, and in
Angular it is an RxJS timer with switchMap towards HttpClient. The
listing is compiled with Angular 21.2.26 (exit 0), not run.
import { HttpClient } from '@angular/common/http';
import { Injectable, inject } from '@angular/core';
import { Observable, retry, share, switchMap, timer } from 'rxjs';
export interface Reading {
temperature: number;
timestamp: number;
}
@Injectable({ providedIn: 'root' })
export class SensorPollingService {
private readonly http = inject(HttpClient);
/** Short polling: one request every 5 seconds as long as there is at least one subscriber. */
readonly reading$: Observable<Reading> = timer(0, 5000).pipe(
switchMap(() => this.http.get<Reading>('/api/sensor')),
retry({ delay: 5000 }),
share(),
);
}
Three choices to note. timer(0, 5000) starts immediately and then repeats, whereas
interval(5000) would have waited five seconds for the first reading. switchMap
abandons a request still in flight when another one starts, so a slow response does not arrive after
a more recent one. share() makes several components share the same stream: without it, each
subscriber would start its own polling. The trade-off lies in the interval: the maximum latency with which you see a
change is the interval itself, and every client, even when nothing has changed, costs a request.
Short polling is the right choice when data changes rarely, timeliness is not critical and you want zero new infrastructure: the status of an order, the availability of a seat. It stops being so when to get fast updates you have to shorten the interval, because at that point you spend requests to discover that nothing has changed.
Long polling: keeping the request open
Long polling inverts the rhythm: the server holds the request pending until it has something
to say (or a timeout expires), and the client immediately opens another one. The following handler uses an
EventEmitter, a clock and a timer passed in as parameters, so I can run it with fake
requests and simulated time. No server, no real waiting.
import { EventEmitter } from 'node:events';
// Long polling handler with injected clock and timers: no server, no real waiting.
export const createLongPoll = ({ waitMs, now, setTimer, clearTimer }) => {
const emitter = new EventEmitter();
let latest = { value: 0, timestamp: 0 };
const publish = (value) => {
latest = { value, timestamp: now() };
emitter.emit('update', latest);
};
const handler = (req, res) => {
const since = Number(req.query.since) || 0;
if (latest.timestamp > since) return res.json(latest); // something more recent already exists
const onUpdate = (data) => { clearTimer(timer); res.json(data); };
const timer = setTimer(() => {
emitter.off('update', onUpdate);
res.status(204).end(); // nothing new: the client retries
}, waitMs);
emitter.once('update', onUpdate);
// res, not req: since Node 16 the request's 'close' fires once the request has completed.
res.on('close', () => {
clearTimer(timer);
emitter.off('update', onUpdate);
});
};
return { handler, publish, listeners: () => emitter.listenerCount('update') };
};
// --- demo ---
let current = 0;
const pendingTimers = new Map();
let nextId = 0;
const lp = createLongPoll({
waitMs: 30_000,
now: () => current,
setTimer: (fn, ms) => { const id = ++nextId; pendingTimers.set(id, { fn, at: current + ms }); return id; },
clearTimer: (id) => pendingTimers.delete(id),
});
const fake = (name) => {
const res = new EventEmitter();
res.json = (d) => { console.log(`${name}: 200 ${JSON.stringify(d)}`); res.emit('close'); };
res.status = (s) => ({ end: () => { console.log(`${name}: ${s}`); res.emit('close'); } });
return res;
};
current = 1000; lp.publish(7);
lp.handler({ query: { since: '0' } }, fake('A (since=0) '));
const resB = fake('B (since=1000) ');
lp.handler({ query: { since: '1000' } }, resB);
console.log('listeners waiting after B:', lp.listeners());
current = 4000; lp.publish(8);
console.log('listeners after the publish:', lp.listeners());
const resC = fake('C (since=4000) ');
lp.handler({ query: { since: '4000' } }, resC);
current = 34_000;
for (const [id, t] of [...pendingTimers]) if (t.at <= current) { pendingTimers.delete(id); t.fn(); }
console.log('listeners after the timeout of C:', lp.listeners());
const resD = fake('D (since=4000) ');
lp.handler({ query: { since: '4000' } }, resD);
resD.emit('close'); // the client disconnects first
console.log('listeners after the disconnection of D:', lp.listeners(), '| pending timers:', pendingTimers.size);
// Output (Node 24.11.0, identical in two runs):
// A (since=0) : 200 {"value":7,"timestamp":1000}
// listeners waiting after B: 1
// B (since=1000) : 200 {"value":8,"timestamp":4000}
// listeners after the publish: 0
// C (since=4000) : 204
// listeners after the timeout of C: 0
// listeners after the disconnection of D: 0 | pending timers: 0
Read the output line by line. A receives data immediately because one already exists that is more recent than
since=0. B asks from timestamp 1000, finds nothing more recent and stays waiting (one
listener registered); the publish wakes it up and the listener disappears. C waits, times out and receives
204: "nothing new, ask again". D disconnects while waiting, and both the listener count and the timer
count return to zero. That last line is the reason the listing exists: a long polling that does not
clean up its listeners leaks memory for every client that leaves.
There is a detail that ruins many examples online. Here the cleanup is attached to res.on('close'),
not to req.on('close'): the Node documentation specifies that since version 16 the
close event of IncomingMessage is emitted when the request has been completed, not
when the connection closes, whereas the one of ServerResponse signals that the response has
ended or that the connection dropped before that. With req, for a GET without a body, the cleanup
could fire immediately and remove the listener before any update. I could not try it
with a real server (we do not start ports here), so the rule is the one in the documentation.
The Angular client has to do three things that the version you find in tutorials does badly: start again as soon as
a response arrives (even a 204), remember the last timestamp and really stop when the subscriber
goes away. The code uses defer and repeat instead of a function that calls itself:
that way closing the subscription breaks the loop, and a network error is retried with an increasing
wait.
import { HttpClient } from '@angular/common/http';
import { Injectable, inject } from '@angular/core';
import { Observable, defer, filter, repeat, retry, tap, timer } from 'rxjs';
export interface Update {
value: number;
timestamp: number;
}
@Injectable({ providedIn: 'root' })
export class LongPollingService {
private readonly http = inject(HttpClient);
updates$(): Observable<Update> {
return new Observable<Update>((observer) => {
let since = 0;
const subscription = defer(() =>
this.http.get<Update | null>('/api/long-poll', { params: { since } }),
)
.pipe(
retry({ delay: (_e, n) => timer(Math.min(1000 * 2 ** (n - 1), 30_000)) }),
tap((u) => { if (u) since = u.timestamp; }),
repeat(), // as soon as a response arrives (200 or 204) start again
filter((u): u is Update => u !== null),
)
.subscribe(observer);
return () => subscription.unsubscribe(); // closing the subscription stops the loop
});
}
}
The since parameter travels as a query: the server compares that value with the timestamp of the latest
event, which is why the 204 response does not change it. The 30-second cap on the wait is an example
value, to be tuned against the timeouts of the proxies in between (more on that later). The trade-off of
long polling is that every client occupies an open connection for the whole wait: you are close to the
costs of SSE without having its protocol advantages.
Server-Sent Events: the server writes, the browser listens
SSE is defined in chapter 9.2 of the HTML standard (WHATWG), not in a W3C document of its own, and
the server answers with type text/event-stream. The format is line-based text: a field and its
value separated by a colon, and an empty line that closes the event. The fields are data,
event (the type name), id and retry; a line starting with a
colon is a comment, and is used as a heartbeat to keep the connection alive.
The browser does the hard work with EventSource: it reconnects by itself and, on reconnection,
sends the last id received in the Last-Event-ID header, so that the server
can resume from the right point. To understand the format, the following listing writes a stream and
parses it, splitting it mid-line as the network does: the case that breaks parsers written in a hurry.
// Server-side formatting and client-side parsing of a text/event-stream (WHATWG HTML 9.2).
export const formatEvent = ({ event, id, data, retry }) => {
let out = '';
if (retry !== undefined) out += `retry: ${retry}\n`;
if (event) out += `event: ${event}\n`;
if (id !== undefined) out += `id: ${id}\n`;
for (const line of String(data).split('\n')) out += `data: ${line}\n`; // one data: per line
return out + '\n';
};
export const createParser = (onEvent) => {
let leftover = '';
let data = [];
let type = '';
let lastId = '';
const handleLine = (l) => {
if (l === '') { // empty line: deliver the event
if (data.length > 0) onEvent({ type: type || 'message', data: data.join('\n'), id: lastId });
data = []; type = '';
return;
}
if (l.startsWith(':')) return; // comment (used as keep-alive)
const i = l.indexOf(':');
const field = i === -1 ? l : l.slice(0, i);
let value = i === -1 ? '' : l.slice(i + 1);
if (value.startsWith(' ')) value = value.slice(1);
if (field === 'data') data.push(value);
else if (field === 'event') type = value;
else if (field === 'id') lastId = value;
};
return (chunk) => {
leftover += chunk;
const lines = leftover.split(/\r\n|\n|\r/);
leftover = lines.pop(); // the last line may be incomplete: keep it for the next chunk
lines.forEach(handleLine);
};
};
const stream =
formatEvent({ event: 'metrics', id: 1, data: '{"cpu":12}' }) +
': keep-alive\n\n' +
formatEvent({ id: 2, data: 'line one\nline two' });
console.log(JSON.stringify(stream));
const received = [];
const feed = createParser((e) => received.push(e));
// Split the stream in the middle of a line, as the network does.
for (const chunk of [stream.slice(0, 17), stream.slice(17, 45), stream.slice(45)]) feed(chunk);
for (const e of received) console.log(JSON.stringify(e));
// Output (Node 24.11.0, identical in two runs):
// "event: metrics\nid: 1\ndata: {\"cpu\":12}\n\n: keep-alive\n\nid: 2\ndata: line one\ndata: line two\n\n"
// {"type":"metrics","data":"{\"cpu\":12}","id":"1"}
// {"type":"message","data":"line one\nline two","id":"2"}
The first event has a type (metrics) and an id; the comment
: keep-alive produces no event; in the second, the two-line data becomes two
data: lines and the client joins them with a line feed, as the standard prescribes. The
parser's trick is to set aside the last line of every chunk, because it may be incomplete: without that,
a message cut by the network is lost or corrupted.
In Angular you do not need a parser, because the browser does it: it is enough to wrap EventSource in
an Observable. The listing is compiled, not connected to a server.
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
@Injectable({ providedIn: 'root' })
export class SseService {
events$<T>(url: string, type: string): Observable<T> {
return new Observable<T>((observer) => {
const source = new EventSource(url);
source.addEventListener(type, (e) => {
try {
observer.next(JSON.parse((e as MessageEvent<string>).data) as T);
} catch (error) {
observer.error(error); // a message that is not JSON: you report it, you do not ignore it
}
});
// onerror also fires during automatic reconnections: nothing is closed here.
return () => source.close();
});
}
}
Two notes. The service does not close the source on onerror, because an error during the
automatic reconnection is not a final failure; it closes it only when the subscription ends. And a
message that is not JSON it reports as an error, instead of losing it. If your application uses Zone.js,
the EventSource callbacks re-enter the zone and the template update works; if it is zoneless,
update a signal instead of an arbitrary property.
The SSE limits that decide the choice
The first is the number of connections. MDN warns that, without HTTP/2, SSE suffers from a limit of
six open connections per browser and per domain, a problem that MDN marks as "Won't fix" in Chrome and Firefox, and
specifies that the limit applies across all tabs together. With HTTP/2 the number of simultaneous streams is negotiated and MDN
indicates a default value of 100. The second is the data type: SSE carries text, and binary data has to be
encoded. The third is authentication: the MDN page for EventSource shows the URL and
the withCredentials option, not custom headers, so an Authorization token
cannot be sent that way and you resort to cookies or a token in the URL (with the risks that entails), or to
fetch with stream reading.
On the server, two details. Do not set the Connection: keep-alive header as many
examples do: RFC 9113 forbids connection-specific headers in HTTP/2 messages, and behind an
HTTP/2 server the header is useless or harmful. And if you go through nginx, the response may be held
in a buffer: the nginx documentation says buffering can be disabled with the response header
X-Accel-Buffering: no (or with the proxy_buffering directive), otherwise
events arrive in blocks. Also avoid Access-Control-Allow-Origin: * in examples: with an
origin different from yours, choose explicitly which one.
WebSocket: a conversation, not a stream
WebSocket (RFC 6455) opens a bidirectional connection: after an HTTP handshake with
Upgrade: websocket, the server answers 101 Switching Protocols and from that moment
client and server exchange messages in both directions. To verify that both speak the
same protocol, the server must compute the response key, and this can be run:
base64(SHA-1(key + GUID)). The listing uses the RFC's sample key.
import { createHash } from 'node:crypto';
// RFC 6455, 1.3: Sec-WebSocket-Accept = base64(SHA-1(key + GUID)).
const GUID = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11';
const accept = (key) => createHash('sha1').update(key + GUID).digest('base64');
console.log('accept for the RFC sample key:', accept('dGhlIHNhbXBsZSBub25jZQ=='));
// RFC 6455, 5.2: 7 bits, or 7+16 bits, or 7+64 bits of length; +4 mask bytes from the client.
const header = (length, fromClient) => {
const base = 2;
const extended = length <= 125 ? 0 : length <= 0xffff ? 2 : 8;
return base + extended + (fromClient ? 4 : 0);
};
for (const n of [5, 125, 126, 65_535, 65_536]) {
console.log(`payload ${String(n).padStart(6)} bytes: header server->client ${header(n, false)} bytes, client->server ${header(n, true)} bytes`);
}
// Output (Node 24.11.0, identical in two runs):
// accept for the RFC sample key: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
// payload 5 bytes: header server->client 2 bytes, client->server 6 bytes
// payload 125 bytes: header server->client 2 bytes, client->server 6 bytes
// payload 126 bytes: header server->client 4 bytes, client->server 8 bytes
// payload 65535 bytes: header server->client 4 bytes, client->server 8 bytes
// payload 65536 bytes: header server->client 10 bytes, client->server 14 bytes
The result matches the RFC's value (s3pPLMBiTxaQ9kYGzzhZRbK+xOo=). The second
part computes, from the rules in section 5.2, how much a message header weighs: two bytes up to
125 bytes of data, four up to 65,535, ten beyond that, and four more for messages going from the client to the
server, which are always masked. That is why the comparison with HTTP, where every request carries headers
of hundreds of bytes, is sharp on small and frequent messages, and less relevant on large and rare ones.
On the server side I use the ws package (8.23.0). The listing adds two things that minimal examples
skip: a limit on message size (maxPayload) and a heartbeat with ping and pong
that closes clients that do not answer, because proxies, NATs and mobile networks can let a
connection die without telling anyone. The listing is compiled with TypeScript, not started.
import { WebSocket, WebSocketServer } from 'ws';
const wss = new WebSocketServer({ port: 3000, maxPayload: 64 * 1024 });
const alive = new WeakSet<WebSocket>();
wss.on('connection', (ws: WebSocket) => {
alive.add(ws);
ws.on('pong', () => alive.add(ws));
ws.on('message', (data) => {
for (const client of wss.clients) {
if (client !== ws && client.readyState === WebSocket.OPEN) client.send(data.toString());
}
});
});
// Heartbeat: every 30 s, whoever has not answered the previous ping is closed.
const heartbeat = setInterval(() => {
for (const ws of wss.clients) {
if (!alive.has(ws)) { ws.terminate(); continue; }
alive.delete(ws);
ws.ping();
}
}, 30_000);
wss.on('close', () => clearInterval(heartbeat));
The server does not interpret messages: it relays them to the other clients. In a real application you should validate them (shape and size) and authenticate the connection already in the handshake, because after the upgrade there is no HTTP request left to check. With several server instances, clients connected to different instances do not see each other: you need a shared channel. Redis Pub/Sub is the common solution, but its documentation specifies that it offers "at-most-once" delivery: if a subscriber cannot handle the message or the network drops, the message is lost forever. If you cannot afford losses, the same page points to Redis Streams. I ran nothing on Redis in this guide.
Reconnecting: the client is yours
Unlike EventSource, the browser's WebSocket API does not reconnect by itself. With RxJS
you can get it with retry, but it is easy to get the wait wrong. The delay function
receives the attempt number, and it is worth knowing what value it starts from: the following experiment makes a
source fail three times and records the numbers received (RxJS 7.8.2).
import { defer, throwError, of, timer, retry } from 'rxjs';
// A source that fails three times and then succeeds.
let attempts = 0;
const source = defer(() => (++attempts <= 3 ? throwError(() => new Error('dropped')) : of('connected')));
const seen = [];
source
.pipe(
retry({
count: 5,
delay: (_error, attemptNumber) => {
seen.push(attemptNumber);
return timer(0); // zero delay: here the number matters, not the wait
},
}),
)
.subscribe({ next: (v) => console.log('result:', v), complete: () => console.log('numbers passed to delay():', JSON.stringify(seen)) });
// Exponential backoff with a cap; the jitter is left out so the output is repeatable.
const wait = (n) => Math.min(1000 * 2 ** (n - 1), 30_000);
console.log('waits for n = 1..8:', JSON.stringify([1, 2, 3, 4, 5, 6, 7, 8].map(wait)));
// Output (Node 24.11.0, identical in two runs):
// waits for n = 1..8: [1000,2000,4000,8000,16000,30000,30000,30000]
// result: connected
// numbers passed to delay(): [1,2,3]
The first number is 1, not 0: with the formula 1000 * 2 ** (n - 1) the first wait is one
second, and the 30-second cap is reached at the sixth attempt. A common example writes
1000 * Math.pow(2, retryCount) and comments "1s, 2s, 4s", but with the number starting from 1 the first
real wait is two seconds. In production add a bit of randomness (jitter) to the wait,
otherwise, after an outage, all clients reconnect at the same instant: I left it out here to
get a repeatable output. The Angular service that follows uses the same scheme.
import { Injectable } from '@angular/core';
import { Observable, retry, timer } from 'rxjs';
import { WebSocketSubject, webSocket } from 'rxjs/webSocket';
export interface Message {
type: 'chat' | 'system' | 'error';
user?: string;
text: string;
}
@Injectable({ providedIn: 'root' })
export class WsClientService {
private socket$?: WebSocketSubject<Message>;
connect(url: string): Observable<Message> {
this.socket$ = webSocket<Message>(url);
return this.socket$.pipe(
// retry starts a new subscription: the WebSocketSubject opens a new connection.
retry({ delay: (_error, n) => timer(Math.min(1000 * 2 ** (n - 1), 30_000)) }),
);
}
send(message: Message): void {
this.socket$?.next(message);
}
close(): void {
this.socket$?.complete();
}
}
One point the code does not solve: retry starts again only if the connection ends with an
error. A clean close by the server completes the Observable and the client stays still. If
you want to reconnect in that case too, you have to tell a deliberate close() from a
server that closed; it is a design decision, and it must be made before writing the reconnection.
The comparison, with what I could verify
The table contains only what the cited sources support or what I measured. I removed latencies, server-side connection caps and judgements such as "medium scalability", which depend on your load.
| Aspect | Polling (short and long) | SSE | WebSocket |
|---|---|---|---|
| Direction | The client asks | From server to client | Bidirectional |
| Transport | HTTP requests | One HTTP response that stays open (text/event-stream) | HTTP handshake, then the WebSocket protocol (RFC 6455) |
| Reconnection | You write it | Automatic in the browser, with Last-Event-ID | You write it |
| Binary data | With encoding | Text only | Text or binary messages |
| Browser headers | Any, with HttpClient | No custom ones (MDN) | No custom ones from the browser constructor |
| Limit per domain | That of HTTP requests | 6 on HTTP/1.1, negotiated (100 by default) on HTTP/2 (MDN) | I did not measure it |
One entry in this table must be read with an explicit caveat: the last WebSocket row says "I did not
measure it" because the previous version of this article claimed "no limit" without a source. The
Authorization header on the browser's WebSocket constructor is another absence that I state on the basis
of the API, not of a page that lists it: if you need it, check the documentation of the browser you use.
How to choose
The four following questions almost always lead to the choice, in the order in which it is worth asking them. Changing the order changes the answer, because the first question discards the two most expensive solutions.
- Does the client need to send frequent data to the server on the same connection? If not, WebSocket is oversized: an ordinary HTTP request is enough for user actions.
- How bad is waiting a few seconds? If it is not bad, polling with a reasonable interval is the simplest solution to maintain.
- Does the server need to push events continuously? Then SSE: reconnection, resuming from the last event and ordinary HTTP included.
- Do you really need conversation, binary data or very frequent messages in both directions? Only at this point WebSocket.
The trade-off the questions hide is operational complexity: the further down the list, the more state you keep on the server and the more work falls on whoever manages load balancers, proxies and reconnections. My preference, which is an opinion and not a measurement, is to start with SSE for everything that is "the server notifies" and to bring in WebSocket for the cases where the client truly talks. As a limit to the rule, an environment where a corporate proxy blocks long streams makes polling preferable, because it is the only one that asks nothing of the infrastructure. To go deeper into the security side of these connections (authenticating after the upgrade, limiting messages), also read OWASP Top 10 2025 for web developers.
What you can do now
You can choose between polling, SSE and WebSocket with four questions instead of a table of scores. You have seen
the long polling mechanism run (with the cleanup many people forget), the SSE format with a stream
split mid-line, the handshake and the weight of WebSocket frames, and the attempt number that RxJS passes to
retry. You know which parts I did not try: listening servers, the proxy, Redis and the behaviour
of req.on('close'). If you are designing a real feature, the next step is to try your
choice behind the proxy you will use in production, because that is where long streams break.
For two cases where WebSocket carries a real product, read Real-Time Collaboration in EdTech: CRDTs and WebSockets and Durable Objects: Consistent State and WebSockets at the Edge.
Sources
- WHATWG HTML Living Standard, 9.2 Server-sent events - stream format, parsing rules, Last-Event-ID header, consulted on 2026-11-12
- MDN: EventSource - six-connection limit on HTTP/1.1, negotiated streams on HTTP/2, withCredentials option, consulted on 2026-11-12
- MDN: Using server-sent events - data, event, id, retry fields, consulted on 2026-11-12
- RFC 6455: The WebSocket Protocol - handshake, accept key, frame format, consulted on 2026-11-12
- RFC 9113: HTTP/2 - section 8.2.2, connection-specific headers forbidden, consulted on 2026-11-12
- nginx: ngx_http_proxy_module - buffering and the X-Accel-Buffering response header, consulted on 2026-11-12
- Redis: Pub/Sub - at-most-once delivery semantics, consulted on 2026-11-12
- Node.js: http - close event of IncomingMessage (since v16) and of ServerResponse, consulted on 2026-11-12
Programs b1, b2, b3 and b4 were run with Node 24.11.0, twice with identical output, in a temporary folder outside the repository (rxjs 7.8.2). The Angular code (21.2.26, strictTemplates) and the ws 8.23.0 code were compiled with ngc, exit 0. No server started, no port opened, no writes to Redis.

Commenti
Caricamento commenti...
Sign in to comment