Inkpost, home
Inkpost cover: the title "One IP for the whole world" and "Anycast to join. Unicast for every call." beside a globe where five sites share 203.0.113.10 and a user in Delhi joins via Mumbai, pinned to bom-sfu-1 at 198.51.100.11.

Advanced development · Performance tuning

One IP for the whole world: anycast to join, unicast for every call

How to build a Zoom-style backend that everyone reaches through one anycast IP, pins each call to a nearby unicast SFU, relays between regions over a private backbone and fails over in seconds. BIRD, mediasoup, coturn, NATS and Redis, every config spelled out (all dummies).

Suman AcharyyaVerified@sumanacharyya999

23 min read

Put a video call's only server in Virginia and the people in Virginia are happy. Everyone in Delhi, Jakarta or Melbourne talks over each other, because every word crosses half the planet twice. The fix sounds simple: one IP address that answers from the nearest data center, everywhere. That is anycast. This post builds the whole system around it: the BGP announcements, the join service, the media servers, TURN, the relay between regions, the failover and the scaling, with every package, config and secret written out.

Why one server, or one IP per server, breaks down

Light in fiber is fast but not instant. From Delhi to a server in Virginia and back is often more than 200 ms before the server does any work, and a call pays that for every packet, in both directions. Past a couple of hundred milliseconds, conversations turn into walkie-talkie turns.

So you add servers in Mumbai, Frankfurt, Singapore and Sydney, each with its own IP. Now every client needs to know which one to use. A list of 40 zone names in DNS grows with every region. GeoDNS answers by the location of the user's DNS resolver, which is a good guess, not a measurement, and when a site dies, clients keep the cached answer until its TTL runs out.

Approach

How a user reaches a server

When a server or site fails

One central server

One IP in one place

Everyone is down; far users are always slow

One IP per server

The client or DNS picks from a list

Each client has to notice and switch

GeoDNS

DNS answers by the resolver's location

Clients wait for the cached answer to expire

Anycast for everything

BGP sends each user to the nearest announcer

Routes move in seconds, but a route change can move a live call

Anycast to join, unicast for media

Anycast for the join request; the call itself goes to one unicast SFU

The client rejoins through anycast and lands on a healthy site

The design: join on anycast, stay on unicast

Users in Delhi, Jakarta, Frankfurt, New York and Melbourne all open meet.example.com; BGP sends each to the nearest PoP (bom, sin, fra, iad, syd), all answering on 203.0.113.10, and each PoP pins media to its own unicast SFU.
Anycast gets every user to the nearest site; the call itself then sticks to one unicast media server.

Every site (a PoP, point of presence) announces the same prefix, 203.0.113.0/24, to its upstream networks over BGP. Routers everywhere keep the shortest path, so meet.example.com, which resolves to 203.0.113.10 all over the world, lands in Mumbai for Delhi and in Singapore for Jakarta. If a site stops announcing, routers forget that path within seconds and traffic moves to the next nearest site. That is perfect for a short HTTPS request and risky for a 40-minute call, which is why the call itself never uses the anycast address.Source [1]

especially for long running flows, there are potential failure modes using anycast

RFC 4786, "Operation of Anycast Services", section 4.1

  1. The browser calls POST https://meet.example.com/v1/rooms/<room>/join with the user's sign-in token. BGP delivers it to the nearest PoP.

  2. The edge in that PoP checks the token, records the room's home region (the first joiner's) and picks the least-loaded media server (SFU) in its own region.

  3. It answers with a ticket: the SFU's unicast address (for Mumbai, wss://bom-sfu-1.meet.example.com on 198.51.100.11), a 60-second media token that only that SFU accepts, and TURN credentials for the region.

  4. The browser opens the SFU's WebSocket and sends audio and video to that one unicast address. This is the pin: no route change on the internet can move it.

  5. If people in other regions are in the same room, the SFUs relay each stream once per region over a private backbone (the cascade).

  6. If the SFU or the whole PoP goes away, the browser simply joins again through anycast and gets a new pin in a healthy place.

Transcript
A video call needs every packet to arrive fast. One server far away makes most of the world slow. From Delhi to a server in Virginia and back is often more than 200 ms, for every packet. Adding servers with their own IPs means every client must pick one, and DNS can only guess. With anycast, every site announces the same IP, and the internet routes each user to the nearest one. Routes can move in seconds. That's great for joining a call, and risky for staying in one. So the join request uses anycast, and the call is pinned to one unicast media server. When a room spans regions, servers relay each stream once over a private backbone. If anything fails, the client joins again through anycast and gets a new pin. One IP, the whole world.

