I got my first computer, a ZX Spectrum 128K, when I was 10. Decades later I'm still doing the same thing: taking something apart to see how it works. This year that something was random video chat, the Omegle-style "press Start, talk to a stranger, press Next" experience.
The result is Chaface, a free random video chat (18+) that runs in the browser and on Android. This post is about the architecture and, more usefully, the bugs. Most WebRTC tutorials stop at "two tabs on localhost can see each other". Real users on 4G, on old phones and pressing Next every two seconds are a different story.
The stack
- Frontend: React + TypeScript (Vite), the browser WebRTC API, Socket.IO client. The Android app is the same web app wrapped with Capacitor.
- Backend: Node.js + Express + TypeScript, Socket.IO for signaling.
- Redis: the matching queues.
- PostgreSQL: users, matches, reports.
- STUN + TURN: public STUN plus my own TURN server (coturn) on the same VPS.
Video and audio never touch my server when a direct connection is possible. The server only does three things: match two people, relay signaling messages between them, and relay media through TURN when the network leaves no other choice.
1. Matching: Redis lists as queues
The core idea is simple: everyone waiting for a partner sits in a Redis list. When you press Start, the server tries to pop someone from a queue. If nobody is there, you get pushed onto it and wait.
const QUEUE_PREFIX = 'matching:queue:'; async function requestMatch(userId: string, countryFilter?: string) { // Try the queues in priority order const candidate = (countryFilter && await tryQueue(QUEUE_PREFIX + countryFilter, userId)) || await tryQueue(QUEUE_PREFIX + 'random', userId); if (candidate) return createMatch(userId, candidate); // Nobody waiting: queue this user const key = QUEUE_PREFIX + (countryFilter ?? 'random'); await redis.rPush(key, userId); // Safety net: never leave ghosts in the queue setTimeout(() => redis.lRem(key, 1, userId), 120_000); return null; } async function tryQueue(key: string, self: string) { const id = await redis.lPop(key); if (id && id !== self) return id; return null; } Two lessons from production:
Country filters can split a small user base into empty rooms. Chaface lets you pick a country. The app preselects your own country, so most people end up waiting in their country's queue. With a modest number of users online, someone in Mexico waiting in the "Mexico" queue and someone in Spain waiting in the "Spain" queue would never see each other, even though both just wanted to talk to someone. The fix was a priority cascade:
- the country you asked for,
- your own country,
- the general queue,
- anyone waiting in any other country's queue.
Step 4 is the one that matters most when few people are online.
Never skip a real person. It sounds obvious, but any fallback logic (a timeout, a retry, a "try another queue") has to run after checking that nobody real is waiting. I had a bug where a fallback path could fire before the queues were checked, so two people could be online and still not meet.
2. Signaling: Socket.IO rooms
WebRTC needs an out-of-band channel to exchange the SDP offer/answer and the ICE candidates. Socket.IO is perfect for that. When two users are matched, both sockets join a room named after the match ID, and the server blindly relays messages to "the other person in the room":
socket.on('webrtc-offer', ({ offer }) => { if (socket.matchId) socket.to(socket.matchId).emit('webrtc-offer', { offer }); }); socket.on('webrtc-answer', ({ answer }) => { if (socket.matchId) socket.to(socket.matchId).emit('webrtc-answer', { answer }); }); socket.on('webrtc-ice-candidate', ({ candidate }) => { if (socket.matchId) socket.to(socket.matchId).emit('webrtc-ice-candidate', { candidate }); }); Bug: both peers sent an offer ("glare")
In my first version, both clients created an offer as soon as they were matched. Sometimes it worked, often it didn't: two offers crossing in flight leave both peers in have-local-offer and nobody answers.
The fix: the server decides who calls. When it creates the match it tells one side isInitiator: true and the other isInitiator: false. Only the initiator calls createOffer(); the other side waits and answers.
socket.emit('match-found', { matchId, isInitiator: true }); partnerSocket.emit('match-found', { matchId, isInitiator: false }); (The "perfect negotiation" pattern is the more general solution, but when a server already sits in the middle, a single flag is simpler and impossible to get wrong.)
3. NAT traversal: why you need your own TURN
const config: RTCConfiguration = { iceServers: [ { urls: 'stun:stun.l.google.com:19302' }, { urls: 'turn:YOUR_TURN_HOST:3478', username: '…', credential: '…' }, // from your backend, see below { urls: 'turn:YOUR_TURN_HOST:3478?transport=tcp', username: '…', credential: '…' }, ], bundlePolicy: 'max-bundle', rtcpMuxPolicy: 'require', }; On desktop Wi-Fi, STUN alone works most of the time. On mobile data it often doesn't: carrier-grade NAT and symmetric NAT break direct connections. Before I added TURN, calls on 4G could end with a black screen on one side.
Three details that mattered:
- Offer TURN over TCP as well as UDP. Some mobile and corporate networks block UDP entirely.
- TURN costs bandwidth, not CPU. Every relayed call goes through your server twice (in and out), so keep an eye on the traffic in your hosting plan.
- Never ship static TURN credentials. My first version had the username and password hardcoded in the frontend, which means anyone could read them from the bundle and use my server as a free relay. Now the backend hands out short-lived credentials (coturn's
use-auth-secret, the "TURN REST API"): the username is an expiry timestamp plus the user ID, and the password is an HMAC of it with a secret that only the server knows.
// Backend (Express): GET /api/turn/credentials, only for signed-in users const expiresAt = Math.floor(Date.now() / 1000) + 12 * 3600; const username = `${expiresAt}:${userId}`; const credential = crypto.createHmac('sha1', process.env.TURN_SECRET!) .update(username) .digest('base64'); res.json({ expiresAt, iceServers: [{ urls: ['turn:YOUR_TURN_HOST:3478'], username, credential }] }); While you're in the coturn config, also add denied-peer-ip rules for private ranges (10.x, 192.168.x, 127.x…). Otherwise your relay can be used to reach machines inside your own network.
4. The "Next" button and race conditions
This is the part no tutorial prepared me for. In random video chat, users skip a lot. Someone can press Next while the previous connection is still sending ICE candidates, or while a track event is about to fire. The result: the previous stranger's video shows up in the new call, or a late ICE candidate is added to the wrong connection.
The fix is a session counter. Every new match increments it, and every WebRTC callback checks that it still belongs to the current session before touching the UI:
const sessionRef = useRef(0); function createPeerConnection(sessionId: number) { const pc = new RTCPeerConnection(config); pc.onicecandidate = (e) => { if (sessionRef.current !== sessionId) return; // stale, ignore if (e.candidate) socket.emit('webrtc-ice-candidate', { candidate: e.candidate }); }; pc.ontrack = (e) => { if (sessionRef.current !== sessionId) return; // stale, ignore setRemoteStream(e.streams[0]); }; return pc; } function onMatchEnded() { sessionRef.current++; // bump FIRST, then clean up // close pc, reset state, maybe search again… } Bumping the counter before the cleanup is important: callbacks already queued from the dying connection become no-ops immediately.
5. Recovering from bad networks
Phones switch from Wi-Fi to 4G, lifts kill the signal, trains go through tunnels. Two rules:
pc.oniceconnectionstatechange = () => { if (pc.iceConnectionState === 'disconnected') { // Often temporary: give it a few seconds, then try an ICE restart setTimeout(() => { if (['disconnected', 'failed'].includes(pc.iceConnectionState)) pc.restartIce(); }, 5000); } if (pc.iceConnectionState === 'failed') { endMatch(); findNextMatch(); // don't leave the user staring at a frozen frame } }; -
disconnectedis often temporary. Wait a bit and tryrestartIce()before giving up. -
failedis final. End the match and automatically search again. For a random chat, a new partner is a better experience than an error message.
Bug: alert() killed the socket on mobile
My early error handling used alert(). On mobile browsers it blocks the event loop, Socket.IO misses its heartbeats, and the server thinks you've disconnected. The user closes the alert and finds themselves logged out of the queue. Never block the main thread in a real-time app: use non-blocking UI for errors.
6. Safety is part of the architecture
A random video chat with no safety measures quickly becomes unusable, so I treated it as a core feature and not an add-on:
- 18+ only, sign-in with Google. No anonymous throwaway accounts, so bans actually stick.
- Report button in every chat. Reported content is reviewed with the help of AI moderation, and repeat offenders are banned.
- Users can skip instantly, without explaining anything.
I won't go into the details of the moderation pipeline (it's a cat-and-mouse game), but the lesson is: design for it from day one.
What I'd tell myself on day one
- Test on real mobile data early. Localhost and office Wi-Fi hide all the hard problems.
- Let the server decide who sends the offer.
- Run your own TURN, with TCP enabled and short-lived credentials.
- Assume every callback can arrive late, and guard it with a session ID.
- Make the queue logic generous. With few users, every person waiting is precious: never let a filter or a fallback leave two people alone.
If you want to see the result, Chaface is free at chaface.com and on Google Play. And if you've built something with WebRTC, I'd love to hear which bug taught you the most. Let me know in the comments.
