UI Sheet
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 production

Server-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 โšก

ProtocolDirectionLatencyAuto-reconnectUse case
WebSocketBidirectionalVery lowManualChat, gaming, collab
SSEServerโ†’ClientLowNative โœ…Notifications, feeds
Long PollingServerโ†’ClientMediumManualLegacy support
Short PollingServerโ†’ClientHighN/A (always on)Simple status checks
HTTP/2 PushServerโ†’ClientLowManualProactive resource push
gRPC StreamingBidirectionalVery lowManualMicroservices, 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)