1. What runs where, and what to install

  • Edge (every PoP, on the anycast IP 203.0.113.10): Caddy for TLS and a small Fastify join service. It never touches media.

  • SFU nodes (every PoP, each on its own unicast IP): mediasoup, one worker per CPU core.

  • TURN (every PoP, unicast): coturn, for users behind strict firewalls.

  • Routing (every PoP): BIRD 2 announces the anycast prefixes and a health check withdraws them.

  • Shared state: Redis for SFU load and room ownership, NATS for messages between SFUs in different regions.

  • Backbone: WireGuard tunnels (10.42.0.0/16) between PoPs, used only for SFU-to-SFU relays.

# On every PoP host (Ubuntu 24.04 LTS)sudo apt-get updatesudo apt-get install -y bird2 coturn wireguard-tools redis-tools caddy curlsudo ip addr add 203.0.113.10/32 dev lo        # the anycast service IP (dummy)# Node.js 22 LTS services: edge (join) and SFU# mediasoup builds or downloads its C++ worker on install: keep python3, make and g++ availablesudo apt-get install -y python3 python3-pip make g++npm install mediasoup@3.32.2 fastify@5.12.8 @fastify/websocket@11.3.7 \  ioredis@6.0.0 jose@6.2.18 nats@2.29.3 zod@4.6.7 prom-client@15.1.3npm install -D typescript @types/node# Browser appnpm install mediasoup-client@3.26.0# One Ed25519 key pair for media tickets: private key on edges, public key on SFUsopenssl genpkey -algorithm ed25519 -out media-token.keyopenssl pkey -in media-token.key -pubout -out media-token.pub

2. Announce one IP from every PoP

You need your own AS number and a provider in each region that will run a BGP session with you, plus an IPv4 /24 and an IPv6 /48: most networks drop anything more specific than that. Put the service address on the loopback interface (ip addr add 203.0.113.10/32 dev lo) and let BIRD announce the whole /24 from every PoP. Register a ROA (Route Origin Authorization) in RPKI for both prefixes, so networks that validate routes ignore anyone else who announces them.Source [2]Source [3]

# /etc/bird/bird.conf on the Mumbai PoP (all values are dummies)
log syslog all;
router id 198.51.100.11;

define OUR_ASN = 64500;                       # documentation ASN; use your own
define ANYCAST4 = [ 203.0.113.0/24 ];
define ANYCAST6 = [ 2001:db8:4b00::/48 ];

protocol device { scan time 10; }

# The prefixes we announce. The real service IP (203.0.113.10) sits on lo;
# these routes exist only inside BIRD so BGP has something to export.
protocol static anycast4 {
  ipv4;
  route 203.0.113.0/24 blackhole;
}
protocol static anycast6 {
  ipv6;
  route 2001:db8:4b00::/48 blackhole;
}

filter only_anycast4 { if net ~ ANYCAST4 then accept; reject; }
filter only_anycast6 { if net ~ ANYCAST6 then accept; reject; }

protocol bgp upstream4 {
  description "Transit, Mumbai";
  local 198.51.100.11 as OUR_ASN;
  neighbor 192.0.2.1 as 64496;
  multihop 2;
  password "dummy-bgp-md5-secret";
  hold time 9;                              # fail over in seconds, not minutes
  ipv4 { import none; export filter only_anycast4; };
}

protocol bgp upstream6 {
  description "Transit, Mumbai (v6)";
  local 2001:db8:ffff::11 as OUR_ASN;
  neighbor 2001:db8:ffff::1 as 64496;
  multihop 2;
  password "dummy-bgp-md5-secret";
  hold time 9;
  ipv6 { import none; export filter only_anycast6; };
}

A PoP must stop announcing the moment it can't serve, or anycast keeps sending people into a dead site. This small loop does that: three failed checks withdraw both prefixes, five good ones bring them back, so one slow second doesn't flap routes across the internet.

