Five ways to push
| Technique | Direction | How it works | Good for | Watch out for |
|---|---|---|---|---|
| Short polling | Client pulls | Ask every N seconds | Rare updates, simple dashboards | Wasted requests, up to N s delay |
| Long polling | Client pulls (held) | Server holds request until data or timeout | Fallback when WebSockets are blocked | Many hanging requests; reconnect overhead |
| SSE | Server → client | One long HTTP response streaming events | Feeds, notifications, live scores, AI token streams | One-way; text only |
| WebSocket | Both ways | HTTP upgrade to a persistent full-duplex socket | Chat, multiplayer, collaboration | Stateful servers, LB stickiness, reconnects |
| WebRTC | Peer to peer | UDP-based media/data between browsers | Voice and video calls, screen share | NAT traversal needs STUN/TURN servers |
How to decide
- Updates every few minutes? Polling is fine.
- Server → client only, text events? SSE: simple, works through proxies, auto-reconnects.
- Both directions, low latency? WebSockets.
- Audio/video between users? WebRTC, with a server (SFU) for group calls.
The hard part: stateful connection servers
HTTP servers are stateless; WebSocket servers are not. Each one holds thousands of open connections, and a message for Priya must reach the specific server where Priya is connected.
The pieces:
- Session registry: when a user connects, the gateway writes
user_id → gateway_idinto Redis with a TTL, refreshed by heartbeats. - Delivery: the message service looks up the gateway and forwards the message there (direct RPC, or a per-gateway channel on a pub/sub system).
- Offline users: no registry entry → store the message and trigger a push notification (APNs/FCM). On reconnect, the client syncs everything after its last-seen message ID.
Scaling and operating connection servers
- Capacity is about connections, not QPS. Size by memory per connection (often 10–50 KB) and file descriptors.
- Load balancing: L4 load balancers or L7 with WebSocket support. Use "least connections", not round robin.
- Deploys drain slowly: you can't restart a server with 200k connections at once without a reconnect storm. Drain gradually and make clients reconnect with jittered exponential backoff.
- Heartbeats: ping/pong every 20–30 s detects dead connections and keeps NAT mappings alive on mobile networks.
- Resume, don't replay: on reconnect the client sends its last acknowledged sequence number; the server sends only what's missing.
Common trap
Treating "delivered to the socket" as "delivered". A phone can lose the network a millisecond after the server writes. Real delivery needs a client acknowledgement with the message ID; un-acked messages are resent on reconnect, and the client deduplicates by ID.