Recipe
Recipe: WebRTC peer-to-peer design
A reference architecture for direct browser-to-browser data channels with STUN/TURN negotiation, signaling relay, and fallback paths.
Signaling flow
- Peer A creates
RTCPeerConnectionand generates an offer. - Offer SDP is relayed to Peer B via a lightweight WebSocket signaling server.
- Peer B sets the remote description, creates an answer, and relays it back.
- ICE candidates trickle through the same signaling channel until connectivity is established.
NAT traversal
STUN servers (e.g. Google's public stun:stun.l.google.com:19302) discover the public IP:port mapping. When symmetric NAT blocks direct connectivity, TURN relays media through a fallback server. Always provision TURN as a safety net.
Data channel
After the ICE connection completes, open a bidirectional RTCDataChannel. Use ordered, reliable mode for control messages and unordered, unreliable mode for low-latency streams. Keep messages under 16 KB to avoid fragmentation penalties.
Security
- DTLS-SRTP is mandatory — WebRTC enforces it by default.
- Authenticate the signaling channel with short-lived tokens.
- Validate SDP origin and fingerprint before setting remote descriptions.
- Rotate ICE credentials per session to prevent replay.