#!/usr/bin/env bash# /usr/local/bin/anycast-health: announce 203.0.113.0/24 only while this PoP can serve.# Runs as a systemd service (Restart=always). Withdraws after 3 failed checks,# re-announces after 5 good ones, so a flapping box doesn't flap the internet.set -uo pipefailCHECK_URL="http://127.0.0.1:8080/healthz"FAILS_TO_WITHDRAW=3OKS_TO_ANNOUNCE=5state="up"; fails=0; oks=0announce() { birdc -s /run/bird/bird.ctl "$1" anycast4 >/dev/null; birdc -s /run/bird/bird.ctl "$1" anycast6 >/dev/null; }while true; do  # Healthy = edge answers AND at least one local SFU has a fresh heartbeat.  if curl -fsS --max-time 1 "$CHECK_URL" >/dev/null \     && [ "$(redis-cli -u "${REDIS_URL:-redis://127.0.0.1:6379}" zcount "sfu:load:${POP_REGION:-bom}" 0 999999)" -gt 0 ]; then    oks=$((oks + 1)); fails=0  else    fails=$((fails + 1)); oks=0  fi  if [ "$state" = "up" ] && [ "$fails" -ge "$FAILS_TO_WITHDRAW" ]; then    announce disable; state="down"; logger -t anycast "withdrew anycast routes after $fails failed checks"  elif [ "$state" = "down" ] && [ "$oks" -ge "$OKS_TO_ANNOUNCE" ]; then    announce enable; state="up"; logger -t anycast "re-announced anycast routes"  fi  sleep 1done

3. Mint a pinned ticket at the edge

The join service is the only thing on anycast. It verifies the user, stores which region owns the room, picks an SFU from the load scores the SFUs publish every 2 seconds and signs a 60-second Ed25519 token whose audience is that one node. TURN credentials follow the TURN REST API pattern: the username is an expiry time plus the user ID, and the password is an HMAC of it with a secret only the edge and coturn know, so nothing needs a database lookup.Source [4]

// edge/join.ts: runs on every anycast PoP behind 203.0.113.10.// It never carries media. It picks a unicast SFU and hands back a pinned ticket.import Fastify from "fastify";import { Redis } from "ioredis";import { SignJWT, jwtVerify, createRemoteJWKSet, importPKCS8 } from "jose";import { createHmac } from "node:crypto";import { z } from "zod";const env = z.object({  POP_REGION: z.enum(["iad", "fra", "bom", "sin", "syd"]),  REDIS_URL: z.string().url(),  AUTH_JWKS_URL: z.string().url(),  MEDIA_TOKEN_PRIVATE_KEY: z.string(), // Ed25519, PKCS#8 PEM  TURN_SHARED_SECRET: z.string().min(32),  TURN_HOST_TEMPLATE: z.string(),      // "turn-{region}.meet.example.com"}).parse(process.env);const redis = new Redis(env.REDIS_URL);const userJwks = createRemoteJWKSet(new URL(env.AUTH_JWKS_URL));const mediaKey = await importPKCS8(env.MEDIA_TOKEN_PRIVATE_KEY, "EdDSA");const HEARTBEAT_MAX_AGE_MS = 6_000;// Pick the least-loaded SFU in this region whose heartbeat is fresh and that isn't draining.async function pickSfu(region: string): Promise<{ id: string; url: string } | null> {  const ids = await redis.zrange(`sfu:load:${region}`, "0", "9"); // lowest load first  for (const id of ids) {    const node = await redis.hgetall(`sfu:node:${id}`);    const fresh = Date.now() - Number(node.seenAt ?? 0) < HEARTBEAT_MAX_AGE_MS;    if (fresh && node.draining !== "1" && node.url) return { id, url: node.url };  }  return null;}// TURN REST API style credentials: username = expiry:userId, password = base64(HMAC-SHA1).function turnCredentials(userId: string, region: string, ttlSeconds = 3_600) {  const username = `${Math.floor(Date.now() / 1000) + ttlSeconds}:${userId}`;  const credential = createHmac("sha1", env.TURN_SHARED_SECRET).update(username).digest("base64");  const host = env.TURN_HOST_TEMPLATE.replace("{region}", region);  return [    { urls: [`turn:${host}:3478?transport=udp`, `turns:${host}:443?transport=tcp`], username, credential },  ];}const app = Fastify({ logger: true });app.get("/healthz", async () => ({ ok: true, region: env.POP_REGION }));app.post<{ Params: { roomId: string } }>("/v1/rooms/:roomId/join", async (req, reply) => {  const bearer = req.headers.authorization?.replace(/^Bearer /, "") ?? "";  const { payload } = await jwtVerify(bearer, userJwks, { audience: "meet.example.com" });  const userId = String(payload.sub);  const { roomId } = req.params;  // The first joiner decides the room's home region; everyone else learns it.  await redis.set(`room:home:${roomId}`, env.POP_REGION, "EX", 86_400, "NX");  const homeRegion = (await redis.get(`room:home:${roomId}`)) ?? env.POP_REGION;  await redis.sadd(`room:regions:${roomId}`, env.POP_REGION);  await redis.expire(`room:regions:${roomId}`, 86_400);  const sfu = await pickSfu(env.POP_REGION);  if (!sfu) return reply.code(503).send({ error: "no_capacity", retryAfterMs: 1_000 });  // The pin: a short-lived ticket that only this SFU node accepts.  const mediaToken = await new SignJWT({ roomId, homeRegion, region: env.POP_REGION })    .setProtectedHeader({ alg: "EdDSA", kid: "media-2026-11" })    .setSubject(userId)    .setAudience(`sfu:${sfu.id}`)    .setIssuedAt()    .setExpirationTime("60s")    .sign(mediaKey);  return {    sfu: { id: sfu.id, url: sfu.url },    mediaToken,    region: env.POP_REGION,    homeRegion,    iceServers: turnCredentials(userId, env.POP_REGION),  };});await app.listen({ host: "127.0.0.1", port: 8080 }); // Caddy terminates TLS on 203.0.113.10:443
POP_REGION=bom
REDIS_URL=rediss://default:dummy-redis-password-7c1e@redis-bom.internal.example.com:6380
NATS_URL=nats://10.42.0.10:4222
AUTH_JWKS_URL=https://auth.example.com/.well-known/jwks.json
MEDIA_TOKEN_PRIVATE_KEY="-----BEGIN PRIVATE KEY-----\nMC4CAQAwBQYDK2VwBCIEIDUMMYdummyDUMMYdummyDUMMYdummyDUMMYdummy\n-----END PRIVATE KEY-----"
MEDIA_TOKEN_PUBLIC_KEY="-----BEGIN PUBLIC KEY-----\nMCowBQYDK2VwAyEADUMMYdummyDUMMYdummyDUMMYdummyDUMMYdummyDUM=\n-----END PUBLIC KEY-----"
TURN_SHARED_SECRET=dummy-turn-shared-secret-0f9c2b7e4a1d
TURN_HOST_TEMPLATE=turn-{region}.meet.example.com
SFU_NODE_ID=bom-sfu-1
SFU_PUBLIC_IP=198.51.100.11
SFU_PUBLIC_URL=wss://bom-sfu-1.meet.example.com
BACKBONE_IP=10.42.3.11
BGP_MD5_PASSWORD=dummy-bgp-md5-secret

