Designing a Polling vs WebSocket vs SSE System
Compare short polling, long polling, WebSockets, and Server-Sent Events for real-time data delivery — with use cases and architecture decisions.
srikanthtelkalapally888@gmail.com
Polling vs WebSocket vs SSE
Choosing the right real-time communication mechanism significantly impacts performance and complexity.
Short Polling
Client repeatedly asks server: "Any updates?"
setInterval(() => {
fetch('/api/messages/new').then(render);
}, 5000); // Every 5 seconds
Pros: Simple, works everywhere Cons: Wastes bandwidth, high latency (up to 5s), high server load
Long Polling
Server holds request open until data is available.
Client sends request
Server holds connection open (up to 30s)
When data arrives → Server responds
Client immediately sends next request
Pros: Near real-time, works through proxies/firewalls Cons: Still HTTP overhead per message, complex on server
Server-Sent Events (SSE)
One-way stream from server to client over HTTP.
// Server
res.setHeader('Content-Type', 'text/event-stream');
res.write('data: {"price": 150}\n\n');
// Client
const es = new EventSource('/prices');
es.onmessage = (e) => updatePrice(JSON.parse(e.data));
Pros: Simple, built-in reconnect, works with HTTP/2 Cons: One-direction only (server → client)
WebSocket
Full-duplex persistent connection.
HTTP Upgrade Handshake → WebSocket connection
Client ↔ Server (both directions, any time)
const ws = new WebSocket('wss://api.example.com/ws');
ws.onmessage = (e) => handleMessage(e.data);
ws.send(JSON.stringify({ type: 'chat', text: 'Hi!' }));
Pros: Bidirectional, low latency, efficient (no HTTP headers per message) Cons: Complex (load balancing sticky sessions), firewall issues
Decision Matrix
Use Case → Protocol
Live chat → WebSocket
Live sports scores → SSE
Stock price ticker → SSE
Online multiplayer game → WebSocket
Order status updates → SSE or Long Polling
Simple notifications → Long Polling
Simple data refresh → Short Polling
Scaling WebSockets
Challenge: Each WebSocket is a persistent connection
Solution:
- Sticky sessions (IP hash load balancing)
- Redis Pub/Sub to share messages across servers
- Horizontal scaling with shared message bus
Conclusion
SSE for server-push scenarios (notifications, feeds), WebSocket for bidirectional (chat, games). Avoid short polling for latency-sensitive applications.