What is WebSocket?
WebSocket is a computer communications protocol providing full-duplex communication channels over a single TCP connection. Unlike traditional HTTP request-response patterns, WebSocket enables real-time, bidirectional communication between clients and servers, making it perfect for applications requiring live updates, such as chat applications, gaming, collaborative editing, and financial trading platforms.
Standardized by the IETF as RFC 6455 in 2011, WebSocket starts with an HTTP handshake for compatibility but then upgrades to a persistent connection using its own framing protocol. This eliminates the overhead of HTTP headers and connection establishment, reducing latency from hundreds of milliseconds to just a few milliseconds for each message.
WebSocket Performance Calculator
CPU Cores: 2
Capacity Used: 20%
Est. Cost: $110/month
WebSocket vs HTTP Polling
HTTP Polling
Client repeatedly requests updates from server
← 200 OK (no data) ←
Client → GET /updates → Server
← 200 OK (no data) ←
Client → GET /updates → Server
← 200 OK (data!) ←
Latency: Up to poll interval
Efficiency: Wastes bandwidth
Scalability: Poor (connection churn)
WebSocket
Persistent bidirectional connection
← 101 Switching ←
===== Connected =====
Client ↔ Message ↔ Server
Client ↔ Message ↔ Server
Client ↔ Message ↔ Server
Latency: Network RTT only
Efficiency: Minimal overhead
Scalability: Excellent
Performance Comparison
WebSocket: 5-10ms
WebSocket: ~10 bytes/msg
WebSocket: Low (persistent)
WebSocket Protocol Details
1. Handshake Process
WebSocket connection starts with HTTP upgrade request.
GET /chat HTTP/1.1
Host: server.example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Sec-WebSocket-Version: 13
// Server Response
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
2. Frame Structure
WebSocket messages are sent in frames with minimal overhead.
3. Frame Types
- • Text (0x1): UTF-8 text data
- • Binary (0x2): Binary data
- • Continuation (0x0): Fragmented message
- • Close (0x8): Connection close
- • Ping (0x9): Heartbeat request
- • Pong (0xA): Heartbeat response
WebSocket Implementation
Server (Node.js)
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
// Connection handling
wss.on('connection', (ws) => {
console.log('Client connected');
// Handle incoming messages
ws.on('message', (data) => {
console.log('Received:', data.toString());
// Broadcast to all clients
wss.clients.forEach((client) => {
if (client.readyState === WebSocket.OPEN) {
client.send(data);
}
});
});
// Handle disconnection
ws.on('close', () => {
console.log('Client disconnected');
});
// Send heartbeat
const interval = setInterval(() => {
if (ws.readyState === WebSocket.OPEN) {
ws.ping();
}
}, 30000);
ws.on('close', () => clearInterval(interval));
});
Client (JavaScript)
class WebSocketClient {
constructor(url) {
this.url = url;
this.reconnectInterval = 5000;
this.shouldReconnect = true;
this.connect();
}
connect() {
this.ws = new WebSocket(this.url);
this.ws.onopen = () => {
console.log('Connected');
this.reconnectInterval = 5000; // Reset backoff
};
this.ws.onmessage = (event) => {
console.log('Message:', event.data);
// Handle incoming messages
};
this.ws.onclose = () => {
console.log('Disconnected');
if (this.shouldReconnect) {
this.reconnect();
}
};
this.ws.onerror = (error) => {
console.error('Error:', error);
};
}
reconnect() {
setTimeout(() => {
this.reconnectInterval *= 2; // Exponential backoff
this.connect();
}, this.reconnectInterval);
}
send(data) {
if (this.ws.readyState === WebSocket.OPEN) {
this.ws.send(JSON.stringify(data));
}
}
}
// Usage
const client = new WebSocketClient('ws://localhost:8080');
client.send({ type: 'chat', message: 'Hello!' });
Scaling WebSocket Applications
Horizontal Scaling
Distribute connections across multiple servers
• Redis pub/sub for cross-server messaging
• Consistent hashing for connection routing
• HAProxy or nginx for load balancing
Message Broadcasting
Efficient message distribution patterns
• Fanout exchange patterns
• Message queues (RabbitMQ, Kafka)
• Selective broadcasting
Connection Management
Handle millions of concurrent connections
• Heartbeat/ping-pong
• Idle connection cleanup
• Resource limits per connection
High Availability
Ensure reliability and failover
• Message queue persistence
• Connection state recovery
• Geographic distribution
Real-World WebSocket Applications
Slack
Real-time messaging and presence updates
- • Millions of concurrent connections
- • Message delivery in <100ms
- • Typing indicators
- • Presence status updates
Trading Platforms
Real-time market data and order execution
- • Sub-millisecond latency
- • Thousands of price updates/sec
- • Order book streaming
- • Binary protocol for efficiency
Online Gaming
Multiplayer game state synchronization
- • Player position updates
- • Game state broadcasting
- • Low latency requirements
- • Binary data for efficiency
Collaborative Editing
Google Docs, Figma real-time collaboration
- • Operational transformation
- • Cursor position sharing
- • Conflict resolution
- • Presence awareness
WebSocket Security
Security Risks
- • Cross-site WebSocket hijacking (CSWSH)
- • Lack of built-in authentication
- • Message injection attacks
- • DoS through connection exhaustion
Best Practices
- • Always use WSS (WebSocket Secure) over TLS
- • Implement origin validation
- • Add authentication tokens to handshake
- • Rate limit connections per IP
- • Validate and sanitize all messages
- • Implement connection timeouts
WebSocket Best Practices
✅ Do
- • Implement reconnection with backoff
- • Use heartbeat/ping-pong for connection health
- • Compress large messages
- • Implement proper error handling
- • Use message queuing for reliability
- • Monitor connection metrics
- • Plan for graceful degradation
❌ Don't
- • Send sensitive data without encryption
- • Ignore connection limits
- • Skip authentication/authorization
- • Use WebSocket for request-response patterns
- • Forget about proxy/firewall issues
- • Neglect mobile battery optimization
- • Assume connections are always stable