4. Run the SFU on unicast

Each media server runs one mediasoup worker per CPU core, and each worker owns one WebRtcServer on a single UDP and TCP port, which keeps the firewall to 4 UDP and 4 TCP ports on a 4-core box instead of thousands. A room is one router on one worker; a worker handles roughly 500 consumers (one person receiving one track) before it needs help. Every 2 seconds the node writes its load to Redis, and a node marked as draining scores 1,000,000,000, so the edge stops sending new people to it.Source [5]

// sfu/node.ts: one per media server, on a UNICAST address (e.g. bom-sfu-1 = 198.51.100.11).import * as mediasoup from "mediasoup";import type { types } from "mediasoup";import { Redis } from "ioredis";import { cpus } from "node:os";const NODE_ID = process.env.SFU_NODE_ID ?? "bom-sfu-1";const REGION = process.env.POP_REGION ?? "bom";const PUBLIC_IP = process.env.SFU_PUBLIC_IP ?? "198.51.100.11";   // unicast, never the anycast IPconst PUBLIC_URL = process.env.SFU_PUBLIC_URL ?? "wss://bom-sfu-1.meet.example.com";const redis = new Redis(process.env.REDIS_URL ?? "redis://127.0.0.1:6379");export const mediaCodecs: types.RtpCodecCapability[] = [  { kind: "audio", mimeType: "audio/opus", clockRate: 48000, channels: 2, preferredPayloadType: 100 },  { kind: "video", mimeType: "video/VP8", clockRate: 90000, preferredPayloadType: 101 },  {    kind: "video", mimeType: "video/H264", clockRate: 90000, preferredPayloadType: 102,    parameters: { "packetization-mode": 1, "profile-level-id": "42e01f", "level-asymmetry-allowed": 1 },  },];type Slot = { worker: types.Worker; server: types.WebRtcServer; load: number };const slots: Slot[] = [];const rooms = new Map<string, { router: types.Router; slot: Slot }>();// One worker per core; each worker owns one WebRtcServer on a single UDP+TCP port.export async function start() {  for (let i = 0; i < cpus().length; i++) {    const worker = await mediasoup.createWorker({ logLevel: "warn" });    worker.on("died", () => { console.error(`worker ${worker.pid} died`); process.exit(1); });    const port = 40000 + i;    const server = await worker.createWebRtcServer({      listenInfos: [        { protocol: "udp", ip: "0.0.0.0", announcedAddress: PUBLIC_IP, port },        { protocol: "tcp", ip: "0.0.0.0", announcedAddress: PUBLIC_IP, port },      ],    });    slots.push({ worker, server, load: 0 });  }  setInterval(heartbeat, 2_000).unref();}// Rooms are pinned to the least-loaded worker on this node.export async function routerFor(roomId: string) {  const existing = rooms.get(roomId);  if (existing) return existing;  const slot = slots.reduce((a, b) => (a.load <= b.load ? a : b));  const router = await slot.worker.createRouter({ mediaCodecs, appData: { roomId } });  const entry = { router, slot };  rooms.set(roomId, entry);  return entry;}export async function createClientTransport(roomId: string) {  const { router, slot } = await routerFor(roomId);  const transport = await router.createWebRtcTransport({    webRtcServer: slot.server,    enableUdp: true,    enableTcp: true,    preferUdp: true,    initialAvailableOutgoingBitrate: 1_500_000,  });  slot.load += 1;  transport.observer.on("close", () => { slot.load -= 1; });  return {    transport,    params: {      id: transport.id,      iceParameters: transport.iceParameters,      iceCandidates: transport.iceCandidates,      dtlsParameters: transport.dtlsParameters,    },  };}// Publish load so edges can choose. Score = transports per core (lower is better).async function heartbeat() {  const load = slots.reduce((sum, s) => sum + s.load, 0) / slots.length;  const draining = (await redis.get(`sfu:drain:${NODE_ID}`)) === "1";  await redis    .multi()    .hset(`sfu:node:${NODE_ID}`, { url: PUBLIC_URL, region: REGION, seenAt: Date.now(), draining: draining ? "1" : "0" })    .zadd(`sfu:load:${REGION}`, draining ? 1e9 : load, NODE_ID)    .exec();}

