1:1 WebRTC voice calls over polled signaling and TURN
webrtcvoipturncoturnsignalingflutter-webrtcpush
A WebRTC call needs three things besides the media itself: a signaling channel to swap
session descriptions (SDP) between the two peers, ICE servers (STUN to learn your public
address, TURN to relay when no direct path exists), and a way to ring a device that is not
looking. None of them needs a WebSocket server. TLDR's v1.63.0 voice calls (1:1, audio only,
Flutter web + Android via flutter_webrtc) use a plain REST table for signaling, coturn on the
same 1 GB VPS, and an FCM push to ring.
Signaling through a polled table
- The API is just a mailbox:
POST /call/signalsstores an opaque blob for a recipient,GET /call/signalsreturns what is waiting,DELETE /call/signals/{callId}clears a call's rows at hangup, and a per-minute cron sweeps anything older than a few minutes. No call history is kept. - Poll slowly while idle (3 s) and fast (800 ms) from the moment a call rings or is placed, and only while the app is in the foreground (see Stop Flutter timers from polling while the app is in the background). A push that arrives in the foreground triggers an immediate poll instead of waiting for the timer.
- Guard the poller against overlap: if a poll is running, set a "poll again" flag instead of starting a second one, and loop until it is clear.
- Drop stale signals by age: an offer older than ~50 s is not a ringing call any more; other signals older than ~2 min are ignored.
- On a small PHP-FPM box, short polling beats long-polling or PHP WebSockets, which would pin worker processes. See Memory thrash and capacity on a 1 GB VPS.
Skip trickle ICE when signaling is slow
Trickle ICE sends each candidate as its own signal as it is discovered. Over a polled mailbox
that is many round trips. Instead, wait for iceGatheringState == complete (capped at ~4 s so a
slow interface cannot stall the call), then send getLocalDescription(), which by then contains
every candidate. One offer and one answer per call.
The signal vocabulary
| signal | direction | meaning |
|---|---|---|
offer |
caller → callee | SDP + the caller's device id; rings the callee |
answer |
callee → caller | SDP + which device picked up |
taken |
caller → callee | another of your devices answered; stop ringing |
decline, busy |
callee → caller | busy = already on a call (sent automatically) |
cancel |
caller → callee | caller hung up before an answer |
hangup |
either | call over |
Multi-device: a user may be signed in on a phone and a browser. Each app run gets a random
device id, every device rings, and the caller sends taken once one device answers. Ring
timeout 45 s.
TURN credentials without user accounts
coturn's use-auth-secret mode (the "TURN REST API" scheme) needs no per-user configuration:
- The API mints a short-lived credential: username = "<expiry-unix>:<random>",
credential = base64(HMAC-SHA1(secret, username)), TTL about 10 minutes.
- coturn holds the same secret as static-auth-secret and rejects expired usernames. Keep the
secret in a server-only config file outside git.
- Return both turn:host:3478?transport=udp and ?transport=tcp; fall back to a public STUN
server if the TURN endpoint fails so a direct path still works.
- The relay only ever sees DTLS-SRTP packets, so it cannot listen in.
Connection state handling
- Start the call timer at
RTCPeerConnectionState.connected, not when the answer arrives. disconnectedis often temporary (Wi-Fi to mobile handoff, a blip). Give it ~12 s to recover before hanging up.failedis final: hang up at once.- Request audio with
echoCancellation,noiseSuppressionandautoGainControlon. - Browsers only play remote audio through a media element. Attaching the remote stream to a
renderer (which creates a hidden
<audio>) is required on web; on Android it plays natively and the renderer is harmless. - Mute =
track.enabled = falseon the local audio track; speakerphone is an Android-only call.
Ringing a device that is not open
- The ring push must be a visible, high-priority notification. A data-only message does not reliably wake a killed or Doze-restricted Android app. See Doze, WorkManager backoff, and background sync that stalls and FCM push notifications from a PHP backend to a Flutter app.
- The ringtone and vibration come from a small native helper over a MethodChannel (system ringtone, ringback tone for the caller); on web, a short Web Audio chime.
- The call UI is an overlay wrapped around the whole router (
MaterialApp.router(builder:)), so a call survives navigation and can shrink to a banner.
End-to-end encryption of signaling
If the signaling blobs are encrypted end to end, the server sees neither the SDP nor the DTLS fingerprint inside it, so it cannot substitute its own fingerprint and man-in-the-middle the media. Details of the key derivation are in Simple E2E messaging with X25519 + HKDF + AES-GCM (and why not Signal).
Testing
Two headless Chrome instances with --use-fake-device-for-media-stream and
--use-fake-ui-for-media-stream can run a full ring, answer, connect and hangup cycle. Log in
by injecting the stored auth token into localStorage rather than driving a login form, which
was flaky. This does not test a real NAT path through TURN or a killed app being woken by the
push; those need real phones on different networks.
When calls ring but never connect
The first real calls between two homes failed six times in a row, two weeks after release.
Signaling was perfect every time (offer, answer, taken), then the callee hung up 10 to 11
seconds after answering: that is ICE timing out, not a signaling bug. The lessons:
- A firewall in front of the host can drop TURN while everything on the host looks right. coturn was running, the host firewall allowed its ports, and a STUN test run on the server succeeded. The hosting provider's cloud firewall (allow 22, 80, 443 TCP and ICMP, drop the rest) silently discarded 3478/udp, 3478/tcp and the relay port range before they reached the machine. A service that listens on new ports needs a rule in every firewall layer; see Setting up an Alma Linux 9 LAMP server.
- Prove where packets die with a sniffer on the server's interface. Send probes from an
outside machine while capturing on the NIC (a raw socket or
tcpdump): probes to port 80 arrived, probes to 3478 never did. Packets that never reach the NIC were dropped upstream; packets that arrive but get no reply are a host problem. Test from outside, never from the server itself. - If your ICE server list is only your own STUN/TURN and it is unreachable, phones gather host candidates only. Calls then connect on the same LAN, or directly over public IPv6 (the likely reason one call between two phones on the same carrier did connect), and nowhere else. That is exactly the set of cases a developer tests first, so the feature looks finished.
- Serve the ICE server list from the API, not from the app. The client asks for it with the TURN credentials before each call, so adding a public STUN server as a stopgap was an API-only change with no app release. With STUN alone, ordinary home NATs can connect directly; symmetric NAT (many carrier and corporate networks) still needs the relay. The tradeoff of a public STUN server is that its operator sees the callers' IP addresses, though never the media or the signaling.
- Plan the firewall rules with the feature: UDP 3478 and TCP 3478 for STUN/TURN plus the
UDP relay range configured in coturn (
min-port/max-port). If no UDP at all is allowed in, moving coturn to an already open port does not help.
coturn settings that bite later:
- denied-peer-ip covering the server's own public address blocks relay-to-relay pairs, which
is the path two clients take when both sit behind symmetric NAT.
- user-quota and total-quota count allocations, not calls. A phone with several network
interfaces, each trying two TURN URLs, uses several allocations per call; quotas of 4 and 12
are tight.
A VoIP call inside an ordinary app also knows nothing about the phone's own calls. Without the
Android telecom framework (a ConnectionService), audio-focus handling or phone-state
listening, a cellular call that arrives mid-call is not coordinated with it: neither call is
held or ended, and Android hands the microphone to the cellular call. See
Writing a replacement phone (dialer) app for Android for the telecom side.
Gotchas
- A two-browser test on one machine proves signaling and the call UI, and nothing about NAT traversal: both peers share a host, so ICE never needs STUN or TURN.
- Without TURN, calls between two phones on carrier networks (symmetric NAT) often fail even though desktop tests on one LAN always work.
- Delete the signal rows when a call ends on both sides, or a late poll can replay an old offer.
- Rate-limit (per sender per minute) and size-limit the signal endpoint, refuse calls to yourself, and honor DM blocks: a blocked user must not be able to ring you.
See also
- Headless Chrome testing gotchas
- Pull-based job queues for agents behind NAT (design)
- TLDR platform architecture (tldrnerd.com)