A TURN server relays WebRTC traffic when a browser cannot reach its media peer directly. For voice-agent teams, the operating job extends beyond making that server reachable: access must be controlled, audio must flow through the selected relay path, and capacity must remain visible. Here is a practical coturn workflow covering provisioning, credentials, browser configuration, failure diagnosis, and recovery.
What a TURN server must deliver
TURN stands for Traversal Using Relays around NAT, or network address translation. It gives a client a reachable relay address when a direct path is unavailable. In a browser voice session, the other peer is usually the agent's media service. Interactive Connectivity Establishment (ICE) selects the candidate pair used to carry the session.
Three separate outcomes matter:
- An authorized browser can obtain a relay allocation, the address, port, and server-side state reserved for its traffic.
- The selected ICE path carries audio in both directions.
- Operators can distinguish credential failures, blocked media paths, and exhausted relay resources.
A gathered relay candidate proves only the first outcome. A listening process proves even less.
Our WebRTC and WebSocket comparison covers transport selection and candidate discovery. The work here begins with an application that already exchanges session descriptions and ICE candidates. The examples are generic WebRTC infrastructure, independent of any managed agent provider's relay interface.
1. Provision the listener and the relay path
Use a dedicated Linux host with a stable public address, a DNS hostname such as turn.example.com, and a trusted TLS certificate for that hostname. TLS means Transport Layer Security. Keep public ingress closed during installation and configuration.
On Debian-based systems, coturn is available as a package:
sudo apt-get update sudo apt-get install coturn
The configuration below uses the coturn configuration options from version 4.19.2. Package versions and service definitions vary by distribution. Its example host has private address 10.0.1.10 and public address 203.0.113.10; replace both, the hostname, secret, and certificate paths with deployment values.
# /etc/turnserver.conf listening-ip=10.0.1.10 relay-ip=10.0.1.10 external-ip=203.0.113.10/10.0.1.10 listening-port=3478 tls-listening-port=5349 min-port=49152 max-port=51151 realm=turn.example.com fingerprint use-auth-secret static-auth-secret=REPLACE_WITH_BACKEND_SHARED_SECRET cert=/etc/turn/tls/fullchain.pem pkey=/etc/turn/tls/privkey.pem no-tcp-relay no-multicast-peers # Loopback peers stay blocked. Do not enable allow-loopback-peers. denied-peer-ip=10.0.0.0-10.255.255.255 denied-peer-ip=172.16.0.0-172.31.255.255 denied-peer-ip=192.168.0.0-192.168.255.255 denied-peer-ip=169.254.0.0-169.254.255.255 denied-peer-ip=fc00::-fdff:ffff:ffff:ffff:ffff:ffff:ffff:ffff denied-peer-ip=fe80::-febf:ffff:ffff:ffff:ffff:ffff:ffff:ffff # Illustrative allocation limits, not a calls-per-host rating. user-quota=4 total-quota=800 drain-min-allocations=0 log-file=stdout
Here, user-quota=4 limits concurrent allocations for the application-assigned relaySessionId suffix used below. In coturn 4.19.2, quota identity handling strips the numeric timestamp from this timed username. Changing only the expiry preserves that quota bucket; issuing another session suffix creates another. Account- and tenant-wide fairness still belongs in the issuer and application.
Store the rendered configuration and private key with access limited to the service and administrators. Inject the shared secret from backend secret storage. The credential issuer in step 2 needs the same secret; the browser never receives it. Use use-auth-secret alone, without adding lt-cred-mech or no-auth.
For a host with its public address directly on an interface, use that address for listening and relaying and omit the NAT mapping. Behind NAT, every allocated relay port needs a port-preserving mapping: external port 50000 must reach internal port 50000.
The network rules must cover two different legs:
| Traffic | Example ingress | Purpose |
|---|---|---|
| Browser to TURN | UDP and TCP 3478 | TURN client connections |
| Browser to TURN over TLS | TCP 5349 | Encrypted TURN client connection |
| Media peer to relay allocation | UDP 49152–51151 | Peer traffic to the allocated relay port |
Allow corresponding outbound traffic and return packets. Apply the same relay range at the cloud firewall, host firewall, and any NAT or container boundary. An HTTP reverse proxy in front of the listener does not supply this relay path. Coturn's container networking guidance also calls out the cost of mapping large port ranges.
The private-address rules above are a baseline, not a complete destination policy. Add organization-specific internal ranges, metadata destinations, and any other networks the relay must not reach. Coturn 4.19.2 blocks loopback peers by default; this configuration deliberately leaves allow-loopback-peers unset. Security acceptance requires rejected relay access to IPv4 loopback (127.0.0.0/8), IPv6 loopback (::1), and forbidden private destinations, including relevant mapped-address forms.
If the agent uses known media addresses, a narrow destination policy can reduce exposure further. Coturn's allow rules override matching deny rules, so a broad allow can undo a restriction. Network egress controls supply port-level restrictions that an IP-only peer rule cannot.
Run coturn under a service manager with an unprivileged service account, readable certificate material, captured logs, and restart controls. The server invocation is:
turnserver -c /etc/turnserver.conf
Open the intended public ports only after the configuration and egress policy are in place. Keep management endpoints off public ingress.
2. Issue credentials after authorizing the voice session
Do not embed a permanent TURN password in browser JavaScript. An application backend should authenticate the caller, authorize the requested tenant and voice session, and issue a short-lived credential pair.
Coturn calls its time-limited credential convention the TURN REST API. The application's web server supplies the HTTP endpoint. Coturn validates the resulting username and password; it does not provide that credential endpoint itself.
The username combines an expiry timestamp in Unix seconds with an identifier. The password is a Base64-encoded HMAC-SHA1, a keyed message authentication code, over that exact username. This server-side Node.js helper follows the coturn credential convention:
import { createHmac } from "node:crypto"; const sharedSecret = process.env.TURN_SHARED_SECRET; if (!sharedSecret) throw new Error("Missing TURN shared secret"); // Call only after application authorization. // relaySessionId is a backend-assigned, opaque session identifier. export function issueTurnCredentials(relaySessionId) { const expiresAt = Math.floor(Date.now() / 1000) + 600; const username = `${expiresAt}:${relaySessionId}`; const credential = createHmac("sha1", sharedSecret) .update(username, "utf8") .digest("base64"); return { expiresAt, iceServers: [{ urls: [ "turn:turn.example.com:3478?transport=udp", "turn:turn.example.com:3478?transport=tcp", "turns:turn.example.com:5349?transport=tcp" ], username, credential }] }; }
Ten minutes is an example credential lifetime, separate from allocation lifetime and call revocation. In coturn 4.19.2, an authenticated session retains its key for later integrity checks. An expired timed username cannot authenticate a new allocation, but expiry does not terminate an existing allocation or require replacement credentials for every Refresh request.
New allocations need valid credentials, including an ICE restart that requires a new allocation. The rollout gate includes long-running refreshes and post-expiry allocation attempts on the deployed client and server versions. Application session termination needs its own enforcement; a ten-minute timestamp is not a ten-minute call-revocation timer.
Scope access in the application: issue only for an entitled session, rate-limit issuance by account and tenant, and record the opaque session identifier for correlation. Return the response over HTTPS with Cache-Control: no-store. Keep credentials out of URLs, analytics events, and ordinary logs.
The session label supports attribution. It does not cryptographically bind the credential to a browser, an origin, or a particular remote peer. Anyone holding the pair can use it within the server's authentication and resource limits. Peer restrictions, allocation quotas, and issuer controls supply additional bounds.
Keep issuer and relay clocks synchronized. Cover expired timestamps, a wrong shared secret, unauthorized session requests, and clock skew in authentication acceptance cases. Coordinate secret rotation across issuer and relay, accounting for outstanding credentials.
3. Configure ICE servers and client transports
Fetch credentials immediately before creating the peer connection:
const response = await fetch("/api/voice/turn-credentials", { method: "POST", credentials: "same-origin", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ sessionId }) }); if (!response.ok) throw new Error("Relay access unavailable"); const { iceServers } = await response.json(); const pc = new RTCPeerConnection({ iceServers, iceTransportPolicy: "all" });
The endpoint and sessionId are application-defined. A caller-supplied session ID is never authorization by itself. Retain the application's microphone, track, signaling, and termination handling around this connection.
The URL's transport parameter describes the browser-to-TURN leg. turn:...?transport=tcp does not make the TURN-to-agent leg TCP. The configuration above disables separate TCP relay allocations with no-tcp-relay while retaining TCP and TLS client listeners. Its peer-facing relay is UDP. TURN URI schemes and transport parameters are defined in RFC 7065.