The SFU's own WebSocket checks the ticket before anything else. A ticket minted for bom-sfu-1 is rejected by bom-sfu-2, an expired one is rejected everywhere, and that is what makes the pin hold: a client can't drift to another node by accident.

// sfu/signal.ts: the SFU's own WebSocket. It accepts only tickets minted for THIS node.import Fastify from "fastify";import websocket from "@fastify/websocket";import { jwtVerify, importSPKI } from "jose";import type { types } from "mediasoup";import { start, routerFor, createClientTransport } from "./node.js";const NODE_ID = process.env.SFU_NODE_ID ?? "bom-sfu-1";const publicKey = await importSPKI(process.env.MEDIA_TOKEN_PUBLIC_KEY ?? "", "EdDSA");await start();const app = Fastify({ logger: true });await app.register(websocket);app.get<{ Params: { roomId: string }; Querystring: { token: string } }>(  "/rooms/:roomId",  { websocket: true },  async (socket, req) => {    const { roomId } = req.params;    let userId: string;    try {      const { payload } = await jwtVerify(req.query.token, publicKey, { audience: `sfu:${NODE_ID}` });      if (payload.roomId !== roomId) throw new Error("wrong room");      userId = String(payload.sub);    } catch {      socket.close(4401, "bad ticket");             // ticket for another node, room or expired      return;    }    const { router } = await routerFor(roomId);    const transports = new Map<string, types.WebRtcTransport>();    socket.on("message", async (raw: Buffer) => {      const { id, method, params } = JSON.parse(raw.toString());      let result: unknown;      switch (method) {        case "getRouterRtpCapabilities":          result = router.rtpCapabilities;          break;        case "createTransport": {          const { transport, params: p } = await createClientTransport(roomId);          transports.set(transport.id, transport);          result = p;          break;        }        case "connectTransport":          await transports.get(params.transportId)?.connect({ dtlsParameters: params.dtlsParameters });          result = { ok: true };          break;        case "produce": {          const producer = await transports.get(params.transportId)!.produce({            kind: params.kind, rtpParameters: params.rtpParameters, appData: { ...params.appData, userId },          });          result = { id: producer.id };   // cascade.ts pipes it to other regions that need it          break;        }      }      socket.send(JSON.stringify({ id, result }));    });    socket.on("close", () => transports.forEach((t) => t.close()));  },);await app.listen({ host: "127.0.0.1", port: 8443 }); // Caddy serves TLS for bom-sfu-1.meet.example.com on :443

