惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

博客园 - 三生石上(FineUI控件)
Martin Fowler
Martin Fowler
月光博客
月光博客
AI
AI
B
Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
C
CXSECURITY Database RSS Feed - CXSecurity.com
WordPress大学
WordPress大学
GbyAI
GbyAI
L
Lohrmann on Cybersecurity
O
OpenAI News
Schneier on Security
Schneier on Security
P
Palo Alto Networks Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
T
Troy Hunt's Blog
V2EX - 技术
V2EX - 技术
W
WeLiveSecurity
L
LINUX DO - 最新话题
人人都是产品经理
人人都是产品经理
S
Security Affairs
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
A
Arctic Wolf
Recorded Future
Recorded Future
Microsoft Security Blog
Microsoft Security Blog
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
G
GRAHAM CLULEY
N
Netflix TechBlog - Medium
TaoSecurity Blog
TaoSecurity Blog
C
Check Point Blog
Scott Helme
Scott Helme
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Apple Machine Learning Research
Apple Machine Learning Research
PCI Perspectives
PCI Perspectives
www.infosecurity-magazine.com
www.infosecurity-magazine.com
Vercel News
Vercel News
The Hacker News
The Hacker News
Y
Y Combinator Blog
Latest news
Latest news
SecWiki News
SecWiki News
Hugging Face - Blog
Hugging Face - Blog
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Google Online Security Blog
Google Online Security Blog
Webroot Blog
Webroot Blog
Google DeepMind News
Google DeepMind News
Recent Commits to openclaw:main
Recent Commits to openclaw:main
C
Cisco Blogs
博客园_首页
H
Hackread – Cybersecurity News, Data Breaches, AI and More
宝玉的分享
宝玉的分享
L
LINUX DO - 热门话题

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
How we connect two strangers' webcams fast (and keep the TURN bill small)
Camdiv · 2026-05-26 · via DEV Community

Camdiv matches you with a random stranger and puts you both on live video. I wrote separately about the genuinely hard part, which is moderation. This post is about the part people assume is hard and mostly isn't: getting two browsers to see and hear each other. WebRTC handles the media. The interesting work lives around it.

Think about the clock the user feels. They click Start, then they wait, staring at their own face, until a stranger appears. Every millisecond in that gap is something we have to earn back: finding a partner, telling both browsers about each other, negotiating a peer connection, and punching through whatever router or firewall each person sits behind. Four problems, and all of them are latency.

The whole path looks like this:

diagram

Step one: find a partner fast

Matching is the first place you can blow the latency budget, and the easiest place to over-engineer. The instinct is to reach for a database or a Redis sorted set and query it on every request. We don't. The matching queues live in memory, in the Node process.

When you click Start, the server first checks whether anyone is already waiting for your chat type (video, audio, or text). If someone is, you're paired on the spot and a room is created. If nobody's there, you go into an in-memory queue, and a loop running every 200ms does a greedy pass over that queue pairing people off. The worst case for a waiting user is a couple hundred milliseconds, not a network round trip to a datastore.

diagram

Redis is in the picture, but as a backup, not the source of truth. The in-memory queue is authoritative; Redis gets a best-effort copy in the background so a restart doesn't strand everyone, and so we can add a second server later without rewriting matching. Today it runs as a single instance, and the code says so out loud: the queues are the source of truth, single-instance assumption noted right there in the comment. I like comments that admit their assumptions. The day we scale out, that comment is the first thing the next person needs to read.

One thing that's easy to miss until it bites you: the partner you just matched can vanish in the same instant you matched them. Closed tab, dropped wifi, whatever. So before either side is told about the match, the server checks both sockets are alive, mutates the chat state, then checks again that both are still connected. If one disappeared, the survivor doesn't get dumped onto a dead screen. They go straight back into matchmaking. Getting matched with a ghost is one of the worst feelings on an app like this, and most of avoiding it is just being paranoid at the right three lines of code.

Step two: signaling is a dumb relay, on purpose

Once two people are matched, their browsers need to swap connection details: an SDP offer, an answer, and a stream of ICE candidates (the possible network routes each side can be reached on). That exchange rides over the Socket.IO connection each client already has open.

The backend's job here is almost nothing, and that's the point. It relays. An offer from A gets forwarded to B, B's answer comes back to A, ICE candidates trickle across in both directions. The server never parses SDP, never touches media, never becomes part of the conversation. It's a switchboard.

The one optimization on this path is a hot cache. Every signaling packet has to find the recipient's socket by user id, and a Redis lookup for each one would pile latency onto the busiest path in the app. So there's a plain in-memory map from user id to socket id, checked first, with the slower lookup only as a fallback.

There's a classic WebRTC trap here called glare: if both peers create an offer at the same moment, the negotiation collides. Our fix is boring and cheap. A deterministic tiebreak from the two peers' ids decides which side sends the offer; the other waits to answer. It isn't the full "perfect negotiation" pattern from the spec, and I'd reach for that if we did a lot of mid-call renegotiation. We don't. Each match is a fresh connection, so a deterministic initiator is enough to keep the two sides from talking over each other.

