Key Takeaways
- A WebRTC voice AI implementation treats WebRTC as the transport layer, not the agent itself — it moves audio over UDP with its own jitter buffer, so a dropped packet degrades one 20ms frame instead of stalling the stream behind a TCP retransmit
- RFC 7874 requires every WebRTC endpoint to implement Opus plus G.711 (PCMA/PCMU); Opus at 48kHz with 20ms frames is the right default for agent audio, and the G.711 path is what you fall back to on a PSTN bridge
- Trickle ICE (RFC 8838) is the setup change with the largest payoff: exchanging candidates incrementally instead of waiting for gathering to complete removes most of the dead air before the agent's first word
- Budget 20–60ms for transport and jitter buffering inside a sub-250ms p50 target — the remaining 200ms+ belongs to STT, LLM first-token, and TTS first-chunk, not the network
- Prodinit built Cuebo's self-hosted LiveKit stack on this architecture: a WebRTC SFU for media, Python agent workers for the AI pipeline, and ECS autoscaling that absorbs 10x peak load at 90K+ calls/month
A voice agent that works perfectly on your laptop will fail on a corporate VPN, and the failure will look like a model problem. The transcript is empty, the agent says nothing, and the logs show a healthy session. The actual cause is almost always two layers below the model: ICE never found a path, or it found one and the audio is arriving too late to be useful.
WebRTC voice AI implementation, the short version. WebRTC gives a voice agent a low-latency, encrypted, bidirectional audio path over UDP. A working implementation needs five pieces: a signalling channel, a token-authenticated room join, ICE with STUN and TURN, an Opus-encoded media path with tuned capture constraints, and an agent worker that consumes RTP frames and publishes synthesized audio back.
Why WebRTC and Not a WebSocket for Voice AI Audio
The case for WebRTC over a raw WebSocket is a transport argument, not a feature argument. WebSockets run on TCP, which guarantees ordered delivery — and that guarantee is exactly wrong for live audio. One lost packet triggers a retransmit, and every frame behind it waits. For a voice agent, that stall lands as a half-second of silence mid-sentence.
WebRTC runs media over UDP with SRTP. A lost packet degrades a single 20ms Opus frame; packet loss concealment interpolates it and the conversation continues. WebRTC also ships a jitter buffer and playout clock, which a WebSocket does not have — with raw WebSocket audio you are writing your own reordering and timing logic, and that code is where most homegrown voice stacks break under real network conditions.
Three other things come free with WebRTC and have to be rebuilt by hand otherwise:
- Encryption is not optional. RFC 8827 defines the WebRTC security architecture, with peer identity verified cryptographically through DTLS-SRTP. There is no unencrypted WebRTC media path to misconfigure — which also makes the compliance scope easier to argue when call audio never leaves your own infrastructure.
- Browser audio processing.
getUserMediaexposes echo cancellation, noise suppression, and automatic gain control as capture constraints. Echo cancellation in particular is load-bearing: without it, the agent's own TTS output re-enters the microphone and the STT transcribes the agent talking to itself. - NAT traversal. ICE, STUN, and TURN solve connectivity for clients behind NATs and firewalls. This is the part teams underestimate, and a later section is entirely about it.
A WebSocket is still the right tool for the control channel — session state, transcripts, tool-call events, UI updates. The production pattern is WebRTC for media and a WebSocket alongside it for everything that is not audio.
The Five Components of a WebRTC Voice AI Implementation
A production WebRTC voice agent is five distinct components, and conflating any two of them is the most common architectural mistake. The media server, the control plane, and the AI pipeline each have different failure modes, different resource profiles, and different scaling axes — which is why they belong on separate services.
- The client — a browser or mobile app that captures microphone audio via
getUserMedia, establishes the peer connection, and plays received audio. - The signalling channel — an HTTPS or WebSocket path that exchanges SDP offers and answers plus ICE candidates. Signalling is not part of the WebRTC spec; you choose it.
- The media server (SFU) — a Selective Forwarding Unit such as LiveKit that terminates DTLS/SRTP, manages room state, and forwards RTP packets without decoding or re-mixing them. For a two-party agent call it is technically optional, but you want it for recording, observability, and multi-participant sessions.
- The agent worker — a process that joins the room as a participant, receives decoded audio frames, runs the STT → LLM → TTS pipeline, and publishes synthesized audio back into the room.
- The control plane — your existing API. It creates rooms, mints access tokens, dispatches agents, and handles webhooks for lifecycle events.
The separation between the media server and the agent worker is the one that matters most. When Prodinit migrated Cuebo's voice AI off a Django WebSocket monolith, the core change was exactly this split: LiveKit handles WebRTC signalling and media routing, while standalone Python agent workers run the pipeline on their own ECS service. LLM latency can no longer destabilise WebRTC signalling, and each side autoscales on its own metric.
WebRTC Voice AI Implementation Guide: Signalling and the Room Join
Signalling is deliberately unspecified in WebRTC, which means it is yours to get right. The sequence for an agent call is: client requests a session from your API, your API creates a room and mints a short-lived JWT scoped to that room and identity, the client connects with the token, and your API dispatches an agent worker into the room.
Keep three rules in the signalling layer:
Mint tokens server-side, scoped and short-lived. The access token encodes room name, participant identity, and permissions (can publish, can subscribe, can publish data). It should expire in minutes, not hours, and it must never be generated in the browser — a long-lived token with room-create permission is a free voice agent for anyone who reads your bundle.
Dispatch the agent with a metadata payload, not a code branch. When the control plane dispatches a worker, it passes JSON metadata describing which pipeline to run. The worker reads that field and instantiates the matching pipeline class. Cuebo's agent worker uses a factory pattern on exactly this mechanism to select between five STT/LLM/TTS combinations — Deepgram, Azure OpenAI, ElevenLabs, Claude Sonnet, and Sarvam variants — from one codebase. Switching pipelines is a per-session configuration value, not a deployment.
Handle the lifecycle webhooks. participant_joined and room_finished are how your control plane learns what actually happened. Without them you accumulate orphaned rooms and sessions that look active forever. Pair them with a scheduled cleanup task for calls that died without firing an event.
ICE, STUN, and TURN — The Part That Breaks on Corporate Networks
ICE is where WebRTC voice agents fail in the field. The client gathers candidate addresses — host, server-reflexive via STUN, and relayed via TURN — and the two peers probe pairs until one works. On a home network the direct path almost always succeeds. Behind symmetric NAT, a restrictive corporate firewall, or a VPN, it often does not, and the call needs a TURN relay.
Deploy TURN. It is not optional. A STUN-only configuration works in testing and then fails for exactly the enterprise users you care about. TURN relays media through your server when no direct path exists, which costs bandwidth and adds a hop of latency — and it is the difference between a call and a silent session. Run TURN on UDP with TCP and TLS on port 443 as fallbacks, because some networks block everything else.
Use trickle ICE. Specified in RFC 8838, trickle ICE exchanges candidates as they are discovered instead of waiting for gathering to finish before sending the offer. Non-trickle setups wait for every candidate, including TURN allocations that may time out. Practitioner reports put the penalty at several hundred milliseconds to roughly two seconds of added call-setup time; those figures are not independently benchmarked, but the direction is not in dispute, and all major SDKs trickle by default. Verify yours has not been turned off.
Open the right UDP ports. A self-hosted media server needs its UDP range reachable — and a security group that permits TCP but not the UDP media range is the most common deployment failure in new self-hosted WebRTC stacks. The symptom is a session that connects, reports healthy, and carries no audio.
Log ICE connection state transitions and the selected candidate pair type for every call. When a user reports silence, the first question is whether they relayed or went direct, and you cannot answer it retroactively without that log line. This belongs in the same instrumentation layer as the rest of your voice AI monitoring.
Tuning the Audio Path: Opus, Capture Constraints, and the Jitter Buffer
RFC 7874 requires every WebRTC endpoint to implement Opus with the RFC 7587 payload format, plus PCMA and PCMU (G.711). For agent audio, Opus at 48kHz with 20ms frames is the default worth keeping: it is the wideband path, it carries its own comfort-noise mechanism, and its packet loss concealment is why moderate loss stays intelligible rather than dropping words.
Three settings carry most of the audio quality:
Capture constraints. Request echoCancellation: true, noiseSuppression: true, and autoGainControl: true in getUserMedia. Teams sometimes disable echo cancellation to "preserve audio fidelity for the STT" and immediately regress into the agent transcribing its own TTS output. Keep it on.
Jitter buffer depth. The jitter buffer trades latency for smoothness. Too shallow and packet reordering becomes audible gaps; too deep and you have added dead time to a budget that cannot afford it. Start at the SDK default, measure p95 jitter on real traffic, and only then adjust. Sizing it from a developer laptop on office Wi-Fi is how you ship a buffer that collapses on a mobile network.
The G.711 fallback. Any call bridged to the PSTN lands on 8kHz G.711 — narrowband, and a measurable accuracy hit for STT. If telephony is in scope, evaluate your STT model on 8kHz audio specifically, because SIP trunking into a WebRTC stack changes the input distribution your transcription accuracy was measured on.
Transport and jitter buffering should consume 20–60ms of an end-to-end budget targeting sub-250ms at p50. If the network layer is eating more than that, the problem is usually a relayed candidate pair, a media server in the wrong region, or a jitter buffer tuned by guess.
Wiring the Agent: From RTP Frames to STT, LLM, and TTS
The agent worker joins the room as a participant, subscribes to the caller's audio track, and receives decoded PCM frames. From there the pipeline is a streaming chain, and the word "streaming" is the whole design: every stage must emit partial results rather than waiting to complete.
The loop, in order:
- VAD on the inbound frames to detect speech start and end — 10–30ms, and the gate for everything downstream.
- Streaming STT over a pre-warmed connection. Opening a fresh STT socket per utterance adds a full handshake to the critical path; hold the connection open for the session.
- LLM call fired on interim transcripts, not on the final one, with the request cancelled if the user keeps talking.
- TTS started on the first LLM sentence boundary, not on completion, and published into the room as it synthesizes.
- Barge-in that stops playback and cancels the in-flight LLM and TTS calls the moment VAD detects the caller interrupting.
Barge-in is where a WebRTC voice agent either feels alive or feels broken, and it is the behaviour most worth building a test harness around — we cover the mechanics in testing voice agents for barge-in and latency.
Two implementation notes that save a rewrite. First, publish synthesized audio as a track into the room rather than streaming it back over your control WebSocket; the SFU already has the timing and encryption, and a second transport means a second sync problem. Second, keep the worker stateless per session and push state into your control plane, because an agent worker that holds session state cannot be autoscaled or replaced mid-incident.
Whether you self-host the media server or use a hosted SFU is a separate decision from this architecture — the agent worker code is identical either way. Our self-hosted LiveKit production guide covers the deployment side, and LiveKit vs Pipecat compares the two frameworks we have run in production.
Get Prodinit's AI engineering guides in your inbox
Deep-dives on production LLMs, voice AI, and MLOps — published weekly. No sales emails.
Frequently Asked Questions
A WebSocket works for a prototype and degrades under real network conditions. TCP retransmits stall every queued audio frame, and you have to build jitter buffering, playout timing, and echo cancellation yourself. Use WebRTC for media and a WebSocket for the control channel — session state, transcripts, and tool events.
Transport and jitter buffering should account for 20–60ms inside an end-to-end budget targeting sub-250ms at p50. If the network layer costs more, the usual causes are a TURN-relayed candidate pair, a media server in a distant region, or an over-deep jitter buffer. STT, LLM first-token, and TTS first-chunk own the remaining budget.
You need TURN. STUN alone resolves most home-network connections and fails behind symmetric NAT, restrictive corporate firewalls, and many VPNs — exactly where enterprise users sit. Run TURN with UDP first and TCP plus TLS on port 443 as fallbacks, and log the selected candidate pair type so you can diagnose silent calls.
Opus at 48kHz with 20ms frames. RFC 7874 makes Opus and G.711 (PCMA/PCMU) mandatory for every WebRTC endpoint, and Opus gives you wideband audio, built-in comfort noise, and packet loss concealment. Calls bridged to the PSTN drop to 8kHz G.711, so validate STT accuracy on narrowband audio separately.
Three causes account for most of it: the media server's UDP port range is blocked by a security group that permits TCP only, ICE selected no working candidate pair because TURN is missing, or the agent worker subscribed to the room but never to the participant's audio track. Log ICE state transitions and track subscriptions to separate them.