Real time communication techniques
Polling, SSE, WebSockets, gRPC, or WebRTC: what's the difference?
- All of these are real-time communication patterns: ways to get fresh data to a user without them refreshing the page.
- The easiest way to understand them is through their use cases: fetching updates, server-to-client streaming, bidirectional communication, and real-time media.
Category 1: Fetching updates
Short Polling
- Imagine tracking a food delivery order.
- Your app asks the server every few seconds, "Where has my order reached?", and the server responds with the rider's current location.
- This is Short Polling: the client repeatedly sends normal HTTP requests on a fixed interval.
setInterval(async () => {
const res = await fetch("/api/orders/42/location");
updateMap(await res.json());
}, 5000); // every 5 seconds
- Pros: simplest option, works with any server, proxy, or load balancer, and is easy to cache and scale.
- Cons: most responses may contain no change, and every request carries full HTTP headers. Updates can be up to one interval late. A shorter interval means fresher data but more load.
Long Polling
- Imagine you've submitted an image-generation request.
- With short polling, your app asks every second, "Is it ready?" and the server says "No" again and again until the image finally arrives.
- Long Polling reduces those wasted requests:
- The client sends a request.
- The server keeps the request open until the image is generated, or until a timeout (for example, 30 seconds).
- The server sends the response, completing that request.
- The client immediately sends a new request if it still needs updates.
- Pros: near-instant updates using plain HTTP.
- Cons: the server holds many open requests, and every update still requires a new request.
Category 2: Server-to-client streaming
- When you ask ChatGPT a question, the answer appears word by word as the server generates it.
- HTTP Streaming makes this possible: the server keeps one response open and sends data in chunks.
- Server-Sent Events (SSE) is a standard format for this. The server responds with
Content-Type: text/event-stream and sends messages like:
data: {"token": "Hello"}
data: {"token": " world"}
- Browsers have a built-in
EventSource API:
const events = new EventSource("/api/notifications");
events.onmessage = (event) => console.log(JSON.parse(event.data));
- Pros: one-way, server-to-client updates over plain HTTP.
EventSource reconnects automatically and can resume using the Last-Event-ID header.
- Cons: one direction only (the client sends data with separate HTTP requests), and text only, no binary.
EventSource only supports GET requests without custom headers. AI chat apps often use fetch() with a streamed response body instead, so they can send a POST body and auth headers while still reading SSE-formatted chunks.
- Over HTTP/1.1, browsers allow only about 6 connections per domain, so many SSE tabs can exhaust them. HTTP/2 removes this limit in practice.
- Good for: live scores, notifications, stock tickers, progress updates, and AI responses.
Category 3: Bidirectional communication
- Used heavily in real-time chat, multiplayer games, and collaborative editors, where both sides send messages at any time.
1. WebSockets
- The connection starts as a normal HTTP request with an
Upgrade: websocket header.
- The server replies
101 Switching Protocols, and the connection becomes a persistent, full-duplex channel (ws://, or wss:// when encrypted).
- Both the browser and server can now send text or binary messages at any time, without new HTTP requests or repeated headers.
const socket = new WebSocket("wss://chat.example.com");
socket.onopen = () => socket.send(JSON.stringify({ type: "join", room: "general" }));
socket.onmessage = (event) => renderMessage(JSON.parse(event.data));
- Things you must handle yourself: reconnection, heartbeats (ping/pong) to detect dead connections, and message ordering or delivery guarantees.
- Scaling: each server holds long-lived connections. When users in the same chat room are connected to different servers, servers share messages through a pub/sub system such as Redis.
2. gRPC Bidirectional Streaming
- gRPC runs over HTTP/2. In bidirectional streaming, the client and server independently send messages over the same RPC stream, enabling full-duplex communication.
- gRPC supports four call types: unary (one request, one response), server streaming, client streaming, and bidirectional streaming.
- It's mainly used for real-time communication between backend services, for example a delivery service streaming rider locations to a tracking service.
- Browsers can't make native gRPC calls. gRPC-Web needs a proxy and doesn't support client or bidirectional streaming, so browser apps typically use WebSockets instead.
Category 4: Real-time media
- For video calls, voice calls, and screen sharing, use WebRTC (Web Real-Time Communication).
- WebRTC can establish a direct peer-to-peer connection between users, so media doesn't have to travel through your server.
- Servers are still needed to set up the connection:
- Signaling server: exchanges connection offers and network details between users. WebRTC doesn't define how; apps often use WebSockets.
- STUN server: helps each device discover its public IP address and port behind a router (NAT).
- TURN server: relays the media when a direct connection is blocked by strict firewalls or NATs.
- WebRTC usually runs over UDP and always encrypts media. That gives low latency, which matters more than perfect delivery in a live call.
- It also has data channels for sending arbitrary peer-to-peer data, such as game state or files.
- Group calls: connecting everyone to everyone (mesh) doesn't scale beyond a few people. A media server, usually an SFU (Selective Forwarding Unit), receives each participant's stream once and forwards it to the others.
Comparison
Choosing in a system design interview
- Start with the simplest option that meets the freshness requirement. Polling every 10 seconds may be perfectly fine.
- If only the server needs to push data, prefer SSE over WebSockets: it's simpler, uses plain HTTP, and reconnects automatically.
- Use WebSockets when the client also sends frequent messages.
- Use gRPC streaming between internal services, not from the browser.
- Use WebRTC for audio and video, with TURN servers as the fallback.
- Mention scaling: long-lived connections need connection-aware load balancing, heartbeats, and a pub/sub layer to fan out messages across servers.
Summary
- Need to check for updates? → Short Polling or Long Polling.
- Need to continuously send data from server to client? → SSE (HTTP Streaming).
- Need bidirectional real-time communication? → WebSockets, or gRPC between backend services.
- Need live peer-to-peer audio or video? → WebRTC.
References