Stored Playback and Live Interaction Have Different Needs
Two people join a support call. A third person watches yesterday's recorded demo of the same product. Both see video in a browser. Both may use the same codecs, the same player element, and the same Cloudflare account. Almost nothing else about the two paths is shared.
Think of a letter versus a phone call. A letter can be re-sent, stored, opened tomorrow, and read by a thousand people from one copy. A phone call cannot be re-sent. A sentence that arrives three seconds late is worse than a sentence that never arrives, because the listener has already started answering.
That difference produces two different engineering disciplines:
- Stored playback moves a file. The unit of work is a segment that can be cached, retried, and served identically to every viewer.
- Live interaction moves a packet. The unit of work is a few milliseconds of audio or video that is worthless once its moment passes.
Some terms before the mechanics:
- A media track is one continuous stream of audio or video, such as a microphone or a camera.
- A codec compresses that track; Opus for audio and H.264, VP8, or AV1 for video are common.
- A packet is one small piece of an encoded track, sent over the network independently.
- Latency is the delay from mouth to ear. Jitter is the variation in packet arrival time; a stream with steady delay is usable, one with uneven delay is not.
- An SFU (selective forwarding unit) receives each publisher's tracks and forwards copies to subscribers without mixing them.
- An MCU (multipoint control unit) decodes every input, mixes or composites them, and sends one stream back to each participant.
The SFU is a switchboard: it connects lines without listening. The MCU is a studio: it re-frames the picture for you, at the cost of decoding and re-encoding everyone's media on the server. A full mesh — every participant sending directly to every other — needs no server at all, but upload bandwidth grows with the square of the room size, which is why it typically becomes impractical past four or five participants on home connections.
Stored delivery optimizes correctness per byte. A missed segment is fetched again, and a player buffers seconds of content so that a hiccup is invisible.
Interactive delivery optimizes time per packet. The buffer is a few frames deep, loss is concealed rather than repaired, and every receiver has a different path and a different available bandwidth. Cloudflare's own Stream WebRTC documentation targets less than 500 milliseconds of latency for live playback, while segment-based HLS playback is measured in seconds by design. Figure 1 separates the two pipelines.
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','titleColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','activationBorderColor':'#132440','signalColor':'#5a6e82','signalTextColor':'#132440','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
subgraph S["Stored playback: the file is the unit of work"]
S1["Camera or encoder"] --> S2["Encode once at high quality"]
S2 --> S3["Object storage holds one master"]
S3 --> S4["CDN caches segments near the viewer"]
S4 --> S5["Player buffers seconds of content"]
S5 --> S6["Missing segment? Fetch it again"]
end
subgraph L["Live interaction: the packet is the unit of work"]
L1["Camera and microphone"] --> L2["Continuous encode, adaptive bitrate"]
L2 --> L3["SFU forwards only selected tracks"]
L3 --> L4["Each viewer decodes its own stream"]
L4 --> L5["Jitter buffer holds a few frames"]
L5 --> L6["Packet lost? Conceal it and continue"]
end
S6 --> Q{"Can the viewer wait?"}
L6 --> Q
Q -->|"Yes: buffer, cache, retry"| R1["CDN and object storage are the right tools"]
Q -->|"No: forward within 150-400 ms"| R2["SFU and TURN are the right tools"]
classDef primary fill:#132440,color:#ffffff,stroke:#0b172b;
classDef secondary fill:#16476A,color:#ffffff,stroke:#0f314a;
classDef ok fill:#3B9797,color:#ffffff,stroke:#2a6f6f;
classDef danger fill:#BF092F,color:#ffffff,stroke:#7a0420;
classDef warn fill:#c4873b,color:#132440,stroke:#8a5a1f;
class S1,S2,S3,S4,S5,L1,L2,L3,L4,L5,L6,Q,R1,R2 secondary;
class S6 danger;
The two paths also cross different trust boundaries. Your application decides who may join a session, but it never touches the media itself. Figure 2 places identity, signaling, media, and stored delivery in separate layers, with the credential boundary drawn once.
A video feature is two systems
You own the authorization and signaling system, and you rent or operate the media system. Each fails in its own vocabulary: a stalled join or a 4xx from your Worker, versus a missing relay candidate or a flat packet counter. Neither failure looks like the other in the browser.
Signaling Does Not Carry All the Media
Signaling is the conversation about the call. It carries session descriptions in a text format called SDP, network candidates from ICE (Interactive Connectivity Establishment), track names, and identifiers. It does not carry audio or video.
The size difference is stark. A four-minute one-to-one call at 1.2 Mbps moves about 36 MB of media in each direction. The signaling exchange that set it up is a few tens of kilobytes of text. That is roughly a thousand to one. Cloudflare bills Realtime on egress gigabytes, not on signaling messages, because the media is where the bytes are.
Your backend drives the control plane. It calls the SFU over HTTPS to create a session and publish a track; the SFU returns SDP that the browser applies, and media then flows directly between the browser and the SFU. Your Worker never sees a frame.
The table compares the layers you are actually operating, and what each one looks like when it breaks.
| Layer | Carries, and who terminates it | Failure signature |
|---|---|---|
| Application authorization | Session cookie, OIDC token, room ID, and role; terminated by your Worker | HTTP 401 or 403 before any media object exists, with a clear message to the user |
| SFU control API | HTTPS requests to rtc.live.cloudflare.com, authenticated with the App Secret; creates sessions and tracks, returns SDP | A 4xx with a per-item error code, or an HTTP 200 whose tracks array still contains errors |
| Signaling transport | Your own WebSocket or HTTPS channel, carrying SDP, ICE candidates, and track identifiers between browser and backend | A stalled join, a duplicated subscription, or a 406 from overlapping mutations on one session |
| Media, direct path | SRTP over UDP between browser and SFU, with keys agreed by DTLS | connectionState: failed with no relay candidate, or media that connects and then stops |
| Media, relayed | SRTP inside a TURN allocation, over UDP 3478 or 443, or TCP 443 | An ICE gathering timeout on restrictive networks, or a working call that silently degrades under loss |
| One-to-many broadcast | WHIP in, WHEP out, on a Stream live input | An RTMP input cannot be played by WHEP, and a WHIP input cannot be recorded or played as HLS |
| Stored delivery | HTTPS segment requests served by the CDN | A 404, a stale manifest, or a player buffer stall — all recoverable by retrying |
Read the third and fourth rows together: signaling success proves only that both sides agreed on parameters. It says nothing about whether a packet can travel. Figure 3 shows a join that succeeds at the API layer and then takes two different paths at the network layer, along with the denial and conflict branches that produce the most confusing support tickets.
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','activationBorderColor':'#132440','signalColor':'#5a6e82','signalTextColor':'#132440','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
sequenceDiagram
autonumber
participant B as Browser
participant W as Worker and Durable Object
participant S as Realtime SFU
participant T as TURN
B->>W: join room with session cookie
alt membership check fails
W-->>B: 403 and no session is created
else membership check passes
W->>S: POST sessions new
S-->>W: sessionId
W->>S: POST tracks new, location local
S-->>W: SDP answer plus track identifiers
W-->>B: appId, sessionId, trackName, ICE servers
B->>B: apply remote SDP, gather candidates
alt direct path is reachable
B->>S: SRTP media over UDP
S-->>B: forwarded tracks
else NAT or firewall blocks the direct path
B->>T: allocate relay
T-->>B: relayed address and port
B->>S: SRTP media through the relay
end
end
Note over W,S: A second tracks new before the first answer is applied
W->>S: overlapping mutation on the same session
S-->>W: 406 conflict, queue it and reconcile state
406 is a conflict, not a denial
Cloudflare documents that mutations on a single session must be serialized. A room snapshot and a participant-joined event can both try to subscribe on the same receiving session, and the second request can arrive before the first offer/answer exchange finishes. The fix is one queue per session, not a retry loop.
Realtime Services, TURN, and Connectivity Boundaries
There are now several Cloudflare products in this space, and they are not interchangeable. Choosing well is mostly a matter of counting publishers and asking whether you want to own the interface.
| Product | What it is | Choose it when |
|---|---|---|
| RealtimeKit | Managed meetings: prebuilt UI, web and mobile SDKs, participant management, presets, recording, and transcription | You want to add a call to an app without owning signaling. Billed per participant minute: 10,000 audio/video minutes included per month, then $0.002 per minute, as published on 2026-11-04 |
| Realtime SFU | Primitive: sessions, tracks, DataChannels, and an HTTPS control API | The topology is unusual — a robot, a cloud game, an AI audio pipeline, or a room needing per-track control. You own signaling, identity, discovery, and permissions |
| Stream Live WebRTC | One-to-many broadcast: WHIP in, WHEP out, under 500 ms, with no fixed concurrent viewer limit | One publisher, many viewers, and low latency matter more than recording. Reached general availability on 2026-10-15, the same date usage-based billing began |
| Realtime TURN | A relay, not a conference server | You need a point-to-point link, such as an operator controlling a remote device |
| MoQ Relay | Media over QUIC, currently in beta and free during the beta period | You are evaluating telemetry or one-way low-latency delivery, and can keep a fallback |
The first boundary is the proxy. The Cloudflare proxy in front of your zone is an HTTP and WebSocket proxy. It does not carry WebRTC media, which goes to the SFU or TURN hostnames on their own ports rather than to example.com.
Stream WebRTC is deliberately narrow
WHIP and WHEP must be used together. Recording, live HLS playback, RTMP restreaming, viewer counts, and broadcast metrics are not supported on that path as of this writing. Use a standard live input when you need any of them.
TURN is a leased address. The client sends an Allocate request, the server reserves an IP and port, and returns a relayed transport address that the client can hand to its peer. Cloudflare runs this on anycast, so turn.cloudflare.com resolves to a nearby location, with the notable exception of the China Network, which does not serve Realtime traffic. The ports that matter are UDP 3478 and 443, TCP 3478 and 80, and TLS 5349 and 443.
A TURN key is not a credential. The key is a long-lived server-side secret; the browser receives only short-lived credentials minted from it, with a TTL you choose. That TTL must exceed your longest expected call, or the relay allocation dies mid-conversation.
TURN is not a fallback
TURN is not a rare fallback for broken networks. It is the path that makes corporate firewalls, symmetric NAT, and cellular carriers work at all, and omitting it produces failures you cannot reproduce on your own Wi-Fi. Budget for relayed traffic from day one: Cloudflare charges $0.05 per GB of egress, the first 1,000 GB per month is shared across SFU and TURN, and TURN is free when used with the SFU.
Test the candidate pair, not the join. Every join must produce a candidate pair, and you should know whether that pair is direct or relayed before you declare success. A deployment that has never gathered a relay candidate works on the networks you tested and fails on the ones you did not.
Session Permissions and Network Quality
Permissions in a realtime system are not one decision; they are four, made at four different times.
- Who is this? Your own identity provider or session cookie, checked by your Worker.
- May they join this room? Your application state — a Durable Object holding membership, roles, and a publication list — checked before any SFU call.
- What may they publish or subscribe to? A per-participant policy. In a webinar, the audience subscribes but does not publish. In a support call, the agent may publish video while the customer is audio-only.
- What may the media path do? TURN credentials scoped by TTL, and a Stream WHIP URL that functions as a bearer credential for exactly one live input.
The third decision is where products leak. A room name, a session ID, and a track name are identifiers, not permissions. Cloudflare's architecture guide is explicit that a room or track name does not establish permission, and that the SFU supplies no room-presence protocol. If your Worker hands out a publisher's session ID and track name to anyone who asks, you have built an open mic.
The fourth decision is where money leaks. A TURN credential with a 24-hour TTL is a 24-hour relay allowance for whoever holds it. Generate credentials per participant, keep the TTL close to the expected session length, and revoke on logout. The same logic applies to the Stream WHIP URL: anyone with it can broadcast to that input.
Network quality is not a single number. Three measurements matter:
- Round-trip time sets the floor for turn-taking. As a rule of thumb, once a round trip approaches 300 ms, people start talking over each other regardless of video quality.
- Jitter decides how deep the receive buffer must be. A deep buffer smooths playback and adds delay; a shallow buffer stays responsive and stutters.
- Loss decides whether the encoder must back off. Congestion control reacts to loss and rising delay by lowering bitrate, which is why a call on a bad link gets blurry before it gets choppy.
Simulcast is the main lever. A publisher sends several resolution layers, and the SFU forwards the layer each subscriber can afford, so one slow viewer does not degrade the room. Without simulcast, every receiver gets the same encoding and the weakest link sets the quality for everyone downstream of it.
Thirty seconds of silence ends a track
A media track receiving no packets for 30 seconds is garbage-collected, and a session that loses WebRTC connectivity has a 30-second reuse window. A muted tab, a paused screen share, or a device that slept can lose its publication while the UI still shows a green "connected" badge. Rebuild subscriptions or replace the connection after that window.
Figure 4 contrasts the two outcomes that matter in production: an authorized session with a reachable relay, and a session that fails at a different layer while looking identical to the user.
The ordering in Figure 4 is deliberate. Check authorization before ICE, and ICE before getStats, because each layer can only fail in its own vocabulary. A 401 is not a network problem, and a missing relay candidate is not a permissions problem.
Design an Authorized Two-Participant Realtime Session
The exercise is design-only: no hosted session was run for this article, and no measurement below should be read as observed.
Design an Authorized Two-Participant Realtime Session
Execution status: design-only. Not executed as of 2026-11-04. No SFU app, TURN key, or Worker was deployed, and no latency or quality figure was measured.
Prerequisites and plan requirements. A Cloudflare account with Realtime SFU available, Node.js 22.12 or later, a browser with camera and microphone, and two separate browser profiles. Workers Free supports SQLite-backed Durable Objects, which is enough for room state; the Realtime free tier covers 1,000 GB of monthly egress shared by SFU and TURN. Keep everything in one dedicated SFU app so cleanup is a single delete.
Minimal setup. One Worker with three routes and one Durable Object class:
| Route | Responsibility |
|---|---|
POST /api/token | Validate the session cookie, check room membership, call POST /sessions/new and tracks/new, return appId, sessionId, trackName, and short-lived ICE servers. |
GET /api/rooms/:room/ws | Upgrade to a WebSocket handled by the Durable Object for that room. |
POST /api/leave | Close known tracks, remove membership, return per-item close results. |
Server-side secrets only. None of these may reach the browser:
REALTIME_SFU_APP_IDandREALTIME_SFU_BEARER_TOKENauthorize SFU control API calls.TURN_KEY_IDandTURN_KEY_API_TOKENmint short-lived TURN credentials.
Set them with wrangler secret put, never in the repository.
- Create the SFU app in the dashboard and a TURN key alongside it. Record the App ID and both secrets in a password manager, not in the repository.
- Deploy the Worker with the Durable Object migration. Confirm
GET /api/rooms/demo/wsreturns 101 for an authorized cookie and 403 without it. - Mint TURN credentials with a 600-second TTL and pass only the returned
iceServersarray to the browser. Confirm the response contains aturn:entry and not the TURN key. - Open the room in profile A, allow camera and microphone, and join. Open profile B with a different display name and join.
- In each tab, run
await pc.getStats()and recordinbound-rtpentries twice, five seconds apart. Expected:bytesReceivedincreases, and the selected candidate pair is either direct or relayed, never absent. - Read the SFU calls in
wrangler tail. Expected: onesessions/newper participant,tracks/newfor each publication, and arenegotiatefor each offer the SFU returned. - Leave from profile B. Expected: profile A receives a membership update, and the close call returns a per-track result rather than a bare 200.
- Repeat the join with a token minted for a different room. Expected: 403 from your Worker, and no SFU request in the tail.
Failure checks. Set the TURN TTL to 120 seconds and join after it expires: expect ICE gathering to produce no relay candidate and connectionState to fail, with the SFU API still healthy. Revoke a credential mid-call and observe whether the existing allocation survives while the next join fails — verify rather than assume. Block UDP 3478 and 443 outbound, then confirm the TCP 443 path still carries media. Open the room twice in the same profile, which duplicates the identity, and confirm your room state notices instead of silently creating a second member.
Cost dimensions. Two participants for ten minutes at 1.5 Mbps is about 112 MB of media per direction, so roughly 0.22 GB of egress against the 1,000 GB monthly allowance. Workers and Durable Object requests are billed separately and are negligible at this size. Do not read these as measured figures; they are arithmetic on published rates.
Cleanup. Leave both rooms, then delete the deployment in the order shown after this card. Stopping at the Worker leaves the SFU app and the TURN key billable.
Delete in dependency order. The Worker, its namespace, the TURN key, and the SFU app are four separate deletions.
The point of the exercise is not a working demo. It is to make each layer observable separately: an authorization decision, an SFU request, an ICE candidate, and a packet counter. If you can only see "the call works," you cannot debug the call that does not.
Record Join, Disconnect, and Poor-Network Test Cases
Evidence for a realtime system is a set of observations tied to a specific layer, not a screenshot of two people smiling. Use these pass criteria, each with a failure that is distinguishable from the others.
| Check | Assertion | Pass signature | Fail signature |
|---|---|---|---|
| P1 join | Both tabs receive the published camera track | Remote video plays, and inbound RTP bytes rise across two samples five seconds apart | A black frame with a connected PeerConnection |
| P2 authorization | A token minted for another room is rejected | 403 from your Worker, and no SFU request in the log | A session created anyway, or a 4xx from the SFU instead |
| P3 secret handling | The client bundle carries identifiers only | The bundle contains the App ID and session ID, never the App Secret or TURN key | Any server credential found in the bundle |
| P4 disconnect | Leaving removes membership and closes tracks | Room state drops the member within your heartbeat interval, and the close call returns per-item results | A ghost member, or a bare 200 with no item results |
| P5 poor network | Audio survives before video degrades | Resolution drops, audio continues, and loss and jitter move before the picture does | Video freezes and audio drops together |
An HTTP 200 is not a created resource
A 403 that never reaches the SFU means the request stopped at your Worker, so debug identity and membership rather than media. A 200 with an error inside the tracks array means the request succeeded and the resource did not; inspect per-item results. A session that stays connected while received bytes are flat has a live transport and a dead publication.
A realistic operational scenario. A support team reports that calls fail "for people in one office" and nowhere else. The pattern is a NAT and firewall story, not a code story: that office blocks outbound UDP, so the direct path never forms, and the deployment never configured TURN because it worked on the developer's laptop. The fix is not a code change; it is a TURN credential endpoint plus a test that asserts a relay candidate exists when UDP is blocked.
Self-check.
- Your signaling WebSocket shows connected and the SFU logs a successful
tracks/new, but the viewer sees a black frame. What do you check first? The media path: whether the subscriber requested the remote track with the publisher's session and track identifiers, then whether the candidate pair exists, then the inbound RTP counters. A successful API call proves only that the resource description exists. - Why does a 406 appear when two participants join at once? Both joins mutate the same receiving session, and the second
tracks/newcan arrive before the first offer/answer exchange completes. Serialize mutations per session with a queue; retrying makes it worse. - Why is a 24-hour TURN credential a design error even though it expires? The TTL should track the session it protects. For 24 hours, a copied credential buys relay capacity, and a credential that outlives the call also outlives the permission decision that authorized it.
- A broadcast works in preview but cannot be recorded. Why? Stream's WebRTC path requires WHIP and WHEP together, and recording, HLS playback, and RTMP restreaming are not supported on it. Use a standard live input for a recordable broadcast.
Unresolved limitations. No hosted session, TURN relay, or packet capture was performed for this article; every timeout, limit, and price is quoted from documentation verified on 2026-11-04, not measured here. Mobile carriers, corporate TLS inspection, IPv6-only networks, and the China Network boundary were not exercised. SFU and TURN availability, free-tier size, RealtimeKit minute pricing, Stream WebRTC billing, and the MoQ beta status are all time-sensitive and should be re-checked before you commit to a design.
References (verified 2026-11-04):
- Cloudflare Realtime overview: https://developers.cloudflare.com/realtime/
- Realtime SFU overview: https://developers.cloudflare.com/realtime/sfu/
- SFU application architecture: https://developers.cloudflare.com/realtime/sfu/concepts/architecture/
- SFU negotiation and session lifecycle: https://developers.cloudflare.com/realtime/sfu/concepts/negotiation/
- SFU sessions and tracks: https://developers.cloudflare.com/realtime/sfu/concepts/sessions-tracks/
- SFU limits, timeouts, and quotas: https://developers.cloudflare.com/realtime/sfu/platform/limits/
- SFU pricing: https://developers.cloudflare.com/realtime/sfu/platform/pricing/
- SFU observability: https://developers.cloudflare.com/realtime/sfu/observability/
- Realtime SFU get started: https://developers.cloudflare.com/realtime/sfu/get-started/
- TURN service: https://developers.cloudflare.com/realtime/turn/
- What is TURN: https://developers.cloudflare.com/realtime/turn/what-is-turn/
- TURN credentials: https://developers.cloudflare.com/realtime/turn/generate-credentials/
- TURN FAQ, including topology guidance: https://developers.cloudflare.com/realtime/turn/faq/
- RealtimeKit pricing: https://developers.cloudflare.com/realtime/realtimekit/platform/pricing/
- Stream WebRTC, including current limitations: https://developers.cloudflare.com/stream/webrtc/
- Stream Live WebRTC general availability: https://developers.cloudflare.com/changelog/post/2026-10-15-stream-live-webrtc-ga/
- Realtime SFU WebSocket adapter GA: https://developers.cloudflare.com/changelog/post/2026-09-30-websocket-adapter-ga/
- Media over QUIC, beta: https://developers.cloudflare.com/moq/
- Durable Objects WebSockets and hibernation: https://developers.cloudflare.com/durable-objects/best-practices/websockets/
- Durable Objects limits: https://developers.cloudflare.com/durable-objects/platform/limits/
- Connection limits for proxied HTTP: https://developers.cloudflare.com/fundamentals/reference/connection-limits/
Next in the Series
In Tune the WAF With Evidence Instead of Guesswork, we'll explore Build managed and custom policies with observable false positives.