Real-Time Communication Patterns
You'll learn: How to choose the right technique (polling, long-polling, WebSockets, or SSE) when building real-time features in web applications.
The Real-Time Challenge
Sometimes your app needs to know about updates immediately—think chat messages, live sports scores, or stock prices. But HTTP was designed for a "request-response" model: the browser asks, the server answers, then the connection closes. How do you keep data flowing in real-time?
Four Communication Patterns
Polling: Your browser repeatedly asks "Anything new?" every few seconds using regular fetch() requests. Simple but wasteful—like calling someone every minute to check if they've texted you.
Long-Polling: The browser asks "Anything new?" and the server holds the request open until it has news, then responds. The browser immediately asks again. More efficient than polling, but still opens/closes connections frequently.
WebSockets: A persistent, bidirectional connection. Both browser and server can send messages anytime through a single open channel. Like having an open phone line—ideal for chat apps or multiplayer games where both sides need to communicate freely.
Server-Sent Events (SSE): A persistent connection where the server pushes updates to the browser using standard HTTP. One-way communication (server → client). Perfect for news feeds, notifications, or live dashboards where only the server sends updates.
When to Use What
- Polling: Simplest option when updates are infrequent (every 30+ seconds)
- Long-polling: Backward compatibility when WebSockets aren't available
- WebSockets: Two-way real-time communication (chat, gaming, collaborative editing)
- SSE: One-way server updates (live feeds, notifications, progress bars)
Key Takeaway: Choose polling for simplicity and rare updates, WebSockets for bidirectional real-time needs, SSE for server-to-client streams, and long-polling only for legacy compatibility.