Building Private Live Video Infra: How to Configure a VPS as a LiveKit WebRTC SFU Media Server for Mobile Apps
Introduction: The Shift to Self-Hosted WebRTC Infrastructure
In the era of real-time communication, integrating voice and video capabilities into mobile applications has shifted from a premium luxury to a core user expectation. Whether you are building a collaborative enterprise tool, a telemedicine platform, or an interactive social application, real-time engagement is paramount. However, developers frequently encounter a strategic fork in the road: rely on expensive commercial Communications Platform as a Service (CPaaS) vendors with unpredictable per-minute pricing, or architect a self-hosted solution.
For engineering teams prioritizing data sovereignty, predictable infrastructure costs, and deep architectural control, self-hosting is the definitive choice. This technical guide provides a comprehensive blueprint for configuring a Virtual Private Server (VPS) as a LiveKit WebRTC SFU (Selective Forwarding Unit) Media Server. By the end of this article, you will understand how to establish a robust, self-hosted media infrastructure tailored specifically to handle the networking nuances of mobile applications.
Understanding the Architecture: Why LiveKit and SFU?
Before diving into server configuration, it is essential to understand the underlying topology. Early WebRTC implementations relied heavily on a Mesh network (Peer-to-Peer), where every participant sends their media streams directly to every other participant. While efficient for one-on-one calls, Mesh network topology scales poorly; a four-person call forces a mobile device to encode and upstream three identical copies of its video, quickly draining the battery and saturating mobile bandwidth.
An SFU (Selective Forwarding Unit) architecture solves this limitation. In an SFU model, each participant uploads their media stream exactly once to the central media server. The server then routes and forwards those streams to the other participants without re-encoding them. This dramatically reduces the CPU and bandwidth overhead on the client side, making it ideal for mobile devices operating on constrained mobile data networks.
Why Choose LiveKit over Alternatives?
While legacy options like Janus, Jitsi, or Kurento are widely known, LiveKit has rapidly become the modern standard for WebRTC media servers. It offers several distinct operational advantages:
- Go-Based Performance: Built on Go, LiveKit delivers exceptional concurrency management and minimal memory overhead compared to Java or C++ alternatives.
- First-Class Mobile SDKs: LiveKit provides native, highly optimized SDKs for iOS (Swift), Android (Kotlin), Flutter, and React Native, abstracting away complex WebRTC state machines.
- Built-in JWT Authentication: Security is deeply integrated out of the box, utilizing JSON Web Tokens (JWT) to manage access control down to individual participant permissions.
- Robust Reconnection Logic: Essential for mobile apps experiencing fluctuating signal strengths between Wi-Fi and cellular networks (5G/LTE).
Prerequisites and VPS Provisioning
To ensure optimal real-time performance with minimal jitter and packet loss, your hosting environment must meet specific baseline requirements. We recommend selecting a developer-centric cloud provider such as DigitalOcean, Linode (Akamai), Vultr, or AWS EC2.
Minimum Hardware Specifications
- CPU: 2 vCPUs (Compute-optimized instances are strongly preferred, as WebRTC packet routing is highly CPU-bound).
- RAM: 4 GB RAM.
- Operating System: Ubuntu 22.04 LTS or Ubuntu 24.04 LTS.
- Network: 1 Gbps port with unmetered or generous bandwidth allocations.
DNS and Network Prerequisites
Before initiating software installation, ensure you have configured the following:
- A fully qualified domain name (FQDN) pointing to your VPS public IPv4 address (e.g.,
livekit.yourdomain.com). - An open, unrestricted firewall policy on your cloud provider's dashboard that permits custom UDP and TCP traffic ranges.
Step-by-Step Server Configuration
Step 1: System Optimization and Kernel Tuning
WebRTC servers handle a massive volume of concurrent network sockets and UDP packets. By default, standard Linux distributions are tuned for web servers (HTTP traffic) and will choke under high WebRTC throughput. We must modify the system limits and kernel parameters.
Connect to your VPS via SSH and append the following parameters to the /etc/sysctl.conf file to increase network buffer sizes and connection limits:
# Optimize network stack for WebRTC SFU fs.file-max = 2097152 net.core.rmem_max = 16777216 net.core.wmem_max = 16777216 et.core.rmem_default = 16777216 et.core.wmem_default = 16777216 et.core.somaxconn = 4096 et.ipv4.udp_rmem_min = 16384 et.ipv4.udp_wmem_min = 16384
Apply the changes immediately by executing the following command:
sudo sysctl -p
Next, increase the security limits for open files by editing /etc/security/limits.conf and adding these lines at the bottom of the file:
* soft nofile 65535 * hard nofile 65535
Step 2: Firewall and Port Allocation
LiveKit requires specific ports to be completely open to the public internet for signaling, media transit, and automated SSL certificate generation. Configure your system firewall (using UFW) with the following commands:
sudo ufw allow 22/tcp sudo ufw allow 80/tcp sudo ufw allow 443/tcp sudo ufw allow 7880/tcp sudo ufw allow 7881/tcp sudo ufw allow 50000:60000/udp sudo ufw enable
Note: The port range 50000-60000/udp is critical; this is the dynamic allocation pool where actual WebRTC audio and video data streams flow between your mobile clients and the SFU server.
Step 3: Deploying LiveKit via Docker Compose
While a bare-metal binary installation is possible, utilizing Docker and Docker Compose ensures isolation, easily repeatable deployments, and straightforward version upgrades. First, ensure Docker and Docker Compose are installed on your Ubuntu system.
Create a dedicated directory for your infrastructure and generate your deployment configuration:
mkdir -p /opt/livekit && cd /opt/livekit
LiveKit provides an official, interactive setup tool that generates optimal configuration files automatically. Run the initialization script via Docker:
docker run --rm -it -v$PWD:/output livekit/generate
The interactive CLI tool will prompt you for several inputs. Provide the following accurate information:
- Domain Name: Enter your FQDN (e.g.,
livekit.yourdomain.com). - LiveKit Version: Select the latest stable version.
- SSL Management: Choose "Let's Encrypt" for automated, free SSL generation and renewal.
- Turn Server: Enable "embedded TURN". This is highly critical for mobile apps, as it allows users behind restrictive corporate firewalls or carrier NATs to successfully fall back to TCP/TLS mode when standard UDP is blocked.
Once completed, the generator creates several files in your directory, including livekit.yaml (the primary configuration file) and a production-ready docker-compose.yaml.
Step 4: Analyzing and Launching the LiveKit Configuration
Open your generated livekit.yaml to review its structural components. It should align with the following production architecture pattern:
port: 7880
bind_addresses:
- ""
rtc:
tcp_port: 7881
udp_port_range:
start: 50000
end: 60000
use_external_ip: true
turn:
enabled: true
domain: livekit.yourdomain.com
tls_port: 5349
udp_port: 3478
keys:
API_KEY_HERE: API_SECRET_HERESecurely document your generated API_KEY and API_SECRET. These credentials will be used exclusively by your backend application server to generate access tokens for your mobile clients.
Launch your media server infrastructure in detached mode using Docker Compose:
docker compose up -d
Verify that all containers are operating successfully by running docker compose ps. Your server is now actively listening for secure WebRTC connections.
Optimizing for Mobile Clients
Mobile applications present unique operating constraints that traditional web apps do not face. To provide an enterprise-grade experience on native iOS and Android apps, your LiveKit infrastructure must be optimized to handle unpredictable device conditions.
1. Adaptive Stream Management and Simulcast
Mobile screens vary greatly in resolution, and cellular connections fluctuate constantly. It is highly inefficient to send a 1080p high-definition video stream to a mobile device on a weak LTE connection or a small screen interface. LiveKit supports Simulcast out of the box. Ensure your mobile client application publishes video with Simulcast enabled. This forces the mobile app to send three distinct layers of video (Low, Medium, High resolution) to your VPS. The LiveKit SFU dynamically drops or upgrades the resolution layer sent to receiving participants based on their instantaneous real-time network download capacity.
2. Audio-Only Fallbacks and Connection Resiliency
When a mobile user drives through a tunnel or enters an area with poor coverage, packet loss spikes. LiveKit handles this automatically via built-in connection recovery loops. On your mobile client implementation, you should listen to network state transitions and explicitly utilize LiveKit's client-side configurations to automatically pause incoming video tracks while preserving audio streams when bandwidth drops below a sustainable threshold.
---Conclusion and Verification
Establishing a self-hosted WebRTC SFU Media Server provides complete ownership of your data, exceptional latency characteristics, and a predictable, low-cost operational model. By pairing a high-performance VPS instance with LiveKit's modern architecture, you bypass the structural complexities of legacy systems while matching the capabilities of commercial alternatives.
To verify your newly deployed infrastructure, visit the official LiveKit Connection Tool (livekit.io/connection-test) and enter your server URL (wss://livekit.yourdomain.com) along with a valid token generated using your API credentials. Once validated, your private realtime infrastructure is fully prepared to power production-ready video, audio, and screen-sharing experiences across your mobile application ecosystem.
