Real-Time Features: WebSockets, SSE, and Long Polling in Practice
Choosing between WebSockets, server-sent events, and long polling, and the real problem of fanning out messages once you run more than one server.
Real-Time Features: WebSockets, SSE, and Long Polling in Practice
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- WebSockets, server-sent events, and long polling solve the same problem — getting an update to a client without the client having to ask over and over — at three different levels of complexity and capability.
- Server-sent events are a one-way channel (server to client) built on plain HTTP, and the browser's EventSource API reconnects automatically on a dropped connection — a feature you'd otherwise have to build yourself.
- Long polling works through almost any firewall or proxy because it's ordinary HTTP, which is exactly why it's still the fallback of choice when a client environment won't allow a persistent connection.
- The moment you run more than one server instance, a WebSocket or SSE connection pins a client to whichever instance it connected to, so a message produced on a different instance needs a shared pub/sub layer to reach that client at all.
The problem: the client doesn’t know when to ask
A normal HTTP request-response cycle works fine when the client is the one who knows something changed — it clicks a button, it asks, it gets an answer. Real-time features break that assumption. A chat message arrives from someone else. A price updates. A background job the user is waiting on finishes. In all of these, the server knows something happened before the client does, and the client has no way to know it should ask right now instead of in five seconds.
The crude fix is short polling: the client just asks every few seconds, “anything new?” It works, but it’s wasteful — the overwhelming majority of those requests come back with “no,” and you’re paying the cost of a full HTTP round trip (and often a database query) for nothing. Everything in this lesson is about doing better than that, and the three real options trade off complexity against capability in a specific order.
Long polling: the universal fallback
Long polling is the smallest step up from short polling: the client sends a request, and instead of answering immediately, the server holds the connection open until it actually has something to say (or a timeout passes), then responds — at which point the client immediately opens a new request and waits again. It’s still built entirely out of ordinary HTTP requests, which is its biggest practical advantage: it passes through essentially any proxy, firewall, or corporate network policy a WebSocket or a long-lived stream might get blocked by. The cost is overhead — each update still means a full request-response cycle, and a server holding many of these open connections is tying up resources (a thread, or at least a connection slot) per waiting client, the same constraint a web server normally avoids by design.
Server-sent events: one-way, and it reconnects itself
Server-sent events (SSE) are built for the common case where the data only needs to flow one direction: server to client. The client opens one HTTP connection using the browser’s EventSource API, and the server keeps it open, writing a new event down the same stream whenever one occurs — no new connection per update, unlike long polling. Because it’s a plain HTTP response rather than a protocol upgrade, it needs no special server support beyond keeping a connection open and writing to it, and EventSource reconnects automatically if the connection drops, which is a real feature, not an afterthought — building reliable reconnect-with-backoff logic yourself for a WebSocket is routine extra work that SSE gives you for free. The one hard limit: it’s one-way. If the client needs to send anything back beyond the initial request, SSE isn’t the tool.
WebSockets: full duplex, more to manage
A WebSocket starts as an HTTP request and then upgrades the connection into a persistent, bidirectional channel — either side can send a message at any time, independent of the other. This is the right choice when the client genuinely needs to talk back frequently and promptly: a chat app, a multiplayer game, a collaborative document where every keystroke from every participant needs to reach everyone else fast. It’s also the most work to run correctly: you own the reconnect logic, you own detecting a dead connection (a lost network doesn’t always announce itself — this is what ping/pong frames are for), and because it isn’t plain request-response HTTP, some infrastructure needs explicit configuration to pass it through at all.
The decision, in short: need two-way, frequent client-to-server messages? WebSocket. Need one-way server-to-client updates and want the simpler option? SSE. Need something that works absolutely everywhere, including restrictive networks, and can tolerate being less efficient? Long polling.
The part that actually breaks in production: more than one server
Here’s the problem that doesn’t show up until you’re past a single server instance, and it’s the part of this topic that trips up people who’ve only ever built the demo version. A WebSocket or an SSE connection is stateful — when a client connects, it lands on one specific server instance, and that instance holds the open connection in memory for as long as it’s alive. That’s fine as long as everything that client needs to hear about also happens to be handled by that same instance.
It falls apart the moment you have two or more instances behind a load balancer, which is the normal state of any service that’s scaled out. Say a client is connected via WebSocket to instance A. An action that should trigger a message to that client — another user posting a message, a job finishing — gets handled by instance B, because that’s the instance the load balancer happened to route that unrelated request to. Instance B has the message. It has no way to reach that client, because the open socket isn’t on B’s connection table, it’s on A’s. The message is correct and ready to send, and it still never arrives.
The fix is a shared pub/sub backplane: a layer (Redis pub/sub is the common starting point; NATS or a message broker work too) that every server instance subscribes to. When instance B needs to notify a client, it doesn’t try to find the socket itself — it publishes the message to a channel. Every instance, including A, is subscribed to that channel. A receives the message, checks whether one of its own connected clients should get it, and if so, writes it down the socket it already holds. This is the piece that turns “real-time on one server” into “real-time on a real, horizontally scaled service,” and it’s the part of this lesson’s scope that has nothing to do with WebSockets or SSE specifically — it’s an application of the same publish-subscribe pattern used for all kinds of cross-instance coordination.
Where this stops
This lesson is about choosing between these three mechanisms and making them work once you’ve scaled past one server. The protocols themselves — what a WebSocket frame actually looks like on the wire, how the HTTP upgrade handshake works, what a socket is at the operating-system level — are covered at the mechanics layer in Sockets, WebSockets, and Polling. That lesson owns the “what is this, exactly” question; this one owns “which do I pick, and how do I run it for real.”
Check yourself
If your feature only needs to push updates from the server to the client, and never the other way, why might SSE be a better default than a WebSocket?
A WebSocket gives you a full bidirectional channel, which is more capability than a one-way feed needs. SSE is simpler to implement (it's plain HTTP, no special handshake or proxy configuration), and the browser's EventSource API reconnects on its own when the connection drops, which you'd have to hand-build for a WebSocket. Reach for the bidirectional option only when the client actually needs to send frequent messages back, like chat or collaborative editing.
Why does long polling still get used despite being the least efficient of the three options?
It's implemented as a sequence of ordinary HTTP requests, which means it passes through corporate proxies, restrictive firewalls, and older infrastructure that might block or mishandle a persistent WebSocket connection or a long-lived SSE stream. When you can't guarantee the client's network allows anything else, long polling is the option that's almost certain to work, at the cost of more overhead per update.
You have two server instances behind a load balancer. A client connected via WebSocket to instance A needs to receive a message triggered by an action that happened to be handled by instance B. What goes wrong without extra work, and what fixes it?
Instance B has no way to reach that client directly — the open socket lives on instance A's connection table, not B's. Without a shared layer connecting the instances, the message never reaches the client even though the server 'had' it. The fix is a pub/sub backplane (Redis pub/sub, NATS, or similar): every instance subscribes to the relevant channels, instance B publishes the message to that channel, and instance A — subscribed to the same channel — receives it and forwards it down the socket it owns.
What's the practical cost of an open WebSocket or SSE connection sitting idle, and why does that matter for how many clients one server can hold?
Each open connection holds a file descriptor and a slice of memory on the server for as long as it's connected, even if no data is flowing. Unlike a short-lived HTTP request that releases its resources the moment it's done, a persistent connection ties them up for the connection's entire lifetime, which caps how many simultaneous clients a single instance can realistically hold and is a big part of why horizontal scaling becomes necessary at all.
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.