Why Real-Time Matters
The request-response model breaks down
The REST API Design course built APIs where the client asks and the server answers. This works for most operations: get a list of books, create a task, update a profile.
But some features need the server to push data to the client without being asked. A chat message arrives. A task is updated by another user. A deployment finishes. A stock price changes. The client needs to know immediately, not the next time it happens to ask.
The naive solution: polling
The simplest approach: the client asks every few seconds.
// Client-side polling
setInterval(async () => {
const res = await fetch("/tasks?updatedSince=" + lastCheck);
const tasks = await res.json();
if (tasks.length > 0) {
updateUI(tasks);
lastCheck = new Date().toISOString();
}
}, 3000); // Every 3 seconds This works. But it has problems. If nothing changed, the request was wasted. If 100 users are polling every 3 seconds, the server handles 2,000 empty requests per minute. If the interval is longer (30 seconds), updates feel slow. Polling trades resources for latency.
The three real-time approaches
Short polling: The client requests updates at a fixed interval. Simple. Wasteful.
Long polling: The client sends a request. The server holds it open until data is available or a timeout is reached. The client immediately reconnects. Less wasteful, but complex to implement.
Server-Sent Events (SSE): The server holds a connection open and pushes events as they happen. One-way (server to client). Built into browsers with the EventSource API. Automatic reconnection.
WebSockets: A persistent, full-duplex connection. Both sides can send messages at any time. Two-way communication. Requires a handshake upgrade from HTTP.
When to use which
Short polling: Low-frequency updates, simple clients, environments where persistent connections are not possible. Checking for new email every 60 seconds.
Long polling: When you need near-instant updates but cannot use SSE or WebSockets (legacy proxies, restrictive firewalls). Fallback for environments that do not support SSE.
SSE: Server-to-client push. Notifications, live feeds, dashboard updates, real-time logs. The server sends; the client listens. The simplest real-time solution.
WebSockets: Bidirectional communication. Chat, collaborative editing, multiplayer games, interactive features where both sides send data frequently.
This course builds all four, starting simple and progressing to complex.
Why is polling wasteful for real-time updates?