Some users can't reach UDP at all (strict office firewalls, some hotel and mobile networks). ICE then falls back to TURN over TLS on port 443. Run coturn on its own unicast address in each PoP and hand out only short-lived credentials.Source [6]Source [7]

# /etc/turnserver.conf on turn-bom.meet.example.com (UNICAST 198.51.100.21; dummy values)
listening-ip=198.51.100.21
external-ip=198.51.100.21
listening-port=3478
tls-listening-port=443
realm=meet.example.com

# Time-limited credentials minted by the edge (TURN REST API style)
use-auth-secret
static-auth-secret=dummy-turn-shared-secret-0f9c2b7e4a1d
stale-nonce=600

cert=/etc/ssl/turn/fullchain.pem
pkey=/etc/ssl/turn/privkey.pem

min-port=49160
max-port=65535
total-quota=1200
fingerprint
no-multicast-peers
no-tcp-relay

# Never relay into private ranges or the backbone
denied-peer-ip=10.0.0.0-10.255.255.255
denied-peer-ip=172.16.0.0-172.31.255.255
denied-peer-ip=192.168.0.0-192.168.255.255

5. Cascade between regions

Four steps: join via meet.example.com, where the edge checks the token and Redis picks an SFU; pin to bom-sfu-1 at 198.51.100.11; cascade to Singapore over the 10.42 backbone via NATS and a PipeTransport; rejoin after any failure.
Join through anycast, pin to one SFU, relay each stream once per region, rejoin on failure.

When Delhi and Jakarta share a room, Delhi's video should cross the ocean once, not once per viewer. mediasoup's router.pipeToRouter() does exactly this between routers on one machine; between machines you do the same steps yourself: create a PipeTransport on each side, exchange IP, port and SRTP keys (here over NATS request and reply), consume on the origin and produce on the remote with the same ID. Remote viewers then consume the piped producer as if the speaker were local.Source [5]

// sfu/cascade.ts: pipe a producer from its origin SFU (e.g. bom) to a remote SFU (e.g. sin)// over the private backbone. Same idea as router.pipeToRouter(), but across hosts,// so we do the signaling ourselves over NATS.import type { types } from "mediasoup";import { connect, JSONCodec } from "nats";import { routerFor } from "./node.js";const BACKBONE_IP = process.env.BACKBONE_IP ?? "10.42.3.11";      // WireGuard address of this nodeconst NODE_ID = process.env.SFU_NODE_ID ?? "bom-sfu-1";const nc = await connect({ servers: process.env.NATS_URL ?? "nats://10.42.0.10:4222" });const jc = JSONCodec();type PipeOffer = { roomId: string; fromNode: string; ip: string; port: number; srtp: types.SrtpParameters };type PipeAnswer = { ip: string; port: number; srtp: types.SrtpParameters };async function newPipeTransport(router: types.Router) {  return router.createPipeTransport({    listenInfo: { protocol: "udp", ip: BACKBONE_IP, portRange: { min: 45000, max: 45999 } },    enableSrtp: true,      // the backbone is private, but encrypt anyway    enableRtx: true,       // retransmit lost packets between regions  });}// ORIGIN side: called when a remote region needs a producer that lives here.export async function pipeProducerTo(roomId: string, producer: types.Producer, remoteNode: string) {  const { router } = await routerFor(roomId);  const local = await newPipeTransport(router);  const offer: PipeOffer = {    roomId, fromNode: NODE_ID,    ip: local.tuple.localIp, port: local.tuple.localPort, srtp: local.srtpParameters!,  };  const msg = await nc.request(`sfu.${remoteNode}.pipe.open`, jc.encode(offer), { timeout: 3_000 });  const answer = jc.decode(msg.data) as PipeAnswer;  await local.connect({ ip: answer.ip, port: answer.port, srtpParameters: answer.srtp });  const pipeConsumer = await local.consume({ producerId: producer.id });  await nc.request(`sfu.${remoteNode}.pipe.produce`, jc.encode({    roomId,    fromNode: NODE_ID,    id: producer.id,                       // keep the id so clients can refer to it anywhere    kind: pipeConsumer.kind,    rtpParameters: pipeConsumer.rtpParameters,    paused: pipeConsumer.producerPaused,  }), { timeout: 3_000 });  pipeConsumer.observer.on("close", () => nc.publish(`sfu.${remoteNode}.pipe.close`, jc.encode({ id: producer.id })));  return pipeConsumer;}// REMOTE side: answer pipe requests from other regions.const remotePipes = new Map<string, types.PipeTransport>();   // key: roomId|fromNodeconst remoteProducers = new Map<string, types.Producer>();nc.subscribe(`sfu.${NODE_ID}.pipe.open`, {  callback: async (_err, msg) => {    const offer = jc.decode(msg.data) as PipeOffer;    const { router } = await routerFor(offer.roomId);    const pipe = await newPipeTransport(router);    await pipe.connect({ ip: offer.ip, port: offer.port, srtpParameters: offer.srtp });    remotePipes.set(`${offer.roomId}|${offer.fromNode}`, pipe);    msg.respond(jc.encode({ ip: pipe.tuple.localIp, port: pipe.tuple.localPort, srtp: pipe.srtpParameters! }));  },});nc.subscribe(`sfu.${NODE_ID}.pipe.produce`, {  callback: async (_err, msg) => {    const req = jc.decode(msg.data) as {      roomId: string; fromNode: string; id: string;      kind: types.MediaKind; rtpParameters: types.RtpParameters; paused: boolean;    };    const pipe = remotePipes.get(`${req.roomId}|${req.fromNode}`);    if (!pipe) return msg.respond(jc.encode({ ok: false, error: "no_pipe" }));    const producer = await pipe.produce({      id: req.id, kind: req.kind, rtpParameters: req.rtpParameters, paused: req.paused,    });    remoteProducers.set(producer.id, producer);    msg.respond(jc.encode({ ok: true }));   // local clients can now consume it like any producer  },});nc.subscribe(`sfu.${NODE_ID}.pipe.close`, {  callback: (_err, msg) => {    const { id } = jc.decode(msg.data) as { id: string };    remoteProducers.get(id)?.close();    remoteProducers.delete(id);  },});

