🧩 What is WebSocket?
🔹 Definition:
WebSocket is a full-duplex, bidirectional communication protocol over a single TCP connection, primarily used for real-time communication between a client (usually a browser) and a server.
🔁 Traditional HTTP vs WebSocket
🧠 How WebSocket Works
1. Handshake (Upgrade Request)
WebSocket starts as an HTTP connection.
The client sends an Upgrade header to switch protocols:
GET /chat HTTP/1.1
Host: server.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Sec-WebSocket-Version: 13
Server responds with 101 Switching Protocols:
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
🔒 Note: This uses the same port as HTTP (80) or HTTPS (443) but switches protocols mid-stream.
2. Data Frames (After Upgrade)
WebSocket messages are sent in frames. There are control frames and data frames.
Each frame has:
FIN bit (final frame)
Opcode (text, binary, ping, pong, close)
Payload length
Masked data (for security)
🧠 You can send:
Text: chat messages, JSON
Binary: images, audio, video
Ping/Pong: heartbeat messages
Close: to gracefully terminate
3. Persistent Full-Duplex Communication
Once connected:
Client and server can send messages at any time
No need to poll or re-establish connection
Perfect for low-latency, high-frequency apps
🔧 Real-World Use Cases
🧪 WebSocket Debugging (Hands-On Tools)
🔍 Tools
📟 Using wscat:
npm install -g wscat
wscat -c ws://localhost:8080
> Hello
< Hello from server
🧰 WebSocket vs Alternatives
🔐 WebSocket + Security Considerations
Always use WSS (WebSocket over TLS) in production
Use authentication during the handshake (e.g., token in URL/query/header)
Limit message size to avoid DoS attacks
Use origin checking on server
Implement ping/pong heartbeats to detect dead connections
⚙️ Protocol Stack: OSI Layer Mapping
👨💻 FAANG-Level Interview Questions on WebSocket
🧩 Beginner
What is WebSocket and how is it different from HTTP?
How does a WebSocket handshake work?
What port does WebSocket use?
🧩 Intermediate
How would you implement authentication in a WebSocket app?
What are the risks of using WebSocket in production?
How can you detect a dead WebSocket connection?
🧩 Advanced / System Design
How would you scale a WebSocket-based chat app to support 10 million users?
What are strategies to load balance WebSocket traffic?
How do you handle backpressure or message flooding in WebSocket?
How do WebSockets interact with reverse proxies like NGINX or API Gateways?
📁 Example Use Case (Chat)
Architecture:
[Client Browser]
⇅ WebSocket
[NodeJS App] ⇄ Redis Pub/Sub ⇄ [Other NodeJS Servers]
All WebSocket servers are stateless
Redis keeps track of message distribution
Messages are published to all connected clients via subscribed channels