The Real-Time Web Era
Historically, the web operated on a request-response cycle over HTTP. To build interactive, real-time features like chat rooms, live gaming, or collaborative drawing, developers needed persistent connections. Today, two primary technologies dominate real-time web architecture: WebSockets and WebRTC.
WebSockets: Persistent Client-Server TCP Streams
WebSockets (standardized in RFC 6455) provide a full-duplex communication channel over a single, long-lived TCP connection. The connection starts as a standard HTTP request, which is then "upgraded" to the WebSocket protocol.
Key Characteristics:
- TCP-Based: Ensures reliable, ordered delivery of messages. If a packet is lost, TCP handles retransmission, temporarily blocking subsequent packets.
- Client-Server Topology: Clients always connect to a central server. All messages between client A and client B must hop through the server.
- Low Overhead: Once established, data frames have an overhead of only 2 to 10 bytes, compared to kilobytes in HTTP headers.
WebRTC: Peer-to-Peer UDP Data Channels
WebRTC (Web Real-Time Communication) is an HTML5 specification designed for direct, browser-to-browser audio, video, and raw data transmission (using the RTCDataChannel API).
Key Characteristics:
- UDP-Based: Uses UDP for minimal latency. WebRTC Data Channels rely on SCTP (Stream Control Transmission Protocol) running over DTLS (Datagram Transport Layer Security) to support both ordered/reliable and unordered/unreliable transmission.
- Peer-to-Peer: Traffic flows directly between user devices, bypassing servers entirely after connection negotiation.
- Complex Connection Flow: Requires a signaling mechanism (usually WebSockets) to exchange ICE candidates and SDP parameters, alongside STUN/TURN servers to traverse firewalls and NATs.
Comparing Protocols: When to Use Which
| Feature | WebSockets | WebRTC |
|---|---|---|
| Topology | Client-Server | Peer-to-Peer (P2P) |
| Transport Layer | TCP | UDP (via SCTP/DTLS) |
| Reliability | Guaranteed (Ordered) | Configurable (Reliable or Unreliable) |
| Signaling Complexity | Low (Built-in) | High (Requires external server) |
| Latency | Low (TCP limits) | Ultra-low (UDP direct) |
Architectural Decision Matrix
Choose **WebSockets** if your application needs a centralized state (e.g., financial tickers, multiplayer lobby coordination, notification services) or requires guaranteed message delivery with simple architecture.
Choose **WebRTC** if your application requires streaming massive media streams (video/audio calls), low-latency screen sharing, or high-bandwidth direct file transfers between browsers (like ToolKitnator P2P Transfer).