Module 8 — APIs

WebSockets & SSE

Real-time communication patterns. Push updates to clients without them asking.

1The Communication Analogy

💡 Simple Analogy
HTTP Polling: Kid asking "Are we there yet?" every 5 seconds.

Long Polling: Kid asks, parent waits until they have news to respond.

SSE: Radio broadcast—parent announces updates, kid just listens.

WebSockets: Phone call—both can talk anytime.

2Comparison

HTTP Polling

Client repeatedly requests at intervals

Direction: Client → Server (repeated)
Pros: Simple, works everywhere
Cons: Wasteful, high latency
Use case: Non-critical updates, legacy systems

Long Polling

Server holds request until data available

Direction: Client → Server (held open)
Pros: Lower latency than polling
Cons: Connection overhead, complex error handling
Use case: Chat before WebSockets

Server-Sent Events (SSE)

Server pushes events over HTTP

Direction: Server → Client only
Pros: Simple, auto-reconnect, works with HTTP/2
Cons: One direction only, limited browser connections
Use case: Notifications, live feeds, stock prices

WebSockets

Full-duplex persistent connection

Direction: Client ↔ Server (bi-directional)
Pros: True real-time, low latency
Cons: More complex, connection management
Use case: Chat, gaming, collaboration tools

3Quick Reference

FeaturePollingSSEWebSocket
DirectionClient→ServerServer→ClientBi-directional
ProtocolHTTPHTTPws://
ReconnectManualAutomaticManual
ComplexityLowLowHigh

4When to Use What

Stock prices, news feed
SSE
Server-to-client, auto-reconnect
Chat application
WebSocket
Bi-directional messaging needed
Collaborative editing
WebSocket
Real-time sync both ways
Notification system
SSE
Simple push, no client messages
Dashboard refresh
Polling or SSE
Depends on update frequency

5Key Takeaways

1Polling: simple but wasteful. Use for non-critical updates.
2SSE: server-to-client push. Great for notifications, feeds.
3WebSockets: bi-directional real-time. Use for chat, gaming.
4SSE is simpler than WebSockets for one-way updates.
5WebSockets have connection management overhead.
6In interviews: discuss trade-offs for the specific use case.