Courses / Node.js: From First Script to Production / Chapter 20
Module 8 · Production services · Chapter 20 of 27
Real-Time Node: Server-Sent Events and WebSockets
Builds on Building a Basic Web Server with node:http, Advanced Topics: Child Processes, Worker Threads, Cluster and Debugging and Profiling Node: CPU Profiles, Flame Graphs and Load Tests. Next up: Testing Node Code with node:test.
Part 1 · Four ways to push an update to a browser
The server cannot speak first
When a wicket falls, a cricket score page should change in front of the reader without a refresh.
HTTP is a request and response protocol. The browser asks, and the server answers. A server has no way to start a conversation with a page by itself. To get an update to the reader sooner than the next page load, you choose among four techniques.
| How it works | Direction | Reconnects by itself | |
|---|---|---|---|
| Polling | the client asks again every few seconds | client asks, server answers | not needed, each request is new |
| Long polling | the server holds a request open until it has news or a timeout | client asks, server answers late | no, the client sends the next request |
| Server-Sent Events (SSE) | one HTTP response that never ends and carries a stream of events | server to client only | yes, in the browser's EventSource |
| WebSocket | an HTTP request that is upgraded into a two-way connection | both ways | no, your code does it |
How it worksthe client asks again every few seconds
Directionclient asks, server answers
Polling, measured
Polling is the baseline, and it is the right answer more often than people expect. The script below runs a score server and a client in one process. The score changes four times over about four seconds, and the client asks every 250 ms and counts how many replies carried new information.
import http from 'node:http'; import { setTimeout as sleep } from 'node:timers/promises'; let runs = 120; let requests = 0; const server = http.createServer((req, res) => { requests++; res.end(JSON.stringify({ runs })); }).listen(55627, '127.0.0.1'); // The score changes four times during the test. for (const ms of [700, 1500, 2300, 3100]) { setTimeout(() => { runs += 4; }, ms); } let seen = -1; let useful = 0; for (let i = 0; i < 16; i++) { const body = await (await fetch('http://127.0.0.1:55627/')).json(); if (body.runs !== seen) { seen = body.runs; useful++; } await sleep(250); } console.log('requests sent:', requests); console.log('responses that carried news:', useful, '(the first is the', 'starting score)'); console.log('score changes in that time: 4'); server.close(); server.closeAllConnections();
requests sent: 16 responses that carried news: 5 (the first is the starting score) score changes in that time: 4
Node 24.18.0.
Sixteen requests were sent. Five replies carried news: the first one, which gives the starting score, and four real changes. The other eleven repeated what the client already knew. Each change also reached the client up to 250 ms late, because the client could not know about it until its next request.
Now scale the numbers up. On a results day, 5 lakh students with a page open, each polling every 5 seconds, send 1 lakh requests a second, and most of them return "no change". Shortening the interval improves delay and makes that load worse, and lengthening it does the reverse. That trade-off is the reason for the other techniques.
Long polling, SSE and WebSocket, and when to use each
Long polling removes the wasted replies. The server holds the request open until it has an update, or until a timeout, and then answers. The client reacts and sends the next request at once. The delay drops to the network time. The cost is one full HTTP request per update, and a hanging request for every client. It was the common workaround before the next two existed, and it still works behind strict proxies.
Server-Sent Events keep a single response open and write many small messages into it. The format is plain text lines. Browsers read it with the built-in EventSource class, which reconnects by itself and tells the server the last event it saw. It carries text only, and only from server to client. That is enough for score feeds, notifications, progress bars and dashboards.
WebSocket is a separate protocol that starts as an HTTP request and then becomes a raw two-way channel carrying framed messages, text or binary. It suits chat, games and collaborative editing, where the client sends as much as it receives. It does more, and it demands more: you handle reconnection, heartbeats and fan-out yourself.
A sensible rule: use SSE when only the server talks, WebSocket when both sides talk often, and polling when updates are rare or the network will not allow the others. The next two lessons build SSE and WebSocket servers with Node, and the last two cover the work that keeps them healthy.
A news ticker shows headlines pushed by the server, and users never send anything back. Which technique is the simplest fit?
- Server-Sent Events. It is one-way, runs over ordinary HTTP and reconnects by itself in the browser.
In the polling run, 16 requests found only 4 changes. What would shrinking the interval to 50 ms do?
- Delay would fall to about 50 ms at most, but the number of requests would grow five times, and almost all would still say "no change".
What does long polling avoid that ordinary polling has?
Part 2 · Server-Sent Events with node:http
The event stream format
An SSE connection is an ordinary HTTP response with a special content type and no end. The server writes events as lines of text.
The response has Content-Type: text/event-stream. Each event is a block of lines that ends with a blank line, and each line is field: value. Four fields exist.
| Field | Meaning |
|---|---|
data | the payload of the event. Several data lines in one block are joined with newlines |
event | a name for the event type. Without one, the browser delivers it as a plain message |
id | an identifier the browser remembers and sends back after a reconnection, in the Last-Event-ID header |
retry | how many milliseconds the browser should wait before it reconnects |
A line that starts with a colon is a comment. Servers send comments every so often as a keep-alive, so that idle connections are not closed by a proxy. The format comes from the WHATWG HTML standard, and the browser rules are described in the MDN page on using server-sent events.
The script below is a small score server. It reads Last-Event-ID from the request, so it knows where to resume. It sends one ball every 200 ms, numbered from that point, and ends the response after the last ball.
import http from 'node:http'; const feed = [ { over: '18.1', text: 'single' }, { over: '18.2', text: 'FOUR' }, { over: '18.3', text: 'dot ball' }, { over: '18.4', text: 'SIX' }, { over: '18.5', text: 'wide' }, { over: '18.6', text: 'WICKET' }, ]; http.createServer((req, res) => { const last = Number(req.headers['last-event-id'] ?? 0); res.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-cache', }); res.write('retry: 1000\n\n'); let id = last; const timer = setInterval(() => { if (id >= feed.length) { clearInterval(timer); return res.end(); } const data = JSON.stringify(feed[id++]); res.write(`id: ${id}\nevent: ball\ndata: ${data}\n\n`); }, 200); req.on('close', () => clearInterval(timer)); }).listen(55628, '127.0.0.1');
Looking at the raw stream
With the server running, curl -N keeps the connection open and prints whatever arrives (-N turns off its buffering).
retry: 1000 id: 1 event: ball data: {"over":"18.1","text":"single"} id: 2 event: ball data: {"over":"18.2","text":"FOUR"} id: 3 event: ball data: {"over":"18.3","text":"dot ball"} id: 4 event: ball data: {"over":"18.4","text":"SIX"} id: 5 event: ball data: {"over":"18.5","text":"wide"} id: 6 event: ball data: {"over":"18.6","text":"WICKET"}
curl -N output, the whole stream.
The first block carries only retry: 1000, which tells a browser to wait one second before it reconnects. Then six events follow, each with an id, an event name and a data line holding JSON. Nothing about this needs a library. It is text written to a response that stays open.
Two header details matter in production. Cache-Control: no-cache stops anything on the way from storing the stream. Some reverse proxies also buffer a response until it is large, which delays every event. Check your proxy's buffering setting for event streams before you blame your code. MDN's example for nginx sets a response header, X-Accel-Buffering: no, to turn buffering off for that one response.
One more limit comes from browsers. Over HTTP/1.1 a browser opens at most six connections to one site, and each SSE stream uses up one. A user with several tabs open to the same site can run out. HTTP/2 raises the limit by carrying many streams on one connection, so serving over HTTP/2 is the usual fix.
Reading a stream, and resuming after a break
Node 24 has no EventSource enabled by default. It exists behind the --experimental-eventsource flag and is marked experimental. The script that follows does the job with fetch, which also shows what EventSource does for a browser. It reads the body as text, splits it at blank lines, parses the fields, and yields events.
async function* readEvents(url, lastId) { const headers = lastId ? { 'last-event-id': lastId } : {}; const res = await fetch(url, { headers }); let buffer = ''; const text = res.body.pipeThrough(new TextDecoderStream()); for await (const chunk of text) { buffer += chunk; let end; while ((end = buffer.indexOf('\n\n')) !== -1) { const block = buffer.slice(0, end); buffer = buffer.slice(end + 2); const ev = {}; for (const line of block.split('\n')) { const i = line.indexOf(':'); if (i > 0) ev[line.slice(0, i)] = line.slice(i + 1).trim(); } if (ev.data) yield ev; } } }
The reader, the first part of l2-sse-client.mjs.
The second half uses it. It reads three events, stops, which closes the connection, and then reconnects with Last-Event-ID set to the last id it saw.
let lastId; for await (const ev of readEvents('http://127.0.0.1:55628/')) { console.log('first connection:', ev.id, JSON.parse(ev.data).text); lastId = ev.id; if (ev.id === '3') break; } console.log('connection dropped after id', lastId); for await (const ev of readEvents('http://127.0.0.1:55628/', lastId)) { console.log('after reconnect:', ev.id, JSON.parse(ev.data).text); }
The second part.
first connection: 1 single first connection: 2 FOUR first connection: 3 dot ball connection dropped after id 3 after reconnect: 4 SIX after reconnect: 5 wide after reconnect: 6 WICKET
The first connection delivered events 1 to 3, then the client dropped it. The second connection sent Last-Event-ID: 3, and the server resumed at event 4. Nothing was lost and nothing repeated. This is the reason for the id field: the browser does this reconnection by itself, and the server's only job is to honour the header.
Two rules of the standard shape how you end a stream. A browser reconnects whenever the connection closes, even when the server closed it on purpose, so the score server above would be asked for event 6 again after one second, and again after that. To tell the browser to stop, answer the next request with 204 No Content, or call close() on the EventSource. The other rule works against you: if the response status is not 200, or the Content-Type is not text/event-stream, the browser fails the connection and does not retry. Check both before you debug the reconnect code.
Part 3 · WebSockets with the ws library
The upgrade handshake
Chat, shared whiteboards and multiplayer games need the client to send as often as it receives. A WebSocket gives both sides a channel that stays open.
A WebSocket connection begins as an HTTP/1.1 request that asks to change protocol. The client sends a GET with Upgrade: websocket, Connection: Upgrade, a random Sec-WebSocket-Key and Sec-WebSocket-Version: 13. A server that agrees answers 101 Switching Protocols and a Sec-WebSocket-Accept header. That header proves the server understood: it is the key joined to a fixed GUID from the standard (RFC 6455), hashed with SHA-1 and encoded in base64. After the 101 reply the same TCP connection stops speaking HTTP and carries WebSocket frames in both directions.
Node has no WebSocket server built in. The ws package is the one most programs use. The script below runs a ws server, then connects to it by hand with a plain TCP socket and sends the upgrade request. It uses the sample key from the RFC, and computes the expected answer itself.
import net from 'node:net'; import crypto from 'node:crypto'; import { WebSocketServer } from 'ws'; const wss = new WebSocketServer({ port: 55629, host: '127.0.0.1' }); const key = 'dGhlIHNhbXBsZSBub25jZQ=='; const GUID = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'; const socket = net.connect(55629, '127.0.0.1', () => { socket.write([ 'GET /live HTTP/1.1', 'Host: 127.0.0.1:55629', 'Upgrade: websocket', 'Connection: Upgrade', `Sec-WebSocket-Key: ${key}`, 'Sec-WebSocket-Version: 13', '', '', ].join('\r\n')); }); socket.once('data', (data) => { console.log(data.toString().replaceAll('\r', '').trim()); const accept = crypto.createHash('sha1').update(key + GUID) .digest('base64'); console.log('\ncomputed accept:', accept); socket.destroy(); wss.close(); });
HTTP/1.1 101 Switching Protocols Upgrade: websocket Connection: Upgrade Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo= computed accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
The response has CRLF line ends on the wire. Shown with LF.
The server answered 101, and the accept value it sent matches the one computed from the key and the GUID. The accept value shows the client that the server read this very handshake and understands the protocol. The random key works the other way: the standard says it helps a WebSocket server refuse ordinary HTTP clients that are being abused to send it data.
Frames, ping and pong
Watch for the HTTP request turning into a two-way connection
Read it as steps
A WebSocket starts as an HTTP upgrade, carries messages in both directions, and ends with a close handshake.
Messages travel in frames. A frame is either a data frame, carrying text or binary, or a control frame. The three control frames are close, ping and pong. A peer that receives a ping must answer with a pong, and ws does that by itself. Frames sent by a client are masked with a random key, a rule in the standard that protects intermediaries from confusion. You never handle masking yourself.
Closing is a short exchange of its own. One side sends a close frame, the other answers, and then the TCP connection ends. A connection that disappears without it, for example when a phone loses signal, is the case the heartbeat lesson handles.
A broadcast server and Node's own client
The script is a minimal chat room. The server passes every message it receives to all other connected clients. The three clients are made with the global WebSocket that Node 22 and later provides, which has the browser API: addEventListener, send and close. It was marked stable in Node 22.4.0.
import { WebSocketServer, WebSocket } from 'ws'; const wss = new WebSocketServer({ port: 55629, host: '127.0.0.1' }); wss.on('connection', (socket) => { socket.on('message', (data, isBinary) => { for (const peer of wss.clients) { if (peer !== socket && peer.readyState === WebSocket.OPEN) { peer.send(data, { binary: isBinary }); } } }); }); const connect = (name) => new Promise((resolve) => { const ws = new globalThis.WebSocket('ws://127.0.0.1:55629/'); ws.addEventListener('open', () => resolve(ws)); ws.addEventListener('message', (e) => { console.log(name, 'received:', e.data); }); }); const asha = await connect('asha'); const ravi = await connect('ravi'); const meena = await connect('meena'); console.log('clients on the server:', wss.clients.size); asha.send('SIX! 120 for 3'); await new Promise((r) => setTimeout(r, 200)); for (const ws of [asha, ravi, meena]) ws.close(); wss.close();
clients on the server: 3 ravi received: SIX! 120 for 3 meena received: SIX! 120 for 3
Asha's message reached Ravi and Meena, and not Asha, because the server skips the sender. wss.clients is the set of open connections. The check on readyState guards against a client that is closing, since sending on a closed socket is an error.
Three habits belong in every real WebSocket server, none of which this toy has. Limit the size of a message (maxPayload in ws), because a client could send a gigabyte. Check the Origin header when a browser connects, so that a page from another site cannot use your server on behalf of a visitor. And treat every message as untrusted input: parse it inside a try, and validate the shape before you act on it.
What proves to a client that the server understood the upgrade request?
- The
Sec-WebSocket-Acceptheader: the base64 of the SHA-1 hash of the client's key joined with the fixed GUID from RFC 6455.
Part 4 · Keeping connections healthy
Connections die quietly
A WebSocket server may hold ten thousand connections, and some of them are already dead.
A connection can end without a close frame. A phone that moves out of coverage, a computer that sleeps or a cable that comes out sends nothing. The server's socket looks open for minutes or hours, because TCP only notices when it tries to send and gets no answer. Meanwhile your program holds the memory and the entry in its list of clients. Proxies and load balancers add a second problem: they close connections that carry no traffic for a while.
The remedy is a heartbeat. Every few seconds the server sends a ping. The peer answers with a pong, which the library does by itself. If a ping goes unanswered by the next round, the server terminates the connection. The pings also count as traffic, so idle connections are not cut by a proxy. The script uses two clients: one normal, and one created with autoPong: false, which never answers. This stands in for a peer that has gone silent.
import { WebSocketServer, WebSocket } from 'ws'; import { setTimeout as sleep } from 'node:timers/promises'; const wss = new WebSocketServer({ port: 55629, host: '127.0.0.1' }); let nextId = 1; wss.on('connection', (socket) => { socket.id = nextId++; socket.isAlive = true; socket.on('pong', () => { socket.isAlive = true; }); socket.on('close', () => console.log('server: client', socket.id, 'closed')); }); const beat = setInterval(() => { for (const socket of wss.clients) { if (!socket.isAlive) { console.log('server: no pong from client', socket.id, '- terminating'); socket.terminate(); continue; } socket.isAlive = false; socket.ping(); } }, 300);
The server side of l4-heartbeat.mjs.
Running the heartbeat
const open = (opts) => new Promise((resolve) => { const ws = new WebSocket('ws://127.0.0.1:55629/', opts); ws.on('open', () => resolve(ws)); ws.on('error', () => {}); }); const healthy = await open({}); const frozen = await open({ autoPong: false }); await sleep(1100); console.log('healthy client state:', healthy.readyState === 1 ? 'open' : 'closed', ' frozen client state:', frozen.readyState === 1 ? 'open' : 'closed'); clearInterval(beat); healthy.close(); wss.close();
The clients and the check.
server: no pong from client 2 - terminating server: client 2 closed healthy client state: open frozen client state: closed server: client 1 closed
The ping interval is 300 ms to keep the demonstration short.
Each round, the server marks every client as not alive and pings it. A pong sets the flag again. At the next round a client still marked not alive is terminated. terminate() destroys the socket at once, while close() starts the polite exchange, which a dead peer would never finish. The silent client 2 was removed on the second round, and the normal one stayed.
Real intervals are tens of seconds, not milliseconds. Pick one below the idle timeout of your proxies, and allow one missed pong before you give up. Clients should also reconnect on their own with a growing delay and a little randomness, so that ten thousand of them do not all return in the same second after a restart.
Slow clients and bufferedAmount
A client can also be alive and slow. If you send faster than it reads, the data waits in your process. socket.bufferedAmount reports the number of bytes passed to send() that have not yet been written to the network. It grows when the client cannot keep up. Left alone, it grows until your process runs out of memory, and one slow phone can take down a server that serves thousands.
The script sends a 1 MB frame every 20 ms to a client that completes the handshake and then never reads. It checks bufferedAmount before each send and drops the client when more than 8 MB is waiting.
import net from 'node:net'; import { WebSocketServer } from 'ws'; const wss = new WebSocketServer({ port: 55629, host: '127.0.0.1' }); const mb = (n) => (n / 1024 / 1024).toFixed(1) + ' MB'; const LIMIT = 8 * 1024 * 1024; wss.on('connection', (socket) => { const frame = Buffer.alloc(1024 * 1024, 1); let sent = 0; const timer = setInterval(() => { if (socket.bufferedAmount > LIMIT) { console.log('over 8 MB waiting, dropping this slow client'); clearInterval(timer); socket.terminate(); wss.close(); return; } socket.send(frame); sent++; if (sent % 10 === 0) { console.log('sent', sent, 'MB, buffered', mb(socket.bufferedAmount)); } }, 20); });
The server side of l4-slow.mjs.
// A client that completes the handshake and then never reads. const raw = net.connect(55629, '127.0.0.1', () => { raw.write('GET / HTTP/1.1\r\nHost: x\r\nUpgrade: websocket\r\n' + 'Connection: Upgrade\r\nSec-WebSocket-Version: 13\r\n' + 'Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n\r\n'); raw.pause(); }); raw.on('error', () => {});
The client that never reads.
sent 10 MB, buffered 8.0 MB over 8 MB waiting, dropping this slow client
The exact buffered size varies a little from run to run.
After 10 MB had been sent, 8.0 MB were still waiting in the process, so the next check dropped the client. Your limit and your reaction depend on the application. For a score feed you might skip updates for that client, since only the latest matters. For a chat you might close the connection and let the client reconnect and catch up.
What a connection costs
How many connections can one process hold? The answer depends on memory, file descriptors and what each connection does, so measure it. The server below prints its memory use whenever the connection count changes. A second process opens 1,000 idle connections and closes them again. The server runs with --expose-gc so that each reading follows a collection.
import { WebSocketServer } from 'ws'; const wss = new WebSocketServer({ port: 55629, host: '127.0.0.1' }); const mb = (n) => (n / 1024 / 1024).toFixed(1); let lastCount = -1; setInterval(() => { global.gc(); const n = wss.clients.size; if (n !== lastCount) { const m = process.memoryUsage(); console.log('connections', String(n).padStart(4), ' rss', mb(m.rss), 'MB heapUsed', mb(m.heapUsed), 'MB'); lastCount = n; } }, 500); setTimeout(() => process.exit(0), 9000);
The measuring server.
connections 0 rss 70.8 MB heapUsed 5.7 MB connections 1000 rss 90.5 MB heapUsed 9.1 MB connections 0 rss 90.0 MB heapUsed 6.9 MB
The server process only. Megabytes. Varies a little between runs.
Going from 0 to 1,000 idle connections added about 20 MB of rss, which is roughly 20 KB for each, of which about 3 KB was in the V8 heap. The rest sits outside the JavaScript heap, in memory that the operating system and Node use for each socket. After the clients left, the heap shrank but rss stayed near its peak, which is normal, since the process keeps memory it may need again.
Extrapolate with care. At 20 KB each, 1 lakh idle connections come to about 2 GB, and a busy connection costs more, since it holds message buffers. File descriptor limits and CPU time for heartbeats count as well. Use a number like this to plan, then confirm it with a load test on the real code, as the profiling chapter describes.
Why does a server need its own ping, when TCP has keep-alives?
- A ping is sent by your program on a short timer that you choose, passes through proxies as ordinary traffic, and proves that the program on the other end still works. TCP keep-alives run on long timers and only show that the other operating system answers.
bufferedAmount keeps growing for one client. What is happening and what do you do?
Part 5 · More than one process: fan-out, pub/sub and sticky sessions
The problem with a second instance
One Node process can hold thousands of connections, but one process is also one machine's worth of failure. Run two, and a new question appears.
Each process knows only its own connections. If Asha is connected to instance 1 and Ravi to instance 2, a message from Asha reaches only the clients of instance 1. The two instances share nothing in memory. The cluster lesson in the advanced topics chapter explained why: a cluster is made of separate processes, and so is every extra machine behind a load balancer.
The usual answer is a publish and subscribe bus between instances. When an instance receives something worth broadcasting, it publishes it to the bus. Every instance is subscribed, so each receives the message and sends it on to its own connected clients. The instance does not need to know where the other clients are. Redis offers this through its PUBLISH and SUBSCRIBE commands, and message brokers do the same. The scene shows an update that fans out to phones on two instances.
Watch for one update reaching phones on both instances
Read it as steps
A bus between two cluster workers
The script is a small model of this with no Redis. A primary process starts two workers, and each worker runs a ws server on its own port. The primary plays the bus: it relays any message that one worker publishes to the other. Two clients, one for each worker, then talk through it.
import cluster from 'node:cluster'; import { WebSocketServer, WebSocket } from 'ws'; import { once } from 'node:events'; if (cluster.isPrimary) { const ports = [55627, 55628]; const workers = ports.map((port) => cluster.fork({ PORT: port })); await Promise.all(workers.map((w) => once(w, 'message'))); // The bus: whatever one worker publishes, the others receive. for (const from of workers) { from.on('message', (msg) => { if (msg.type !== 'publish') return; for (const to of workers) if (to !== from) to.send(msg); }); } const open = (port, name) => new Promise((resolve) => { const ws = new WebSocket(`ws://127.0.0.1:${port}/`); ws.on('message', (d) => console.log(name, 'got:', d.toString())); ws.on('open', () => resolve(ws)); }); const asha = await open(ports[0], 'asha on worker 1'); const ravi = await open(ports[1], 'ravi on worker 2'); asha.send('wicket at 18.6'); await new Promise((r) => setTimeout(r, 300)); asha.close(); ravi.close(); for (const w of workers) w.kill();
The primary: workers, bus and test clients.
} else { const wss = new WebSocketServer({ port: Number(process.env.PORT), host: '127.0.0.1' }); const deliver = (text) => { for (const c of wss.clients) c.send(text); }; wss.on('connection', (socket) => { socket.on('message', (data) => { deliver(data.toString()); process.send({ type: 'publish', text: data.toString() }); }); }); process.on('message', (msg) => deliver(msg.text)); wss.on('listening', () => process.send({ type: 'ready' })); }
The worker: a ws server and the two directions of the bus.
asha on worker 1 got: wicket at 18.6 ravi on worker 2 got: wicket at 18.6
Asha sent her message to worker 1. That worker delivered it to its own clients and published it to the primary, which sent it to worker 2. Worker 2 delivered it to Ravi. Her own socket got it through the local delivery. Swap the primary for a Redis channel and the worker code stays nearly the same: publish on receive, and deliver whatever arrives from the subscription.
Sticky sessions and Socket.IO
A load balancer decides which instance receives each new connection. For a plain WebSocket that is a single decision at the upgrade, and after it the connection stays on that instance for as long as it lives. No special setup is needed. For some protocols, a client sends several HTTP requests that belong together. They must all reach the same instance, which is what sticky sessions (also called session affinity) provide, by choosing the instance from a cookie or from the client address.
Socket.IO is a library that adds rooms, automatic reconnection and fallbacks on top of WebSocket and plain HTTP. It runs its own protocol, so a Socket.IO server needs a Socket.IO client, and it needs sticky sessions when it falls back to long polling. For plain ws, you build the features you need. With Socket.IO you gain them at the cost of a heavier stack. Choose by whether you need its features, not by habit.
To close the chapter, here are three points to keep. A connection costs tens of kilobytes of memory. Heartbeats and limits on buffering keep the dead and the slow from taking your server down. And once you run two instances, you need a bus, and clients that can resume from the last message they saw.
| Term | Meaning |
|---|---|
| SSE | a one-way stream of text events over a single long HTTP response |
| WebSocket | a two-way message channel created by upgrading an HTTP connection |
| Heartbeat | regular ping and pong frames that reveal dead connections |
| Pub/sub | publishers send to a bus, and every subscriber receives the message |
| Sticky session | routing a client to the same instance every time |
Asha is connected to instance 1 and Ravi to instance 2. What is needed for Asha's message to reach Ravi?
All chapters · Previous: Caching and Background Jobs in Node Services