For networks that permit outbound TLS only on port 443, a TURN TLS listener can use that port on a suitable address. It still requires TURN-aware routing and a valid certificate. Port 443 does not turn TURN into HTTPS or guarantee passage through an enterprise proxy.
Keep iceTransportPolicy: "all" for normal direct-or-relay operation unless product policy requires relay-only media. All three sample URLs use one hostname. They offer transport choices, not an independent relay failure domain, and their list order is not an application-controlled failover sequence.
4. Prove relay-only audio, not just candidate gathering
A relay acceptance run forces iceTransportPolicy: "relay" on the browser. If both peers are intended to allocate relays, apply relay-only policy on both. If the agent has a public media endpoint, only the browser side needs a relay candidate. The WebRTC relay policy restricts which candidates ICE may use.
Run each advertised URL independently with fresh peer connections, then run the combined configuration. Use two remote endpoints and representative restricted networks, including a case with client UDP blocked. A same-network call or successful TLS handshake cannot establish that peer-facing relay ports work.
Candidate gathering and selection are separate. From getStats(), follow the transport's selected pair to its local and remote candidates:
async function selectedPaths(pc) { const report = await pc.getStats(); const paths = []; for (const stat of report.values()) { if (stat.type !== "transport" || !stat.selectedCandidatePairId) { continue; } const pair = report.get(stat.selectedCandidatePairId); if (!pair) continue; const local = report.get(pair.localCandidateId); const remote = report.get(pair.remoteCandidateId); paths.push({ state: pair.state, nominated: pair.nominated, localType: local?.candidateType, remoteType: remote?.candidateType, relayProtocol: local?.relayProtocol, bytesSent: pair.bytesSent, bytesReceived: pair.bytesReceived }); } return paths; }
Acceptance requires a selected, succeeded pair with nominated: true and localType: "relay" on the relaying browser. Require remoteType: "relay" only when the remote side must also relay. relayProtocol identifies the local candidate's transport to TURN. These relationships come from the WebRTC statistics model.
Sample during sustained audio. Both pair byte counters should rise, and inbound/outbound audio RTP counters should advance on the corresponding endpoints. RTP is the Real-time Transport Protocol. Candidate-pair counters alone are not audio-only evidence. Include audible speech or a known audio signal in each direction, plus packet loss, jitter, and round-trip measurements.
Carry ICE candidates through signaling correctly. Trickle ICE sends candidates as they arrive; a non-trickle flow waits for gathering to finish before sending the complete local session description. An offer sent before relay candidates exist, with no later candidate delivery, can defeat a healthy relay.
5. Classify allocation failures before retrying
Correlate the application session, relay node, client transport, address family, allocation outcome, and selected candidate type. Redact credentials and restrict access to network identifiers. Browser error events help locate failures, but server logs provide the TURN transaction context.
| TURN response | Meaning and operating response |
|---|---|
Initial 401 | Normal challenge. Retry with the supplied realm and nonce. |
Repeated 401 after authentication | Credentials rejected. Inspect expiry, shared-secret agreement, and auth configuration. |
438 | Stale nonce. Retry with the new nonce. |
403 | Administrative restriction, potentially a forbidden peer. Resolve policy before retrying. |
437 on Allocate | The client/server 5-tuple is already allocated. Retry from a different client transport address, with bounded attempts. |
437 on Refresh | Treat the allocation as gone and recover state. |
486 | Allocation quota reached. Back off at least one minute. |
508 | Relay capacity unavailable. Back off at least one minute and investigate capacity. |
408 | Server or path trouble. Another client transport may be a recovery route. |
The TURN error-code definitions, Allocate response handling, and Refresh response handling distinguish these cases. A 5-tuple combines the client address/port, server address/port, and transport. Avoid a single retry loop for all outcomes.
If allocation succeeds but audio fails, move to the advertised relay address, relay-range firewall/NAT mapping, peer permissions, selected pair, and audio tracks. Reissuing credentials will not repair an unreachable peer-facing port.
6. Monitor capacity and exercise recovery
Measure relay use at two levels. Allocated resources consume server capacity even when ICE selects another path. Selected relay sessions describe actual media dependence on TURN. Neither count is interchangeable with application calls.
Metrics are opt-in; the base invocation above does not enable them. Add --prometheus to expose coturn's endpoint, normally at :9641/metrics, with network access restricted to monitoring systems. HTTP is the default. Its turn_total_allocations gauge reports live allocations with client transport and address-family labels. The coturn metrics documentation defines the available series.
Use a small operating dashboard:
| Signal and collection point | Decision it supports |
|---|---|
| Allocation outcomes by transport/region, from relay logs | Detect a broken listener, auth rollout, or network path |
| Live allocations from coturn metrics; port availability and quota rejection evidence from host counters/logs | Add capacity before resource exhaustion |
| Selected relay sessions and TCP/TLS client legs, from browser/media telemetry | Detect network-mix changes and relay dependence |
| Interface throughput, packet rate, drops, CPU, and socket/file-descriptor use, from host monitoring | Identify the limiting host resource |
| Billable outbound bytes and regional cost, from network/billing data | Keep egress within the operating budget |
| Periodic relay-only audio success and setup time, from an end-to-end probe | Detect failures a process-health probe misses |
Build application-level signals where the relay exporter does not supply them. A raw UDP 401 counter includes ordinary challenges and is not an invalid-password rate.
Size against peak simultaneous allocations, setup bursts, relay-port demand, and measured traffic. For the single-relay path above:
relay outbound bits/second ≈ relayed sessions × (browser-bound + agent-bound bitrate)
Use observed wire rates, including protocol overhead, rather than codec settings alone. Compare that result with interface measurements and the provider's billing definition. Traffic crosses both relay legs; a one-direction audio bitrate understates full-duplex relay egress.
Set user-quota, total-quota, per-session max-bps, and aggregate bps-capacity from the resulting load envelope. Convert the formula's bits/s to bytes/s by dividing by eight. Compare per-session rates with max-bps and aggregate rates with bps-capacity, accounting for input and output separately. A combined ingress-plus-egress host total is a different scope from either directional limit.
Limits need room for legitimate bursts and recovery traffic. A narrowly restricted port range can become the first bottleneck even while CPU is idle.
Recovery capacity must cover a lost node or region, not only a normal busy hour. The single-hostname example does not provide that redundancy. Independently provisioned relay endpoints and a demonstrated ICE/application recovery path are deployment acceptance requirements. Adding URLs alone does not establish failover. Run these acceptance cases against that deployment:
- Credential and certificate renewal: new allocations remain available through secret rotation and TLS certificate replacement.
- Graceful replacement: remove the node from new-session routing, then enter coturn drain mode with
SIGUSR1. Withdrain-min-allocations=0, shutdown waits for active allocations to end. - Abrupt loss: interrupt a relay during bidirectional audio. Measure detection, fresh-credential acquisition, ICE restart or session recreation, and time to usable audio.
- Traffic redistribution: send new allocations to surviving capacity and retain acceptable setup success, loss, and latency.
A relay allocation is node-local state. Changing DNS does not migrate it. UDP load balancing also needs consistent transaction and allocation routing. Coturn's shared stateless-nonce setting can address cross-node nonce validation; it does not share allocation state and uses a different secret from credential issuance.
Keep the agent-runtime boundary explicit
TURN owns a media path. The voice application still owns session authorization, signaling, agent execution, and user-visible recovery. With a managed stack, the integration contract determines who provisions TURN and which credential, routing, and diagnostic controls are available.
We support browser voice calls using WebRTC audio and WebSocket signaling. The generic coturn configuration here is not a Dasha TURN-hosting API or a bring-your-own-relay contract. Teams choosing a managed agent runtime can start with our browser voice-call implementation and use the relay acceptance criteria to define their restricted-network requirements.



