REST vs WebSocket¶
1. Decision¶
Choose REST (HTTP Request-Response) for standard stateless, unidirectional client-initiated CRUD operations; choose WebSocket for full-duplex, bidirectional, low-latency, persistent real-time communication (e.g., chat, collaborative editing, live trading, multiplayer gaming).
2. 30-Second Answer¶
REST operates on a stateless, short-lived HTTP request-response model where the client must initiate every interaction. It leverages standard HTTP infrastructure (CDNs, firewalls, load balancers), making it simple, scalable, and easy to secure. However, REST cannot push data from server to client without inefficient polling. WebSocket establishes a persistent, full-duplex, bidirectional TCP connection initiated via an HTTP Upgrade handshake (ws:// or wss://). Once established, both client and server can send lightweight framed data messages instantly (\(<5\text{ms}\) latency) over a single open socket with minimal header overhead (2-10 bytes vs 1KB HTTP headers). WebSockets trade stateless scaling for persistent server memory connections.
3. Decision Matrix¶
| Option | Best For | Avoid When | Latency | Scalability | Consistency | Operational Complexity |
|---|---|---|---|---|---|---|
| REST (HTTP / JSON) | Standard web APIs, CRUD applications, file uploads, stateless microservices | Real-time push updates, sub-second live streaming, interactive chat, collaborative whiteboards | Medium (30-200ms per request RTT + TCP/TLS handshake) | Extremely High (Stateless horizontal scaling behind standard load balancers) | Immediate per request | Low |
WebSocket (ws:// / wss://) |
Instant messenger chat, live financial tickers, collaborative editing (Figma), multiplayer games | Simple CRUD forms, rare batch data updates, static content distribution | Ultra-Low (<5ms frame transmission) | Medium to High (Stateful persistent TCP socket scaling; requires Pub/Sub backplane) | Real-time push synchronization | High (Connection state, reconnects, heartbeat, Pub/Sub cluster) |
4. Selection Rules¶
| Requirement | Best Choice | Rationale / Example |
|---|---|---|
| Standard Unidirectional CRUD Operations | REST | Web app fetching user profile, submitting an order, or querying search |
| Bidirectional Real-Time Communication | WebSocket | Live chat app where user sends message and receives incoming messages instantly |
| Low Network Overhead for Frequent Messages | WebSocket | 2-10 byte framing overhead vs 1KB+ HTTP headers per request |
| Edge CDN Caching & Horizontal Scaling | REST | Standard HTTP GET responses cached at global CDN edge PoPs |
| Collaborative Real-Time State (Operational Transform) | WebSocket | Multiple users editing the same canvas (Figma) or document simultaneously |
| Server-to-Client Unidirectional News Stream | SSE (Server-Sent Events) | Choose SSE over WebSocket if communication is strictly server-to-client push |
5. Tradeoffs¶
- Persistent Full-Duplex Connection vs Stateless Request-Response
- Gain (WebSocket): Microsecond server-push latency; zero client polling overhead.
- Lose (WebSocket): Server maintains persistent TCP state; memory bounded by open socket file descriptors.
- Minimal Framing Overhead vs HTTP Header Verbosity
- Gain (WebSocket): Small 2 to 10-byte binary frame header per message.
- Lose (WebSocket): Lacks standard HTTP status codes, verbs, caching headers, or content negotiation.
- Complex Connection State vs Simple Horizontal Autoscaling
- Gain (REST): Spin up/down stateless app containers behind round-robin load balancers cleanly.
- Lose (WebSocket): Requires sticky sessions, graceful connection draining, and a Redis Pub/Sub cluster backplane to route messages across nodes.
- Custom Application Protocol vs Standardized REST Tooling
- Gain (WebSocket): Flexibility to design custom JSON/Protobuf frame protocols.
- Lose (WebSocket): Loss of standard REST API tooling, OpenAPI documentation, and cURL debugging.
- Firewall & Proxy Traversal
- Gain (REST): Native HTTP/S traverses all corporate proxies and firewalls without issue.
- Lose (WebSocket): Strict enterprise proxies may block HTTP Upgrade headers or terminate long-lived WS connections.
6. Interview Counter Questions¶
- How does the WebSocket HTTP Upgrade Handshake (
101 Switching Protocols) work under the hood? - How do you scale a WebSocket architecture horizontally across 50 server instances (Redis Pub/Sub backplane)?
- What is the difference between WebSocket frame overhead and HTTP/1.1 request header overhead?
- How do you handle Heartbeats (Ping/Pong frames) and stale connection cleanup in WebSockets?
- How do you implement authentication for WebSocket connections (JWT during handshake vs in-frame auth)?
- What happens to open WebSocket connections during a rolling software deployment?
- How do you handle graceful reconnection and message ordering on mobile clients during network drops?
- When should you choose Server-Sent Events (SSE) instead of WebSockets?
- How does AWS API Gateway manage serverless WebSocket connections?
- What security vulnerabilities unique to WebSockets exist (CSWSH - Cross-Site WebSocket Hijacking)?
7. Gold Standard Answers¶
- Client sends HTTP GET with headers
Upgrade: websocketandConnection: UpgradeplusSec-WebSocket-Key. Server validates key, hashes it with magic string, and returns101 Switching ProtocolswithSec-WebSocket-Accept, upgrading the TCP socket. - Server nodes cannot route messages to clients connected to other nodes directly. Use a Redis Pub/Sub or Kafka message backplane: Node A receives a message, publishes to Redis, and all nodes consume and broadcast to their local matching WS connections.
- HTTP/1.1 sends 500B–2KB of headers (cookies, user-agent) per request. WebSocket sends an initial HTTP handshake once, then transmits data in tiny 2 to 10-byte binary frames, saving massive bandwidth.
- Client/server periodically sends WebSocket
Pingframes (opcode0x9). The peer must respond withPong(0xA). If no Pong arrives within a heartbeat interval (e.g., 30s), the server terminates the dead TCP socket to free file descriptors. - Pass JWT token as a URL query parameter or
Sec-WebSocket-Protocolheader during the initial HTTP handshake. Alternatively, establish an unauthenticated WS connection and require the first frame payload to contain{"type": "AUTH", "token": "..."}. - Issue a graceful shutdown signal: Send a WS Close frame (
opcode 0x8), wait for active clients to reconnect to new container instances using exponential backoff with jitter, then terminate old containers. - Mobile clients buffer un-acknowledged messages locally with sequence numbers. Upon reconnect, client sends last received
sequence_id, and server replays missed messages from a Redis Stream buffer. - Choose SSE when communication is strictly unidirectional from server to client (e.g., live sports scores, stock tickers). SSE runs over standard HTTP, supports automatic reconnects natively, and traverses corporate proxies easily.
- AWS API Gateway manages persistent WebSocket connections externally, storing connection IDs. When a client sends a message, API Gateway triggers an ephemeral Lambda function, passing the
connectionIdto post responses back. - CSWSH occurs because browsers include cookies during the initial HTTP Upgrade handshake. Prevent CSWSH by validating the
Originheader during handshake and requiring explicit CSRF tokens or short-lived auth tickets in URL params.
8. Common Mistakes¶
- Using WebSockets for basic CRUD operations where simple HTTP REST calls would suffice.
- Deploying horizontally scaled WebSocket nodes without a Redis Pub/Sub backplane, causing messages to disappear.
- Forgetting Ping/Pong heartbeats, leaving thousands of dead "zombie" TCP sockets hanging in server memory.
- Terminating WebSocket server instances abruptly during deployments without graceful connection draining.
- Relying on long-lived WebSocket connections over unstable mobile networks without client reconnection buffers.
9. Keywords¶
REST, WebSocket, HTTP Upgrade Handshake, 101 Switching Protocols, Full-Duplex, Bidirectional, Heartbeat, Ping/Pong, Redis Pub/Sub Backplane, Stateful Socket, File Descriptors, Graceful Draining, CSWSH, AWS API Gateway WebSocket.
10. Cheat Sheet¶
- Core Difference: REST = Unidirectional, stateless HTTP request-response (CRUD); WebSocket = Bidirectional, persistent full-duplex TCP socket (Real-time).
- Handshake: HTTP GET \(\rightarrow\)
Upgrade: websocket\(\rightarrow\) Server returnsHTTP 101 Switching Protocols. - Scaling Rule: Must use a Pub/Sub Backplane (Redis Pub/Sub / Kafka) to broadcast messages across multi-instance WS server clusters.
- Overhead: WS uses 2–10 byte frame headers vs 1KB+ HTTP headers per message.
- Connection Health: Implement Ping/Pong Heartbeats (e.g., 30s) to clean up zombie TCP sockets and free OS file descriptors.
- Security: Always validate
Originheader during WS handshake to prevent Cross-Site WebSocket Hijacking (CSWSH).