When a connection does drop into the failed state, the client calls restartIce() rather than tearing everything down. That re-gathers routes and often recovers a connection that only hiccuped, with the user seeing nothing worse than a brief freeze.

Step three: ICE without drowning in candidates

This is the part that actually decides whether a connection feels instant or takes three seconds, and where I learned the most counterintuitive lesson.

WebRTC connects peers directly when it can. To do that it gathers candidates (network paths) and tries them. STUN servers help a browser discover its own public address, so two people behind ordinary home routers can talk directly. That covers most users: in our experience roughly 80 to 85 percent connect peer to peer with STUN alone, no relay involved. We point at Google's and Cloudflare's public STUN servers for that.

The rest sit behind strict NATs or corporate firewalls that won't allow a direct path. Those need a TURN server, which relays the media for them. We run our own coturn servers in three regions (New York, Amsterdam, Singapore), and the backend hands each client a TURN config when they ask for one.

Here's the counterintuitive bit. You'd think handing the browser more TURN servers gives it more chances to connect. For speed, the opposite is true. Every TURN server you list multiplies the candidates the browser has to gather and test, and ICE won't settle until it has worked through them. So we don't return all three regions. The backend geo-locates the client by IP and returns the two closest, and only those. Fewer candidates, faster gathering, faster connection. The comment in the code is blunt about it: fewer TURN servers means fewer ICE candidates means faster pairing.

Each TURN server is offered on a few transports, and one of them earns its keep: TURN over TLS on port 443. To a firewall that looks exactly like HTTPS, so it slips through corporate and school networks that block everything else. Plain UDP is tried first because it's lower latency, and 443 is the fallback that decides whether a locked-down network connects at all.

TURN credentials, without leaving the door open

A TURN server that relays media for anyone is a free bandwidth piñata. So you can't hardcode a username and password in the client where anyone can read them out of the network tab.

Instead the credentials are short-lived and computed. The backend shares a secret with the coturn servers. When a client asks, the backend builds a username that is really an expiry timestamp, then signs it with HMAC to produce the password. coturn runs the same signature check and honors the credential until it expires, which for us is 24 hours. Nothing reusable ever sits in the client, and a credential someone scrapes today is dead weight tomorrow.

The client caches that config for six hours and dedupes concurrent fetches, so a page that mounts three things asking for ICE servers still makes one request. If the backend is unreachable, the client falls back to STUN-only, which still connects that 80-something percent. The credential fetch has a five second timeout, because TURN is worth waiting a beat for when you happen to be one of the people who genuinely needs it.

Staying connected on bad networks

Connecting once isn't the job. People walk out of wifi range, switch from wifi to cellular, step into elevators. Two things help.

On the server side, coturn runs with mobility enabled, so a relayed session can survive the client's network changing underneath it. On the client side, the failed-state ICE restart from earlier re-gathers routes and reconnects without rebuilding the whole session.

It isn't magic. A hard network change on a direct peer-to-peer connection can still drop the call, and then you land back in matchmaking. But matchmaking is fast, so the trip from "lost them" to "talking to someone new" is a couple of seconds, which is about as good as this format gets.

The bill

Here's the thing the WebRTC tutorials skip: relays cost money, because they move real bytes. Direct peer-to-peer is free to us, since the media never touches our servers. TURN traffic does touch them, at video bitrates.

The math is what makes the whole format viable. Because only the ~15 percent who can't go direct ever hit a relay, three small droplets are enough. Each coturn box is capped at a few Mbps per session and a few hundred concurrent users, and the three regions together run around twenty dollars a month. If our direct-connect rate fell, that number would climb fast. So the STUN-first, fewest-candidates approach pays off twice: connections settle quicker, and the relay bill stays small.

What I'd flag if you're building this

  • A single signaling instance is fine until it isn't. The Redis backup means scaling out is a config change rather than a rewrite, but we haven't had to prove that under load yet.
  • The deterministic-initiator trick is enough for fresh one-to-one calls. The moment you renegotiate mid-call, say to add screen share, budget time for proper perfect negotiation instead.
  • Geo-selection is only as good as your IP database. It's right the large majority of the time and occasionally wrong, and a wrong guess costs a slightly slower connect, not a broken one. Acceptable trade.
  • Watch your direct-connect percentage closely. It's the single number that sets your TURN bill and your connect speed at the same time.

WebRTC gets framed as the hard part of building something like this. Once it works, it mostly keeps working, and the real effort goes into what sits on either side of it: pairing people in milliseconds, relaying their handshake without becoming a bottleneck, and getting through the messy reality of home and office networks without paying to relay everyone. If you want to see it from the user's side, it's live at Camdiv.

The in-memory matchmaking call and the fewest-TURN-candidates trick are the two I'd most happily defend in the comments.