6. The client: join, pin, rejoin

The browser asks anycast for a ticket, then talks only to the pinned SFU. It sends three simulcast layers of video so the SFU can give each viewer the layer that fits their screen and connection. If ICE fails or the SFU's WebSocket closes, it backs off and joins again through anycast, which by then routes around whatever broke.

// client/join.ts: browser side. Join through the anycast name, then talk to one unicast SFU.import { Device } from "mediasoup-client";import type { types } from "mediasoup-client";type Ticket = {  sfu: { id: string; url: string };  mediaToken: string;  region: string;  homeRegion: string;  iceServers: RTCIceServer[];};// meet.example.com resolves to 203.0.113.10 everywhere; BGP delivers us to the nearest PoP.async function getTicket(roomId: string, userJwt: string): Promise<Ticket> {  const res = await fetch(`https://meet.example.com/v1/rooms/${roomId}/join`, {    method: "POST",    headers: { authorization: `Bearer ${userJwt}` },  });  if (!res.ok) throw new Error(`join failed: ${res.status}`);  return res.json();}// Tiny request/response helper over the SFU's WebSocket.function rpc(ws: WebSocket) {  let seq = 0;  const pending = new Map<number, (v: any) => void>();  ws.addEventListener("message", (e) => {    const msg = JSON.parse(String(e.data));    pending.get(msg.id)?.(msg.result);    pending.delete(msg.id);  });  return (method: string, params: unknown = {}) =>    new Promise<any>((resolve) => {      const id = ++seq;      pending.set(id, resolve);      ws.send(JSON.stringify({ id, method, params }));    });}export async function joinCall(roomId: string, userJwt: string, stream: MediaStream) {  const ticket = await getTicket(roomId, userJwt);  // The pin: from here on, everything goes to this one unicast SFU.  const ws = new WebSocket(`${ticket.sfu.url}/rooms/${roomId}?token=${encodeURIComponent(ticket.mediaToken)}`);  await new Promise((ok, fail) => { ws.onopen = ok; ws.onerror = fail; });  const call = rpc(ws);  const device = new Device();  await device.load({ routerRtpCapabilities: await call("getRouterRtpCapabilities") });  const sendParams = await call("createTransport", { direction: "send" });  const send = device.createSendTransport({ ...sendParams, iceServers: ticket.iceServers });  send.on("connect", ({ dtlsParameters }, done, fail) =>    call("connectTransport", { transportId: send.id, dtlsParameters }).then(done).catch(fail));  send.on("produce", ({ kind, rtpParameters, appData }, done, fail) =>    call("produce", { transportId: send.id, kind, rtpParameters, appData }).then(({ id }) => done({ id })).catch(fail));  const [video] = stream.getVideoTracks();  const [audio] = stream.getAudioTracks();  const producers: types.Producer[] = [];  if (audio) producers.push(await send.produce({ track: audio }));  if (video) {    producers.push(await send.produce({      track: video,      encodings: [                                   // simulcast: 3 layers, the SFU picks per viewer        { rid: "q", scaleResolutionDownBy: 4, maxBitrate: 150_000 },        { rid: "h", scaleResolutionDownBy: 2, maxBitrate: 500_000 },        { rid: "f", scaleResolutionDownBy: 1, maxBitrate: 1_500_000 },      ],      codecOptions: { videoGoogleStartBitrate: 1000 },    }));  }  // If the pinned SFU or its whole PoP dies, go back through anycast and get a new pin.  let rejoining = false;  const rejoin = async (reason: string) => {    if (rejoining) return;    rejoining = true;    console.warn(`media path lost (${reason}); rejoining via anycast`);    producers.forEach((p) => p.close());    send.close();    ws.close();    for (let attempt = 0; attempt < 6; attempt++) {      await new Promise((r) => setTimeout(r, Math.min(250 * 2 ** attempt, 4_000)));      try { return await joinCall(roomId, userJwt, stream); } catch { /* try again */ }    }    throw new Error("could not rejoin the call");  };  send.on("connectionstatechange", (state) => { if (state === "failed") void rejoin("ice failed"); });  ws.addEventListener("close", () => void rejoin("signaling closed"));  return { ticket, device, send, producers, call };}

