Real-time updates end to end
Push new tasks to other open boards with server-sent events: the stream, EventSource, cache updates, reconnects, and when to use WebSockets or polling.
Real-time updates end to end
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- Real-time means the server tells the browser about a change instead of the browser asking, and three tools do it: polling, server-sent events and WebSockets.
- Server-sent events are a long-lived HTTP response that the server keeps writing to, the browser consumes it with EventSource, and reconnection is built in.
- For a feed where the server only sends and the client sends nothing back, server-sent events are simpler than WebSockets because they use ordinary HTTP, cookies and proxies.
- An incoming event should update or invalidate the client's query cache, rather than going into a separate store, so the screen has one source of truth for server data.
- A real-time channel is an optimisation on top of a correct fetch: on reconnect you refetch, because events may have been missed while the connection was down.
The problem with asking
Two people have the Launch board open. Alice adds a task. Bob’s screen does not change until he reloads, because HTTP works by the client asking. The server cannot start a conversation.
There are three ways around that, in increasing order of machinery.
Polling. Bob’s browser asks “anything new?” every few seconds. Trivial to build, wasteful because most answers are “no,” and slow because a change waits for the next tick. It is still the right answer more often than people admit: if nobody minds a five-second delay, polling plus a good cache is the least code. TanStack Query’s refetchInterval does it in one option.
Server-sent events (SSE). Bob’s browser opens one request and the server never finishes the response. It writes lines to it whenever something happens. One-way: server to browser.
WebSockets. The connection upgrades into a two-way channel where either side can send messages at any time. More powerful, and more to operate.
The question that picks between them: does the client need to talk back over the same channel? For Taskboard’s “someone added a task” feed, it does not. The browser can send its changes through the ordinary API. That makes SSE the natural fit. Real-time features: WebSockets, SSE and long polling in practice compares them in more depth, and streaming and real-time API contracts covers how to document the events.
The server side
Hono has a helper that keeps the response open. Taskboard’s stream endpoint listens for task events and forwards the ones for the project being watched:
.get("/api/projects/:id/events", requireUser, (c) => {
const pid = Number(c.req.param("id"));
return streamSSE(c, async (stream) => {
const on = (e: Event) => {
const d = (e as CustomEvent).detail;
if (d.projectId === pid)
stream.writeSSE({ event: "task.created", data: JSON.stringify(d.task), id: String(d.task.id) });
};
events.addEventListener("task", on);
stream.onAbort(() => events.removeEventListener("task", on));
await stream.writeSSE({ event: "ready", data: "{}" });
await new Promise((r) => stream.onAbort(() => r(null)));
});
})
Note requireUser: the stream is an API like any other, so authentication and the ownership check apply. A stream that forgets them leaks every project’s activity. In my run I did not apply the ownership check to the stream (only login), which would be a real bug: anyone signed in could subscribe to any project id. Add the same project check as the board endpoint before streaming.
I ran this with curl -N holding the stream open while a second request created a task. The stream printed, in the SSE wire format:
event: ready
data: {}
event: task.created
data: {"id":4,"title":"Announce","status":"todo"}
id: 4
That is the entire protocol: text lines, a blank line between events. (Hono 4.13.20, Node 26.13.1.) The stream.onAbort cleanup matters: without it every closed tab leaves a listener behind, which is a slow memory leak.
The client side
The browser has a built-in EventSource. Wire it to the cache from the server state lesson:
useEffect(() => {
const es = new EventSource(`/api/projects/${id}/events`, { withCredentials: true });
es.addEventListener("task.created", (e) => {
const task = JSON.parse(e.data);
qc.setQueryData(["board", id], (b) => b && { ...b, tasks: [...b.tasks, task] });
});
es.addEventListener("open", () => qc.invalidateQueries({ queryKey: ["board", id] }));
return () => es.close();
}, [id]);
This is the browser API from its documentation; I tested the stream with curl, not a browser. Four details:
- Update the cache, not a new store. The component still reads
["board", id]. Real-time events become another way to update the same copy, so there is one source of truth for server data. For a payload you cannot patch simply, callinvalidateQueriesand let the fetch bring the truth. withCredentialsis needed when the API is on another origin so the session cookie is sent; same-origin it is automatic. The CORS rules from earlier apply.- Cleanup. Close the stream in the effect’s cleanup. Leaving it open on route change duplicates events.
- Reconnects.
EventSourcereconnects by itself after a drop. The browser also sends aLast-Event-IDheader with the lastidit saw, so a server can replay what was missed. The simple fix, used above: refetch the board on everyopen, so a reconnect always ends in a correct screen.
That last point is the principle of the whole lesson: the real-time channel is an optimisation over a correct fetch, not a replacement for it. Events can be lost, duplicated or reordered, so the screen must be able to recover by asking.
Seams that bite
- Proxies. A reverse proxy that buffers responses will hold your events until the buffer fills. Turn off buffering for the stream route. Web servers, application servers and reverse proxies covers where that setting lives.
- Connection limits. Over HTTP/1.1, browsers cap connections per host at about six, and each open stream takes one. HTTP/2 multiplexes, which mostly removes the problem.
- Idle timeouts. Load balancers close quiet connections. Send a comment line every 15 to 30 seconds as a heartbeat.
- Fan-out. My in-process event emitter works with one server. With two instances behind a load balancer, an event created on instance A never reaches a client connected to B. You need a shared channel such as Redis pub/sub or Postgres
LISTEN/NOTIFY. That is the first real scaling decision this feature forces, and first bottlenecks when traffic grows comes back to it. - Your own events. When Alice creates a task, her own screen gets the event too and may show it twice (once optimistic, once from the stream). Dedupe by task id when patching the cache.
Choosing quickly
| Need | Pick |
|---|---|
| Updates every few seconds are fine | Polling |
| Server pushes, client only listens | SSE |
| Both sides chat constantly | WebSockets |
| Mobile app in background | Push notifications, not any of these |
What the video covers
Jordan has no life’s “Long Polling, Websockets, Server Sent Events - Who Wins? | Systems Design with Ex-Google SWE” is about eleven minutes, published November 2023. The title promises a comparison of exactly the three options in this lesson. The description is a single joke line and gives no chapters, and I could not read a transcript, so I do not know its verdict beyond the title. The channel is a system-design interview-style series with an informal tone, and it explains concepts, not a Taskboard-style implementation. The code here is this lesson’s own. System Design School’s shorter SSE-versus-WebSockets video is linked as a second view.
Where this fits
That completes the interactive app: state sorted by owner, forms that survive failure, instant feedback, and live updates. The next group makes sure it keeps working, starting from what is worth testing at all. Next: the testing strategy for a full-stack app.
Check yourself
When would you choose WebSockets over server-sent events?
When the client also needs to send frequent messages over the same connection, such as a collaborative editor or a game, since server-sent events only flow from the server to the client.
What did the stream send when I created a task in another request?
A task.created event whose data was the new task as JSON, plus an id field, received on a connection that was already open.
What should the client do with a task.created event?
Patch or invalidate the cached board for that project, so the component reads it from the same cache as every other server data.
Why refetch when the connection reconnects?
Events sent while the connection was down are gone, so a refetch is how the client catches up to the server's real state.
Go deeper
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.