REST API Real-Time WebSockets and SSE
Standard REST follows a simple pattern: the client asks, and the server answers. Some features need the server to speak first. Chat messages, live scores, delivery tracking, and stock tickers all depend on instant updates. Several techniques add real-time behavior to an API.
The Phone Line Picture
Sending letters resembles normal REST. Each letter needs an address, and each reply needs another letter. A phone call keeps a line open, and both sides speak whenever they want. Real-time technologies move an API from letters toward phone calls.
Four Techniques Compared
Polling Client: "news?" ... "news?" ... "news?" (repeated asking) Long polling Client: "news?" ......(server waits)...... "here" SSE Client opens one stream ←← news ←← news ←← (server pushes) WebSocket Client ←→ Server both sides send freely
Polling
The client asks on a timer, such as every 10 seconds. Polling works everywhere and takes minutes to build. It wastes requests when nothing changes and delays updates by up to one interval. Use it for low-frequency data.
Long Polling
The client sends a request, and the server holds it open until news arrives or a time limit passes. The client reconnects immediately after each answer. Updates arrive faster than plain polling, and the server carries many waiting connections.
Server-Sent Events
Server-Sent Events, or SSE, keep one HTTP connection open and let the server stream messages to the client. Data flows in one direction only. Browsers include a built-in EventSource object that reconnects automatically.
GET /orders/77/updates
Accept: text/event-stream
HTTP/1.1 200 OK
Content-Type: text/event-stream
event: status
data: {"orderId":"77","status":"packed"}
event: status
data: {"orderId":"77","status":"shipped"}
const stream = new EventSource("/orders/77/updates");
stream.addEventListener("status", function (event) {
console.log(JSON.parse(event.data));
});
SSE fits live dashboards, progress bars, notifications, and news feeds.
WebSockets
A WebSocket starts as an HTTP request and upgrades into a persistent two-way channel. Both sides send messages at any time with very little overhead.
Client ── GET /chat Upgrade: websocket ──→ Server Client ←── 101 Switching Protocols ─────── Server Client ←→ messages in both directions ←→ Server
WebSockets suit chat, multiplayer games, collaborative editing, and trading screens.
Choosing a Technique
| Need | Best Fit |
|---|---|
| Update every few minutes | Polling |
| Server updates only, in one direction | SSE |
| Frequent two-way messages | WebSocket |
| Server to server events | Webhooks |
Working Beside REST
Real-time channels rarely replace REST. Apps load initial data with a REST call, then subscribe to a stream for changes. REST remains the source of truth for creating and updating resources.
1. GET /orders/77 → current state 2. open stream for order 77 → live changes 3. POST /orders/77/cancellation → actions stay REST
Authentication
Browsers cannot attach custom headers to a WebSocket handshake or an EventSource request. Common solutions include a short-lived ticket in the connection URL, a secure cookie, or a token sent as the first message. Verify the token before sending data, and close the connection when it expires.
Reliability Tips
- Give each message an increasing id, so a returning client can ask for everything after the last id it saw.
- Send periodic heartbeat messages to detect dead connections.
- Reconnect with growing delays and random jitter.
- Limit connections per user to protect server memory.
Scaling Considerations
Open connections consume memory on specific servers. A load balancer must keep a client on one server, and a message broker must share events across servers, so every user receives the update no matter which server holds their connection.
Common Mistakes
WebSockets for Everything
Simple one-way updates run cheaper and simpler on SSE. Match the tool to the need.
No Recovery Plan
Mobile networks drop connections constantly. Plan for reconnects and missed messages.
Skipping Authorization on Subscriptions
A client that subscribes to order 77 must own order 77. Check access on every subscription.