Scaling it as far as it goes

  • Size workers by consumers, not rooms: a 50-person meeting where everyone hears everyone and sees 9 tiles needs about 50 × (49 + 9) = 2,900 consumers, so about 6 workers.

  • Split a big room across workers with pipeToRouter(), and across nodes with the cascade above, so one meeting is never limited to one machine.

  • Autoscale each region on the published load score; add nodes at 70 % and drain the emptiest node when the region falls under 30 %.

  • Keep the join path stateless: any edge in any PoP can answer any join, because room ownership and SFU load live in Redis.

  • Give each region its own Redis for SFU load, and keep room ownership in one globally replicated store; NATS runs as one cluster per region joined into a supercluster.

  • Watch per-region join latency, ICE failures, TURN share and consumer counts; page someone when a PoP withdraws its routes.

  • Test failure on purpose every week: stop an SFU in the middle of a call, withdraw a PoP, cut the backbone between two regions.

What a failure looks like from the user's chair

An SFU process crashes: the WebSocket closes, the browser rejoins through anycast within about a second and lands on another node in the same PoP. A whole PoP loses power: its BGP sessions time out within 9 seconds, routes move to the next nearest PoP, and the rejoin lands there. The backbone between two regions breaks: each region keeps its own part of the call going, and the cascade reconnects when the tunnel is back.

Listen: one IP for the world, in about a minute1:00
Transcript
Here is the whole design in about a minute. A video call is only as fast as the path its packets take. One server in Virginia is close to New York, and far from Delhi, Jakarta and Melbourne. So you add servers around the world. But if each one has its own address, every client has to choose, and DNS can only guess. Anycast fixes the choice. Every site announces the same address with BGP, and the internet sends each person to the nearest site. Routes can change in seconds, though, and a live call can't move with them. So only the join request uses anycast. The site that answers hands back a short ticket for one nearby media server, and the call stays on that server's own, unicast address. When a room spans regions, the servers relay each stream once over a private backbone. And if a server or a whole site fails, the app simply joins again through anycast, and lands somewhere healthy. Anycast finds the door. Unicast keeps the call.

Go further

For the details behind section 2, the IETF's own guide to running anycast services:


Anycast to find the nearest door, unicast to stay in the room, a backbone between rooms: that's how one IP serves the whole world.

Sources

  1. Operation of Anycast Services (RFC 4786), IETF. Accessed 2026-11-20. Back to the text for source 1
  2. BIRD 2.18 User's Guide, CZ.NIC. Accessed 2026-11-20. Back to the text for source 2
  3. IPv4 Address Blocks Reserved for Documentation (RFC 5737), IETF. Accessed 2026-11-20. Back to the text for source 3
  4. A REST API For Access To TURN Services, IETF (Justin Uberti). Accessed 2026-11-20. Back to the text for source 4
  5. Scalability, mediasoup. Accessed 2026-11-20. Back to the text for source 5
  6. Interactive Connectivity Establishment (ICE) (RFC 8445), IETF. Accessed 2026-11-20. Back to the text for source 6
  7. turnserver.conf example, coturn. Accessed 2026-11-20. Back to the text for source 7