Communication & Data Transfer/Real-Time Protocols

WebSockets & Server-Sent Events

Full-duplex WS vs one-way SSE, handshake and framing, auth on persistent connections, and scaling connection fan-out.

3/5Overview: 35m

WebSockets — full duplex

  1. HTTP Upgrade request (Connection: Upgrade, Upgrade: websocket)
  2. 101 Switching Protocols
  3. Framed messages (text/binary), ping/pong keepalive

Use when both directions need low latency: chat, gaming, collaborative cursors, live trading UIs.

Not a drop-in REST replacement — stateful connections, different scaling model.

Server-Sent Events (SSE)

One-way server → client over HTTP:

Content-Type: text/event-stream data: {"score": 3} data: {"score": 4}

Browser EventSource auto-reconnects. Works through many HTTP proxies; simpler than WS.

Pick SSE when: feed/ticker/notifications, only server pushes, HTTP/2 multiplexing OK.

Comparison

WebSocketSSELong poll
DirectionBidirectionalServer→clientClient-initiated
ProtocolWS framesHTTP streamRepeated HTTP
Browser APIWebSocketEventSourcefetch
BinaryYesText onlyEither
Proxy friendlySometimes trickyBetterBest

Auth on persistent connections

  • Cookie on initial HTTP upgrade (WS) — CSRF considerations
  • Token in query — leaks in logs; short-lived
  • First message auth — send JWT after connect
  • mTLS — service-to-service WS

Re-auth on reconnect; handle token expiry mid-session.

Scaling WebSockets

Single server holds connections in memory → horizontal scale needs:

  • Sticky sessions (same client → same pod) — fragile
  • Pub/sub backplane (Redis, Kafka) — all nodes subscribe; local connections receive fan-out
  • Dedicated connection tier (e.g. Socket.io + Redis adapter, Ably, Pusher)

Metrics: connection count, message rate, backpressure drops, reconnect storms. Instrumentation → Observability; FD limits and pod sizing → OS + Concurrency (event loop vs thread-per-connection).

GraphQL subscriptions

Typically WebSocket with connection_init + subscribe messages. Same scaling concerns.

Operational concerns

  • Idle timeouts at LB (AWS ALB default 60s) — configure ping
  • Graceful deploy — drain connections or force reconnect
  • Message ordering — per-connection usually ordered; not global

Networking covered TLS and HTTP upgrade framing — here: application protocol choice, fan-out topology, and when WS beats SSE.

Further Reading

Hands-On Tasks (Optional)

API design drills and whiteboard exercises — protocol selection, contract design, and bulk-transfer architecture. Assumes Networking and sibling tracks on the hub page (Distributed Systems, Databases, Concurrency, LLD).

  • Pick real-time transport for three features

    Features: live sports scores, collaborative doc editing, order status on checkout page. Choose SSE, WebSocket, or polling; address reconnect and auth.

    15m