Understanding the Differences Between Polling, Long Polling, SSE, and WebSocket
Contents
When I want something that happened on the server to show up on screen, I have been choosing between polling, SSE, and WebSocket by feel. They work, so it hasn't caused problems, but if someone asked how the four differ as HTTP, I couldn't explain it.
This time I prepared one small example, implemented the same thing four ways, and checked in order how the raw traffic differs.
A progress notification for a file conversion job. It advances 10% every second and goes back to 0% after reaching 100%. The progress comes from a single file shared by all four approaches. That way, the only difference between the four is how the updates are delivered.
const listeners = new Set();
const history = [];
let seq = 0, progress = 0;
setInterval(() => {
seq += 1;
progress = progress >= 100 ? 0 : progress + 10;
const event = { seq, progress };
history.push(event);
if (history.length > 50) history.shift();
for (const fn of listeners) fn(event);
}, 1000);
const subscribe = (fn) => (listeners.add(fn), () => listeners.delete(fn));
const current = () => ({ seq, progress });
const since = (lastSeq) => history.filter((e) => e.seq > lastSeq);
module.exports = { subscribe, current, since };
seq is the event's sequence number, and it matters later in the reconnection part. Unless noted otherwise, the code from here on is server-side, and each block's caption says which side it belongs to. To keep things short, I show only the key parts.
The client asks at regular intervals, and the server returns an ordinary response and is done. It is the simplest approach, and in exchange it misses events.
const body = JSON.stringify(current());
res.writeHead(200, {
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(body),
});
res.end(body);
Mermaid source
sequenceDiagram
participant C as Client
participant S as Server
C->>S: GET /progress
S-->>C: 200 / with Content-Length / seq=1
Note over S: seq=2 happens (nobody is listening)
Note over S: seq=3 happens (nobody is listening)
C->>S: GET /progress
S-->>C: 200 / seq=4$ curl -v http://localhost:3001/progress
< HTTP/1.1 200 OK
< Content-Type: application/json
< Content-Length: 22
<
{"seq":0,"progress":0}
Because Content-Length is set, the body length is fixed up front, and the receiver can tell the response is over once it has read 22 bytes.
Hitting it three times, 3 seconds apart, gave this.
13:38:03 {"seq":1,"progress":10}
13:38:06 {"seq":4,"progress":40}
13:38:09 {"seq":7,"progress":70}
seq jumps by 3, and the 2 events in between were lost without ever being seen. A shorter interval means fewer misses, but server load grows with the number of polls, not the number of events, so you keep hitting the server at the same pace even while the progress isn't moving.
It solves the "nothing new yet when I ask" problem by not responding until there is something to return.
const lastSeq = Number(url.searchParams.get('lastSeq') ?? 0);
const now = current();
if (now.seq > lastSeq) { send(res, now); return; } // if there is one, return right away
const unsubscribe = subscribe((event) => { // if not, wait without calling res.end()
unsubscribe();
send(res, event);
});
req.on('close', unsubscribe);
Mermaid source
sequenceDiagram
participant C as Client
participant S as Server
C->>S: GET /progress?lastSeq=1
Note over S: Nothing new<br/>hold without calling res.end()
Note over S: seq=2 happens
S-->>C: 200 / with Content-Length / seq=2
C->>S: GET /progress?lastSeq=2
Note over S: Hold again$ curl -v -w '\n所要時間: %{time_total}s\n' 'http://localhost:3002/progress?lastSeq=99999'
< HTTP/1.1 200 OK
< Content-Type: application/json
< Content-Length: 23
<
{"seq":2,"progress":20}
所要時間: 1.001126s
The set of headers is exactly the same as polling (the Content-Length value only changes with the body length). The only difference was the elapsed time (所要時間). In other words, long polling is not an HTTP feature. It is only a trick in how the app waits, and from HTTP's point of view the two are the same thing.
If you pass the returned seq as the next lastSeq and repeat, nothing gets missed.
13:38:49 {"seq":2,"progress":20}
13:38:49 {"seq":3,"progress":30}
13:38:50 {"seq":4,"progress":40}
13:38:51 {"seq":5,"progress":50}
The first two lines share the same second because seq=2 had already happened when I sent the first request with lastSeq=0. It took the "if there is one, return right away" branch in the code above and returned without waiting.
The server log shows a request coming in every time.
[long-polling] GET /progress lastSeq=0
[long-polling] GET /progress lastSeq=2
[long-polling] GET /progress lastSeq=3
[long-polling] GET /progress lastSeq=4
Sending 100 events means making the request 100 times. Then why not keep one response open and keep appending to it? That is the next approach.
Keep one response open and append to it each time an event happens. On the transfer side, the only change was not calling res.end().
The receiver is the browser's EventSource. This time I wanted logs, so I received the events with Node 24's built-in EventSource (--experimental-eventsource), which implements the same spec.
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
});
res.write('retry: 3000\n\n');
for (const event of since(Number(req.headers['last-event-id'] ?? 0))) sendEvent(res, event);
const unsubscribe = subscribe((event) => sendEvent(res, event));
const heartbeat = setInterval(() => res.write(': keep-alive\n\n'), 15000);
req.on('close', () => { unsubscribe(); clearInterval(heartbeat); });
function sendEvent(res, { seq, progress }) {
res.write(`id: ${seq}\n`);
res.write(`event: progress\n`);
res.write(`data: ${progress}\n`);
res.write(`data: (seq=${seq})\n`); // two data lines get joined with a newline
res.write('\n'); // this ends one event
}
Mermaid source
sequenceDiagram
participant C as EventSource
participant S as Server
C->>S: GET /events
S-->>C: 200 / text/event-stream / chunked
Note over C,S: No terminating chunk is sent<br/>the response stays unfinished
S-->>C: id: 1 / data: 10 / blank line
S-->>C: id: 2 / data: 20 / blank line
S-->>C: id: 3 / data: 30 / blank line$ curl -N -v --max-time 5 http://localhost:3003/events
< HTTP/1.1 200 OK
< Content-Type: text/event-stream
< Cache-Control: no-cache
< Transfer-Encoding: chunked
<
retry: 3000
id: 1
event: progress
data: 10
data: (seq=1)
id: 2
event: progress
data: 20
data: (seq=2)
(snip: 5 events arrived in 5 seconds)
* Operation timed out after 5002 milliseconds with 243 bytes received
The response is never terminated, so curl doesn't finish until it times out on its own.
Compared with polling, only two things differ as HTTP: Transfer-Encoding: chunked instead of Content-Length, and Content-Type being text/event-stream. I didn't write Transfer-Encoding in the code. Node chose it automatically because I didn't set Content-Length. So SSE is not a relative of WebSocket. It is an ordinary HTTP response that never ends, plus a convention for delimiting events.
curl decodes the chunked encoding before showing it, so I captured the raw bytes with a plain socket. I made \r and \n visible.
Transfer-Encoding: chunked\r\n
\r\n
d\r\n ← the next 0xd = 13 bytes
retry: 3000\n
\n
\r\n
6\r\n ← the next 6 bytes are data
id: 1\n
\r\n
10\r\n ← the next 0x10 = 16 bytes
event: progress\n
\r\n
9\r\n
data: 10\n
\r\n
e\r\n
data: (seq=1)\n
\r\n
1\r\n ← 1 byte
\n ← SSE blank line (end of the frame)
\r\n
Each res.write() sends a pair of a length and data. chunked only declares how many bytes the next chunk has and says nothing about the total length, so you can keep appending to the end without deciding the total up front.
The end of the body is defined as the moment a zero-length chunk is sent (0\r\n\r\n if there are no trailers), and what SSE does is never send it. It doesn't appear anywhere in the output above.
You can't do this with Content-Length. The response is complete as soon as the declared length is reached, and if you write a falsely large value, the receiver keeps waiting forever for a rest that never comes. To keep sending without declaring a length while reusing the connection in HTTP/1.1, you need chunked.
Not declaring a length is also possible without chunked. With neither Transfer-Encoding nor Content-Length, the body lasts until the connection closes (RFC 9112 §6.3). But then the connection can't be reused. HTTP/2 and later don't have chunked at all and do the same thing with frames.
Besides how data is transferred, SSE also specifies reconnection. When the connection drops, EventSource reconnects automatically, and at that point it sends back the last id: it received in the Last-Event-ID request header.
While the client was receiving, I killed the server and started it again 8 seconds later.
04:40:49.689 progress lastEventId=5
04:40:50.693 error readyState=0 ← the moment I killed it
04:40:53.698 error readyState=0
04:40:56.702 error readyState=0
04:40:59.708 open readyState=1 ← reconnected on its own
From the drop at 50.693, it tried again at 53.698, 56.702, and 59.708, exactly every 3 seconds, so the retry: 3000 sent at the start of the stream is in effect as is. The server log shows that the client's report arrived too.
[sse] connected Last-Event-ID=5 path=/events
I didn't write a single line of app code for this.
But only the header arrives. Whether the stream can continue from there depends on how the server is built. Here is the log right after reconnecting.
04:40:59.728 progress lastEventId=1 ← back to 1 from 5
04:41:00.730 progress lastEventId=2
This implementation kept event numbering and history in process memory, so the restart reset the numbering to 0. Even after receiving Last-Event-ID: 5, it had nothing to return, and it started streaming again from a newly numbered id: 1. To resume properly, you need to move the IDs and history out of the process, into something like a DB or Redis Streams.
Never terminating raises the question of how to wrap up when the job finishes. When I simply sent the terminating chunk with res.end(), the client reconnected after an error.
06:09:09.212 error readyState=0
06:09:13.209 open readyState=1 ← it reconnected
06:09:15.211 error readyState=0 ← sent 3 events and terminated again
06:09:19.214 open readyState=1 ← back again
The spec says to reconnect when the body ends normally, just as when the connection is cut, so terminating correctly doesn't end the stream. You need to stop it explicitly in one of two ways: define an event that signals completion and call close() on the client, or have the server return 204 No Content to requests for a finished job. With the latter, the client still connects once before giving up, so you have to expect at least one more request after completion.
This is where you end up when you want two-way communication or to send binary data. It is the only one of the four that returns 101 and stops being HTTP. I didn't use a library and wrote only the handshake and frame building myself.
const GUID = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'; // fixed value defined in RFC 6455
server.on('upgrade', (req, socket) => {
const key = req.headers['sec-websocket-key'];
const accept = crypto.createHash('sha1').update(key + GUID).digest('base64');
socket.write(
'HTTP/1.1 101 Switching Protocols\r\n' +
'Upgrade: websocket\r\n' +
'Connection: Upgrade\r\n' +
`Sec-WebSocket-Accept: ${accept}\r\n\r\n`
);
const unsubscribe = subscribe(({ seq, progress }) => {
socket.write(encodeTextFrame(JSON.stringify({ seq, progress })));
});
socket.on('close', unsubscribe);
});
// 0x81 = FIN(1) + opcode 1(text). Frames from the server are not masked.
// Only for payloads up to 125 bytes. Longer ones need an extended length (the progress JSON here is short enough).
function encodeTextFrame(text) {
const payload = Buffer.from(text, 'utf8');
return Buffer.concat([Buffer.from([0x81, payload.length]), payload]);
}
Mermaid source
sequenceDiagram
participant C as WebSocket
participant S as Server
C->>S: GET / <br/>Upgrade: websocket<br/>Sec-WebSocket-Key
S-->>C: 101 Switching Protocols<br/>Sec-WebSocket-Accept
Note over C,S: Not HTTP from here on
S-->>C: 0x81 frame / seq=1
S-->>C: 0x81 frame / seq=2
Note over C,S: The spec allows the client to send too<br/>(not implemented here)$ curl -v --max-time 3 \
-H 'Connection: Upgrade' -H 'Upgrade: websocket' \
-H 'Sec-WebSocket-Version: 13' \
-H 'Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==' \
http://localhost:3004/
> Connection: Upgrade
> Upgrade: websocket
> Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
>
< HTTP/1.1 101 Switching Protocols
< Upgrade: websocket
< Connection: Upgrade
< Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
It is the only one of the four that isn't 200, and it has no Content-Type either. 101 itself is an HTTP response, but HTTP ends with this response. The handshake itself is HTTP, though, so you could say WebSocket isn't built on top of HTTP. It borrows HTTP only for the entrance and leaves right away. Sec-WebSocket-Accept is just the received key plus a fixed GUID, hashed with SHA-1 and Base64-encoded, so it has no cryptographic meaning. It was a step only for confirming that the other side understands the WebSocket spec.
SSE's automatic reconnection is part of the EventSource spec, not an HTTP feature, so WebSocket doesn't get it. The WebSocket API doesn't define it, so when the connection drops, readyState becomes 3 and that is the end. It didn't recover unless I wrote code to reconnect.
These are the response headers of the four approaches with the same example. I left out Date and Connection, which all four share, and Cache-Control, which I added myself for SSE.
== Polling == == Long polling ==
HTTP/1.1 200 OK HTTP/1.1 200 OK
Content-Type: application/json Content-Type: application/json
Content-Length: 23 Content-Length: 23
== SSE == == WebSocket ==
HTTP/1.1 200 OK HTTP/1.1 101 Switching Protocols
Content-Type: text/event-stream Upgrade: websocket
Transfer-Encoding: chunked Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
Polling and long polling had the same headers. Long polling isn't an HTTP feature. It only delays when the response is returned, so the two can't be told apart at the protocol level. SSE also stays at 200. Only the way the length is indicated and the Content-Type changed, which means it doesn't upgrade. Only WebSocket returns 101, and that is where it leaves HTTP.
What grows with each approach isn't features but the number of parts you have to look after yourself. Polling just repeats an ordinary GET. Long polling adds the decision to wait. SSE has you write the frame delimiters yourself. WebSocket has you do the handshake and frame building yourself.
How easy it is to observe drops in the same order. Up to SSE, curl -v showed the body as is, but with WebSocket, frame headers got mixed in after the 101 and it was no longer readable.
I can now explain the things I was choosing between by feel in terms of where they differ in HTTP. I had thought of SSE as a stripped-down WebSocket, but looking at the raw traffic, it is an HTTP response that never ends, and something entirely different.
I hope this helps anyone else who has been choosing between these by feel.
Translated from the Japanese original.
Thanks. I'll look into it.
Sorry, that didn't go through. Please try again later.