Back
๐๏ธ
UI Sheet โ System Design
Protocols ยท Machine Coding ยท Performance ยท Storage ยท Security
๐ Real-time Communication โ Pick the Right Tool
WebSocket ๐
Full-duplex, persistent TCP connection. Both sides can send anytime.
โ
Use when: Chat, multiplayer games, live trading, collaborative editing, live sports scores
โ Avoid when: Client only reads data (no need for bidirectional), simple notifications
// Client
const ws = new WebSocket("wss://api.example.com/ws");
ws.onopen = () => ws.send(JSON.stringify({ type:"join" }));
ws.onmessage = (e) => console.log(JSON.parse(e.data));
ws.onerror = (e) => console.error(e);
ws.onclose = () => console.log("disconnected");
// Need reconnect logic + heartbeat in productionServer-Sent Events (SSE) ๐ก
One-way stream: server โ client only. Runs over plain HTTP/1.1. Auto-reconnects natively.
โ
Use when: Live feed, notifications, dashboards, progress updates
โ Limit: Client-to-server still needs regular HTTP requests
// Server sends text/event-stream
// Client
const es = new EventSource("/api/stream");
es.onmessage = (e) => console.log(e.data);
es.onerror = () => es.close();
// Named events
es.addEventListener("update", (e) => handle(e.data));
// Auto-reconnects with Last-Event-ID header ๐Long Polling ๐
Client sends request โ server holds until data is ready โ responds โ client immediately re-requests.
โ Use when: Legacy browsers, no WebSocket support, infrequent updates
โ Avoid for: High-frequency data โ creates thundering herd, high server load
async function longPoll() {
while (true) {
try {
const res = await fetch("/api/poll?since=" + lastId);
const data = await res.json();
process(data);
lastId = data.lastId;
} catch { await sleep(1000); }
}
}Short Polling โฑ๏ธ
Client sends HTTP request every N seconds regardless of whether data changed.
โ Use when: Non-critical updates, very simple implementation needed
โ Wasteful โ hits server even when no new data
// Simple but inefficient
setInterval(async () => {
const data = await fetch("/api/status").then(r => r.json());
render(data);
}, 5000);Quick Comparison Table โก
| Protocol | Direction | Latency | Auto-reconnect | Use case |
|---|---|---|---|---|
| WebSocket | Bidirectional | Very low | Manual | Chat, gaming, collab |
| SSE | ServerโClient | Low | Native โ | Notifications, feeds |
| Long Polling | ServerโClient | Medium | Manual | Legacy support |
| Short Polling | ServerโClient | High | N/A (always on) | Simple status checks |
| HTTP/2 Push | ServerโClient | Low | Manual | Proactive resource push |
| gRPC Streaming | Bidirectional | Very low | Manual | Microservices, internal APIs |
๐ HTTP Protocols
HTTP/1.1 vs HTTP/2 vs HTTP/3
HTTP/1.11 request per TCP connection (with keep-alive: 6 parallel). HOL blocking.
HTTP/2Multiplexing โ many requests on 1 TCP. Header compression. Server push. Streams.
HTTP/3QUIC (UDP-based). Faster handshake. No TCP HOL blocking. Better on lossy networks.
HTTP/2 is default for modern HTTPS sites. Fixes domain sharding anti-pattern from HTTP/1.
REST vs GraphQL vs gRPC
RESTResource-based URLs. Easy to cache. Over/under-fetching problem.
GraphQLQuery exactly what you need. Single endpoint. Great for complex UIs. Harder to cache.
gRPCBinary (protobuf). Streaming. Typed. Best for internal microservices.
tRPCType-safe APIs between TS client + server. No codegen.
Interview tip: Choose REST for simple CRUD, GraphQL when clients need flexible data shapes, gRPC for performance-critical internal services.
HTTP Caching
Cache-Control: no-storeNever cache
Cache-Control: no-cacheCache but always revalidate
Cache-Control: max-age=3600Cache for 1 hour
Cache-Control: immutableNever revalidate (use content hash in URL)
ETagServer sends hash; client sends If-None-Match; server returns 304 if unchanged
Last-ModifiedSame idea with timestamps
CDN & Edge
CDN caches static assets close to users. Edge functions run at CDN POPs.
- โStatic assets: aggressive cache (1yr) with content hash in filename
- โHTML: short cache or no-cache (needs to stay fresh)
- โAPI: CDN caching for public data, bypass for private
- โImage CDN: resize/optimize on-the-fly (Cloudinary, Imgix, Next/Image)