Web Socket

 



🧩 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

Feature

HTTP (Request-Response)

WebSocket (Full-Duplex)

Connection

New TCP connection per request

Single persistent TCP connection

Direction

Client → Server only

Client ⇄ Server

Overhead

High (headers in each request)

Minimal after initial handshake

Latency

Higher

Very low (ideal for real-time)

Use case

Browsing, API calls

Live chats, gaming, stock updates


🧠 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

Use Case

Why WebSocket?

✅ Chat apps (e.g., WhatsApp Web)

Real-time, instant delivery

✅ Live sports/stock updates

Push data as it changes

✅ Multiplayer gaming

Low latency, bidirectional

✅ Collaborative tools (Google Docs)

Real-time editing

✅ IoT device monitoring

Continuous data stream


🧪 WebSocket Debugging (Hands-On Tools)

🔍 Tools

Tool

Use

Browser DevTools

Inspect WS connections (Network → WS tab)

Wireshark

Analyze WebSocket frames

wscat (CLI)

Test WebSocket endpoints manually

Postman (Beta)

Test WebSockets visually

Node.js / Python

Simulate clients

NGINX logs

Connection handling & timeouts

tcpdump/ss

Check TCP-level behavior

📟 Using wscat:

npm install -g wscat

wscat -c ws://localhost:8080

> Hello

< Hello from server



🧰 WebSocket vs Alternatives

Protocol

Pattern

Use case

HTTP Polling

Client keeps asking

Inefficient, high latency

Long Polling

Hold connection open

Better, still wasteful

Server-Sent Events (SSE)

Server → Client only

No two-way data

WebSocket

Two-way, persistent

Best for real-time & high frequency


🔐 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

OSI Layer

Role in WebSocket

7 (Application)

Chat, JSON, etc.

6 (Presentation)

Encoding/decoding (UTF-8, binary)

5 (Session)

Persistent connection maintenance

4 (Transport)

TCP

3–1

IP, Ethernet, etc. (as usual)


👨‍💻 FAANG-Level Interview Questions on WebSocket

🧩 Beginner

  1. What is WebSocket and how is it different from HTTP?

  2. How does a WebSocket handshake work?

  3. What port does WebSocket use?

🧩 Intermediate

  1. How would you implement authentication in a WebSocket app?

  2. What are the risks of using WebSocket in production?

  3. How can you detect a dead WebSocket connection?

🧩 Advanced / System Design

  1. How would you scale a WebSocket-based chat app to support 10 million users?

  2. What are strategies to load balance WebSocket traffic?

  3. How do you handle backpressure or message flooding in WebSocket?

  4. 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


Distributed by Gooyaabi Templates | Designed by OddThemes