When you need the server to “push” data to the client (beyond plain request–response), you have a spectrum of approaches—from simple polling to full-duplex streams. Below is an in-depth look at the main patterns, their mechanics, trade-offs, and best practices.
1. High-Level Categories
Pull-Based
• Request–Response (short polling)
• Long polling
Push-Based (unidirectional)
• Server-Sent Events (SSE)
• HTTP/2 Server Push
• Client issues periodic HTTP requests (GET/POST).
• Simple, works everywhere, scales with stateless servers + CDNs.
• Trade-offs:
– Latency = poll interval (e.g. 5s)
– Unnecessary requests when idle
• Tips: vary poll interval based on activity; use ETag/If-None-Match to reduce payloads.
3.2 Long Polling
Client sends HTTP GET → server holds request open until an event or timeout (e.g. 30s).
On event, server responds; client re-opens immediately.
If timeout hits with no event, server returns empty and client reconnects.
• Pros: near real-time without WebSockets.
• Cons: each reconnection costs a new HTTP handshake; care for timeouts/retries.
• Best practices:
– Use jittered reconnects to avoid thundering herd.
– Monitor open-file limits (connections) on your servers.
3.3 Server-Sent Events (SSE)
• Uses text/event-stream over a single HTTP connection.
• Unidirectional: server → client
• Features: automatic reconnection, last‐event‐ID header for resume, event typing.
• Pros: lightweight, built-in reconnection, works with simple proxies.
• Cons: no binary, one-way only, limited IE support (polyfills exist).
• Key headers:
– Cache-Control: no-cache
– Connection: keep-alive
• Example (JavaScript):
js
const evtSrc = new EventSource('/stream');
evtSrc.onmessage = e => console.log('data', e.data);
evtSrc.onerror = e => console.error('SSE error', e);
3.4 HTTP/2 Server Push
• Server “pushes” additional resources (CSS, JS) in response to a request.
• Not for arbitrary event streams—mostly preloading assets.
• Requires HTTP/2; must coordinate with client cache (avoid duplicates).
• Use cases: critical-path asset prefetching.
3.5 WebSocket
• Full-duplex TCP socket, upgraded from HTTP(S).
• Low-latency, framing for text & binary payloads.
• Pros: true bidirectional comms, subprotocol support (e.g. STOMP).
• Cons: sticky-session or routing via an external pub/sub; more complex ops.
• Lifecycle:
Client: GET /ws with Upgrade: websocket
Server: 101 Switching Protocols
Both sides send/receive frames.
• Best practices:
– Implement ping/pong heartbeats.
– Handle reconnect with exponential backoff.
– Use a message broker or Redis pub/sub to fan-out in a clustered setup.
Fallback Strategies
• If WebSocket fails, fallback to SSE or long polling
• Libraries like Socket.io and SignalR automate this “best-effort” approach
5. Choosing the Right Pattern
Simple updates every N seconds → Short polling
Near real-time with broad browser support → Long polling or SSE
Lightweight one-way event stream → SSE
Full duplex, arbitrary messages → WebSocket or gRPC bidi-stream
IoT / constrained devices → MQTT
Preloading static resources → HTTP/2 Server Push
🚀 Ready to pick your design? Let me know your specific use case (browser vs. mobile vs. IoT, scale targets, language stack) and I can sketch out a sample architecture and code snippets!