While STUN servers help most WebRTC connections succeed, some network configurations are too restrictive for direct peer-to-peer communication. This is where TURN (Traversal Using Relays around NAT) servers become essential. In this guide, we'll explore what TURN servers are, when they're needed, and how to deploy them effectively.
What is a TURN Server?
A TURN server is a relay server that forwards traffic between peers when direct peer-to-peer connections cannot be established. Unlike STUN servers that only facilitate address discovery, TURN servers actively participate in the media transmission, relaying audio, video, and data between peers.
Think of a TURN server as a trusted intermediary. When two people can't communicate directly because of restrictive firewalls or complex NAT configurations, they can both connect to a TURN server, which forwards messages between them.
Why TURN Servers Are Necessary
WebRTC aims for peer-to-peer connections, but real-world networks present challenges that make direct connections impossible in some scenarios:
Symmetric NAT
The most common obstacle is symmetric NAT, where routers create unique port mappings for each destination. This makes it impossible for other peers to predict which port to connect to, even with STUN server assistance.
Corporate Firewalls
Many enterprises implement strict firewall policies that block incoming connections entirely. Even if STUN successfully discovers the public address, the firewall prevents external peers from connecting.
Protocol Restrictions
Some networks only allow specific protocols or ports. For example, they might allow TCP traffic on port 443 but block UDP entirely. TURN servers can adapt to these restrictions by supporting multiple protocols.
Double NAT
Situations where devices sit behind multiple layers of NAT (common with mobile hotspots or complex home networks) can defeat STUN's address discovery capabilities.
How TURN Servers Work
The TURN protocol, defined in RFC 5766, establishes a relay mechanism through several steps:
Connection Establishment
- Allocation Request: The client sends an allocation request to the TURN server, typically including authentication credentials. This request asks the server to reserve resources for relaying traffic.
- Server Allocation: The TURN server authenticates the client and allocates a relay address—a unique public IP and port combination that other peers can use to reach this client.
- Permission Management: The client informs the TURN server which remote peers are authorized to send data through the relay. This prevents unauthorized usage and resource exhaustion.
-
Data Relay: Once configured, all media traffic flows through the TURN server:
- The client sends data to the TURN server
- The TURN server forwards it to the destination peer
- Return traffic follows the same path in reverse
Authentication and Security
TURN servers implement robust authentication to prevent abuse:
- Long-term Credentials: Username and password combinations that remain valid for extended periods. Useful for testing but less secure for production.
- Short-term Credentials: Time-limited credentials typically generated by your application server using a shared secret. This is the recommended approach for production deployments.
- Token-based Authentication: Some implementations support OAuth or JWT tokens for integration with existing authentication systems.
TURN vs STUN: Key Differences
Understanding the distinction between TURN and STUN helps optimize your WebRTC infrastructure:
Resource Usage
STUN: Minimal resources required. The server only processes binding requests and sends responses. A single server can handle tens of thousands of concurrent requests.
TURN: Significant resources needed. The server relays all media traffic, requiring substantial bandwidth and processing power. Capacity planning is crucial for TURN deployments.
Cost Implications
STUN: Negligible operational costs. The lightweight nature means STUN servers are inexpensive to run, and free public options are widely available.
TURN: Higher operational costs due to bandwidth consumption. For video calls, a single TURN relay might consume several megabits per second continuously.
Usage Scenarios
STUN: Used first in the ICE process for address discovery. Succeeds in approximately 80-90% of consumer network configurations.
TURN: Used as a fallback when direct connections fail. Critical for ensuring connectivity in restrictive network environments, particularly in enterprise scenarios.
Connection Quality
STUN-facilitated connections: Direct peer-to-peer connections offer the lowest latency and highest quality.
TURN-relayed connections: Additional latency due to the relay hop, and potential quality reduction if the TURN server becomes a bandwidth bottleneck.
For more on the discovery side, see our companion article on STUN servers.
TURN Server Deployment
Deploying TURN servers requires careful planning and consideration:
Infrastructure Requirements
- Geographic Distribution: Deploy TURN servers in multiple regions to minimize latency. Users should connect to the nearest available server.
- Bandwidth Planning: Calculate bandwidth requirements based on expected concurrent relays. Video calls typically require 1-3 Mbps per participant, depending on quality settings.
- Server Specifications: Modern TURN servers like Coturn can handle hundreds of concurrent relays on a reasonably equipped server, but planning for growth is essential.
- High Availability: Implement redundancy with multiple TURN servers behind load balancers to ensure service continuity.
Popular TURN Server Implementations
- Coturn: The most popular open-source TURN server implementation. It supports TURN, STUN, and STUN over TLS (TURNS), offers excellent performance, and includes features like bandwidth limiting and database integration.
- restund: A lightweight, modular TURN server from the libre project. It's efficient and suitable for smaller deployments.
- eturnal: A modern TURN server written in Erlang, offering excellent concurrency and fault tolerance.
Configuration Example
Here's a basic Coturn configuration:
# /etc/turnserver.conf
# Listening ports
listening-port=3478
tls-listening-port=5349
# Public IP address
external-ip=YOUR_PUBLIC_IP
# Authentication
lt-cred-mech
user=username:password
# Realm
realm=yourdomain.com
# SSL certificates for TURNS
cert=/path/to/cert.pem
pkey=/path/to/key.pem
# Logging
verbose
log-file=/var/log/turnserver.log
Client Configuration
Configuring a TURN server in your WebRTC application:
const configuration = {
iceServers: [
{
urls: 'stun:stun.yourdomain.com:3478'
},
{
urls: [
'turn:turn.yourdomain.com:3478?transport=udp',
'turn:turn.yourdomain.com:3478?transport=tcp',
'turns:turn.yourdomain.com:5349?transport=tcp'
],
username: 'temporaryUsername',
credential: 'temporaryPassword'
}
]
};
const peerConnection = new RTCPeerConnection(configuration);
TURN Server Security
Security is paramount when operating TURN servers, as they can be resource-intensive and attractive to attackers:
Credential Management
- Time-limited Credentials: Generate credentials dynamically with expiration times. This prevents credential theft and unauthorized long-term usage.
- Secure Distribution: Transmit credentials over secure channels only. Never include long-term credentials in client-side code.
- Rotation Policy: Regularly rotate shared secrets used for credential generation.
Access Control
- Authentication Requirements: Never run a TURN server without authentication. Open relays are quickly discovered and abused.
- IP Whitelisting: If possible, restrict TURN server access to known IP ranges.
- Rate Limiting: Implement rate limits to prevent denial-of-service attacks.
Monitoring and Auditing
- Usage Tracking: Monitor TURN server usage patterns to detect anomalies.
- Logging: Maintain detailed logs of allocations, permissions, and data transfers.
- Alerts: Set up alerts for unusual bandwidth consumption or authentication failures.
TURN Protocol Variants
TURN supports multiple transport protocols, each with specific use cases:
TURN over UDP
The standard and most efficient TURN implementation. UDP offers lower latency and is ideal for real-time media. Most TURN deployments primarily use UDP.
TURN over TCP
Useful when UDP is blocked by firewalls. TCP provides reliability but adds latency due to connection establishment and retransmission mechanisms.
TURN over TLS (TURNS)
Adds TLS encryption to TURN, providing an additional security layer. Essential for highly secure environments and helpful in bypassing deep packet inspection firewalls.
TURN over DTLS
Provides encryption for UDP-based TURN connections. Combines the performance benefits of UDP with the security of encrypted transport.
Cost Optimization Strategies
TURN server operation can be expensive. Here are strategies to minimize costs:
Prefer Direct Connections
Optimize your ICE configuration to favor direct connections whenever possible. Only use TURN when absolutely necessary.
Regional Deployment
Deploy TURN servers close to user populations. This reduces bandwidth costs and improves performance.
Quality Adaptation
Implement adaptive bitrate algorithms that reduce video quality when using TURN relays, minimizing bandwidth consumption.
Usage Analytics
Monitor which network conditions trigger TURN usage. Understanding patterns helps optimize deployment and potentially reduce reliance on TURN.
Shared Infrastructure
For smaller applications, consider using managed TURN services like Twilio, Xirsys, or Cloudflare Calls, which can be more cost-effective than self-hosting.
Performance Optimization
Maximizing TURN server performance ensures good user experiences:
Server Placement
Position TURN servers strategically to minimize latency. Consider major internet exchange points and user concentration areas.
Protocol Selection
Allow clients to try multiple transport protocols. Start with UDP for best performance, falling back to TCP or TLS when necessary.
Load Balancing
Distribute load across multiple TURN servers. Use DNS-based load balancing or application-level server selection.
Resource Monitoring
Continuously monitor CPU, memory, and bandwidth usage. Scale capacity proactively before resource constraints affect users.
Testing TURN Servers
Thorough testing ensures your TURN infrastructure works correctly. You can validate connectivity and credentials quickly with the ICE server tester before rolling changes into production.
Functionality Testing
Verify that the TURN server:
- Accepts allocation requests with proper credentials
- Rejects unauthorized requests
- Successfully relays traffic between peers
- Handles multiple concurrent relays
Performance Testing
Measure:
- Allocation establishment time
- Relay latency
- Maximum concurrent relays
- Bandwidth capacity
- CPU and memory usage under load
Network Condition Testing
Test TURN functionality under various conditions:
- Different NAT types
- Restrictive firewalls
- Packet loss and jitter
- Limited bandwidth
Common TURN Server Issues
Understanding common problems helps diagnose and resolve issues quickly:
Authentication Failures
Often caused by expired credentials, incorrect shared secrets, or mismatched realms. Verify credential generation and transmission.
Port Blocking
Firewalls may block TURN ports. Offer multiple options including TCP on port 443, which is rarely blocked.
Resource Exhaustion
TURN servers running out of ports, bandwidth, or memory. Implement monitoring and capacity planning.
Certificate Issues
TURNS connections failing due to expired or invalid SSL certificates. Maintain current certificates and proper certificate chains.
Best Practices
Follow these best practices for reliable TURN deployments:
- Always Include TURN: Even if most connections succeed with STUN, always configure TURN servers to ensure universal connectivity.
- Multiple Protocols: Support UDP, TCP, and TLS to work through various firewall configurations.
- Credential Expiration: Use short-lived credentials (15-30 minutes) to minimize abuse potential.
- Geographic Redundancy: Deploy TURN servers in multiple regions for better performance and reliability.
- Monitoring and Alerting: Implement comprehensive monitoring to detect issues before they affect users.
- Regular Updates: Keep TURN server software updated to benefit from security patches and performance improvements.
- Capacity Planning: Provision TURN capacity based on expected peak usage plus headroom for growth.
Conclusion
TURN servers are essential for ensuring that WebRTC applications work reliably across all network configurations. While they're more complex and expensive than STUN servers, they're the safety net that guarantees connectivity even in the most restrictive environments.
By understanding TURN server operation, deployment strategies, and best practices, you can build WebRTC applications that maintain high availability and performance for all users, regardless of their network conditions.
Remember that TURN is a fallback mechanism—optimize your application to prefer direct connections while ensuring TURN is available when needed. This balanced approach provides the best user experience at the lowest operational cost.
Check Your Own Servers
Before you trust a TURN relay in production, confirm it allocates a relay candidate with your credentials. Our free tester checks UDP, TCP, and TLS transports so you know the fallback path really works.
Open the Free ICE Server Tester →