Skip to content

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

  1. Persistent Full-Duplex Connection vs Stateless Request-Response
  2. Gain (WebSocket): Microsecond server-push latency; zero client polling overhead.
  3. Lose (WebSocket): Server maintains persistent TCP state; memory bounded by open socket file descriptors.
  4. Minimal Framing Overhead vs HTTP Header Verbosity
  5. Gain (WebSocket): Small 2 to 10-byte binary frame header per message.
  6. Lose (WebSocket): Lacks standard HTTP status codes, verbs, caching headers, or content negotiation.
  7. Complex Connection State vs Simple Horizontal Autoscaling
  8. Gain (REST): Spin up/down stateless app containers behind round-robin load balancers cleanly.
  9. Lose (WebSocket): Requires sticky sessions, graceful connection draining, and a Redis Pub/Sub cluster backplane to route messages across nodes.
  10. Custom Application Protocol vs Standardized REST Tooling
  11. Gain (WebSocket): Flexibility to design custom JSON/Protobuf frame protocols.
  12. Lose (WebSocket): Loss of standard REST API tooling, OpenAPI documentation, and cURL debugging.
  13. Firewall & Proxy Traversal
  14. Gain (REST): Native HTTP/S traverses all corporate proxies and firewalls without issue.
  15. Lose (WebSocket): Strict enterprise proxies may block HTTP Upgrade headers or terminate long-lived WS connections.

6. Interview Counter Questions

  1. How does the WebSocket HTTP Upgrade Handshake (101 Switching Protocols) work under the hood?
  2. How do you scale a WebSocket architecture horizontally across 50 server instances (Redis Pub/Sub backplane)?
  3. What is the difference between WebSocket frame overhead and HTTP/1.1 request header overhead?
  4. How do you handle Heartbeats (Ping/Pong frames) and stale connection cleanup in WebSockets?
  5. How do you implement authentication for WebSocket connections (JWT during handshake vs in-frame auth)?
  6. What happens to open WebSocket connections during a rolling software deployment?
  7. How do you handle graceful reconnection and message ordering on mobile clients during network drops?
  8. When should you choose Server-Sent Events (SSE) instead of WebSockets?
  9. How does AWS API Gateway manage serverless WebSocket connections?
  10. What security vulnerabilities unique to WebSockets exist (CSWSH - Cross-Site WebSocket Hijacking)?

7. Gold Standard Answers

  1. Client sends HTTP GET with headers Upgrade: websocket and Connection: Upgrade plus Sec-WebSocket-Key. Server validates key, hashes it with magic string, and returns 101 Switching Protocols with Sec-WebSocket-Accept, upgrading the TCP socket.
  2. 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.
  3. 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.
  4. Client/server periodically sends WebSocket Ping frames (opcode 0x9). The peer must respond with Pong (0xA). If no Pong arrives within a heartbeat interval (e.g., 30s), the server terminates the dead TCP socket to free file descriptors.
  5. Pass JWT token as a URL query parameter or Sec-WebSocket-Protocol header during the initial HTTP handshake. Alternatively, establish an unauthenticated WS connection and require the first frame payload to contain {"type": "AUTH", "token": "..."}.
  6. 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.
  7. 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.
  8. 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.
  9. 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 connectionId to post responses back.
  10. CSWSH occurs because browsers include cookies during the initial HTTP Upgrade handshake. Prevent CSWSH by validating the Origin header 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 returns HTTP 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 Origin header during WS handshake to prevent Cross-Site WebSocket Hijacking (CSWSH).

11. Related Decisions