← All Concepts
Networking
WebSocket & Real-Time Communication
Persistent bidirectional communication channels between client and server for real-time features.
**WebSocket** provides full-duplex communication over a single TCP connection.
**How it works:**
1. Client sends HTTP request with Upgrade: websocket header
2. Server responds with 101 Switching Protocols
3. Both sides can now send messages anytime
4. Connection stays open until explicitly closed
**Alternatives:**
- **Server-Sent Events (SSE)**: One-way server → client. Uses HTTP. Auto-reconnects. Good for feeds, notifications.
- **Long Polling**: Client sends request, server holds until data available. Simpler but higher overhead.
- **HTTP Streaming**: Server sends chunked response. Works through proxies.
**Scaling WebSocket:**
- Challenge: connections are stateful (sticky to one server)
- Solution: Session store (Redis) maps user → server for message routing
- Use message queue (Kafka/Redis Pub/Sub) for cross-server communication
- Each server handles ~100K connections
**Common tools:** Socket.IO, ws (Node.js), AWS API Gateway WebSocket.
Common Use Cases
- Chat applications (WhatsApp, Slack)
- Real-time gaming and collaboration
- Live dashboards and stock tickers
- IoT device communication
Advantages
- +True real-time with minimal latency
- +Low overhead per message (small frame headers)
- +Bidirectional - both client and server can initiate
- +Works well for high-frequency updates
Disadvantages
- -Stateful connections are harder to scale
- -Requires sticky sessions or session store
- -Some proxies/firewalls may not support WebSocket
- -More complex than simple REST APIs