πŸŽ‰ 75% of content is free forever β€” Unlock Premium from $10/mo β†’
CW
Search courses…
πŸ’Ό Servicesℹ️ Aboutβœ‰οΈ ContactView Pricing Plansfrom $10

WebSockets and Real-Time

ArchitectureReal-Time Systems🟒 Free Lesson

Advertisement

Architecture

WebSockets and Real-Time

WebSockets enable bidirectional communication between client and server. Master the WebSocket protocol, connection management, scaling strategies, and the patterns behind real-time features.

  • Bidirectional β€” Both client and server can send messages
  • Persistent β€” Connection stays open for low latency
  • Scalable β€” Horizontal scaling with pub/sub backends

WebSockets turn HTTP's request-response into a real-time conversation.

WebSocket Protocol

DfWebSocket

WebSocket is a communication protocol that provides full-duplex communication over a single TCP connection. It starts as an HTTP handshake (Upgrade header) then switches to a persistent, bidirectional connection. WebSockets are designed for low-latency, high-throughput communication between client and server.

HTTP vs WebSocket

AspectHTTPWebSocket
CommunicationRequest-responseBidirectional
ConnectionShort-livedPersistent
LatencyHigh (headers)Low (minimal framing)
Server PushPolling/SSENative support
Use CaseREST APIs, CRUDChat, games, live updates

WebSockets are not always better than HTTP. For request-response patterns, HTTP/2 with multiplexing is often sufficient. WebSockets shine when you need real-time updates or bidirectional communication.

Connection Lifecycle

ClientServer1. HTTP Upgrade Handshake2. Connection Established3. Bidirectional Messages4. Keep-Alive (Ping/Pong)5. Connection Close

Scaling WebSockets

The Challenge

WebSockets are stateful connections. Unlike HTTP requests that can go to any server, WebSocket connections must be maintained on the same server. This makes horizontal scaling more complex.

Scaling Architecture

Clients1M+ connectionsLoad BalancerSticky sessionsWS Server 1WS Server 2WS Server 3Pub/SubRedis / KafkaCross-server msgsMessage Flow1. Client sends message2. Server publishes to pub/sub3. All servers receive message4. Servers deliver to local clients

Connection Management

PatternDescription
HeartbeatRegular pings to detect dead connections
ReconnectionExponential backoff on disconnect
Message QueueingBuffer messages during disconnect
Connection LimitsPer-server and per-user limits

WebSocket Connection Capacity

Cmax=MemoryavailableMemoryper_connectionC_{max} = \frac{Memory_{available}}{Memory_{per\_connection}}

Here,

  • CmaxC_{max}=Maximum connections per server
  • MemoryavailableMemory_{available}=Memory available for connections
  • MemoryperconnectionMemory_{per_connection}=Memory per WebSocket connection (~10KB)

Connection Capacity Planning

Server with 16GB RAM, 4GB reserved for OS:

C_max = (16GB - 4GB) / 10KB = ~1.2M connections per server

For 10M concurrent users: ceil(10M / 1.2M) = 9 WebSocket servers minimum.

Real-Time Patterns

PatternDescriptionUse Case
Pub/SubBroadcast to topic subscribersChat rooms, live feeds
PresenceTrack online/offline statusUser presence indicators
Cursor syncBroadcast cursor positionsCollaborative editing
Live countersReal-time count updatesLike counts, view counts

For production WebSocket systems, always implement: heartbeat detection, exponential backoff reconnection, message acknowledgment, and graceful degradation to long-polling for older browsers.

Practice Exercises

  1. Scaling Design: Design a WebSocket system for 10M concurrent users in a chat application. How many servers, what pub/sub backend, and how do you handle server failures?

  2. Protocol Design: Design the message protocol for a real-time collaborative document editor. Include message types, acknowledgment, and conflict resolution.

  3. Reconnection Strategy: Implement an exponential backoff reconnection strategy. What are the initial delay, max delay, jitter, and max retries?

  4. Performance Analysis: Compare WebSocket, SSE, and HTTP polling for a live sports score update feature. What are the trade-offs in terms of latency, bandwidth, and complexity?

Key Takeaways:

  • WebSockets provide full-duplex, persistent connections over a single TCP connection
  • Scaling requires sticky sessions or pub/sub backends for cross-server messaging
  • Heartbeat detection and exponential backoff reconnection are essential
  • Each WebSocket connection uses ~10KB of memory
  • Pub/sub (Redis/Kafka) enables message distribution across WebSocket servers
  • Choose WebSocket for bidirectional real-time; SSE for server-to-client only

What to Learn Next

-> Elixir and Phoenix for Real-Time Building real-time systems with the BEAM VM and Phoenix Channels.

-> gRPC and Protobuf High-performance RPC with protocol buffers.

-> Chat System Design Designing real-time chat systems at scale.

-> Message Queues Async processing, event-driven architecture, and pub/sub patterns.

-> Load Balancing Distribution algorithms and L4 vs L7 load balancing.

-> Realtime Analytics Design Designing real-time analytics dashboards.

⭐

Premium Content

WebSockets and Real-Time

Unlock this lesson and 900+ advanced tutorials with a Premium plan.

🎯End-to-end Projects
πŸ’ΌInterview Prep
πŸ“œCertificates
🀝Community Access

Already a member? Log in

Need Expert System Design Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement