Skip to main content

📱 WebSockets

A phone call instead of texting

The Phone Call Analogy

Two communication styles:

Text messages (HTTP):

  • Send message, wait for reply
  • New connection each time
  • You can't talk at the same time
  • Pull-based: You ask for updates

Phone call (WebSocket):

  • One connection, stays open
  • Both can talk anytime
  • Real-time conversation
  • Push-based: Updates come to you

WebSockets keep the line open for instant, two-way communication.


What Are WebSockets?

WebSocket = Protocol for persistent, bidirectional communication

Regular HTTP:
  Client: "Any updates?"
  Server: "No"
  Client: "Any updates?"
  Server: "No"
  Client: "Any updates?"
  Server: "Yes, here!"

WebSocket:
  Client: "Keep this line open"
  Server: "OK"
  ... (line stays open) ...
  Server: "Here's an update!" (instant)
  Client: "Got it!"

HTTP vs WebSocket

AspectHTTPWebSocket
ConnectionNew each requestPersistent
DirectionRequest-responseBidirectional
InitiationClient initiatesClient initiates, then either side can send
OverheadHeaders each timeMinimal after handshake
Use caseRequest/responseReal-time

How It Works

The Handshake

1. Client sends HTTP request:
   "I'd like to upgrade to WebSocket"

   GET /chat
   Upgrade: websocket
   Connection: Upgrade

2. Server agrees:
   "OK, upgraded!"

   101 Switching Protocols
   Upgrade: websocket

3. Connection upgraded
   Now speaking WebSocket protocol

After Handshake

Bidirectional messaging:

Client ─────────────────────────→ Server
        "Hello!"

Client ←───────────────────────── Server
        "Hi back!"

Client ←───────────────────────── Server
        "New message arrived!"
        (Server pushes, client didn't ask)

Use Cases

Chat Applications

User sends message → Appears quickly for connected users
No constant polling.
No page refresh.

Live Notifications

New email? Push notification immediately.
Stock price changed? Update the chart.
Friend came online? Show indicator.

Collaborative Editing

Google Docs, Figma.
One person types → Others can see it.
Real-time cursor positions.

Gaming

Multiplayer games.
Player moves → Others see it quickly.
Low latency critical.

Live Data Feeds

Stock tickers.
Sports scores.
Social media feeds.

Architecture

┌─────────────────────────────────────────────────────┐
│                     Clients                          │
│   ┌────────┐    ┌────────┐    ┌────────┐            │
│   │Client 1│    │Client 2│    │Client 3│            │
│   └───┬────┘    └───┬────┘    └───┬────┘            │
└───────┼─────────────┼─────────────┼─────────────────┘
        │             │             │
        │ WebSocket   │ WebSocket   │ WebSocket
        │ Connection  │ Connection  │ Connection
        │             │             │
┌───────▼─────────────▼─────────────▼─────────────────┐
│                  WebSocket Server                    │
│                                                      │
│   Maintains all connections                          │
│   Broadcasts to all or specific clients             │
└──────────────────────────────────────────────────────┘

Message Types

Text Messages

Most common.
JSON payloads.

{ "type": "chat", "message": "Hello!" }

Binary Messages

For audio, video, files.
Efficient for large data.

Control Frames

Ping/Pong: Keep connection alive
Close: Graceful shutdown

Implementation Patterns

Rooms/Channels

Users subscribe to rooms.
Messages typically go to room members.

Chat room: #general
  → Alice
  → Bob
  → Charlie

Message to #general → All three receive.

Heartbeat

Connection idle?
Send ping, expect pong.

No pong? Connection dead. Reconnect.

Reconnection

Connection drops (network blip).
Client should auto-reconnect.
Resume where it left off.

Scaling Challenges

Problem

WebSockets are stateful.
Each connection lives on specific server.

Load balancer sends user to Server A.
Push message needs to go to Server A.
How does Server B know about the user?

Solutions

1. Sticky sessions
   Same user often goes to the same server.

2. Pub/Sub backend (Redis)
   All servers subscribe to message channel.
   Message published → All servers receive.
   Server with that user sends to client.

3. Managed services
   Let AWS, Pusher, etc. handle it.

WebSocket Alternatives

Server-Sent Events (SSE)

Server → Client (one direction).
Simpler than WebSocket.
Good for notifications, feeds.

Use when: Server needs to push updates, and the client doesn't need to send messages.

Long Polling

Client keeps request open.
Server responds when data available.
Client immediately makes new request.

Fallback when WebSocket not available.

Which to Use

Real-time bidirectional: WebSocket
One-way server → client push: SSE
Maximum compatibility: Long polling fallback

Common Tools

ToolType
Socket.IOLibrary with fallbacks
wsNode.js WebSocket library
PusherManaged service
AblyManaged service
AWS API GatewayManaged WebSocket

Common Mistakes

1. Not Handling Disconnection

Networks are unreliable.
Usually implement reconnection logic.

2. No Heartbeat

Connection looks open but is dead.
Ping/pong detects this.

3. Too Much Data

Sending unnecessary updates.
Causing client performance issues.

Send what's needed.

4. No Authentication

WebSocket after handshake doesn't re-auth.
Authenticate during handshake.
Check permissions on each message.

FAQ

Q: When to use WebSocket vs REST?

REST: Request/response, not time-sensitive WebSocket: Real-time, instant updates needed

Q: Do WebSockets work through firewalls?

Usually yes (port 80/443). Upgrade looks like HTTP.

Q: How many connections can a server handle?

Thousands to millions with proper optimization.

Q: Are WebSockets encrypted?

wss:// uses TLS (like https://), which helps protect data in transit.


Summary

WebSockets provide persistent, bidirectional connections for real-time communication.

Key Takeaways:

  • Persistent connection (stays open)
  • Bidirectional (both sides can send anytime)
  • Starts with HTTP handshake, upgrades
  • Ideal for chat, notifications, live data
  • Handle disconnection and reconnection
  • Use wss:// (TLS) when available

WebSockets bring real-time to the web!

Related Concepts

Leave a Comment

Comments (0)

Be the first to comment on this concept.

Comments are approved automatically.