Skip to content
AnswerWell geo Documentation

Research · 8 min read · Answerwell

WebRTC Selective Forwarding Unit: Application Architecture, WebSocket Media Adapters, and DataChannels

How managed SFU apps split signaling, sessions, WebSocket PCM/JPEG adapters, and DataChannel delivery for live media and control.

This page summarizes Cloudflare’s documentation on Realtime SFU: a managed WebRTC selective forwarding unit that routes audio, video, and application data between your endpoints while your backend owns signaling, identity, and permissions.

Realtime SFU: what it does and what your app must provide

Section titled “Realtime SFU: what it does and what your app must provide”

Realtime SFU forwards the media tracks and DataChannels your application selects. It does not implement rooms, discovery, or user authentication by itself.

Realtime SFU forwards media tracks and DataChannels between endpoints. Your application supplies the signaling, state, and permissions around those connections.

— Cloudflare, Application architecture

Endpoints can be browsers, embedded devices, native processes, or servers with WebRTC. Media and DataChannels run over WebRTC between each endpoint and the SFU; SDP offers and answers pass through your backend, which calls the Connection API over HTTPS.

Layer Responsibilities
Endpoint Capture or generate media, own RTCPeerConnection, apply session descriptions, present connection state
Application backend Authenticate users and devices, authorize operations, hold SFU credentials, call the SFU API
Application state Membership, published media, subscriptions, operator roles, resource cleanup
Realtime SFU Establish WebRTC sessions and forward selected tracks and DataChannels

With Realtime SFU you do not deploy SFU servers or pick regions. You create connections through the API and identify remote publications by publisher sessionId and trackName. Rooms, broadcasts, and device groups are your application concepts composed from sessions and publications.

Sessions and tracks: how WebRTC connections map to API identifiers

Section titled “Sessions and tracks: how WebRTC connections map to API identifiers”

An SFU application has an App ID and App Secret used only on trusted backend infrastructure. A session is one endpoint’s WebRTC connection to the SFU—often one RTCPeerConnection per session.

A session represents one endpoint’s WebRTC connection to the SFU. In a browser, an RTCPeerConnection object manages that connection.

— Cloudflare, Sessions and tracks

Calling POST /apps/{appId}/sessions/new returns a sessionId but does not complete WebRTC setup. Unconnected sessions can expire before the first track or DataChannel operation; later calls may return HTTP 410 with session_error, after which you create a new session and repeat setup.

Identifier Purpose
appId Selects the SFU application
sessionId Target session in API URLs; in remote track entries, identifies the publisher
trackName Names a publication within its publishing session
mid Media section in a particular connection’s SDP
Application member or device ID Your permission and state model—not an SFU credential

To publish, use tracks/new with location: "local" and a trackName. To subscribe, use the receiving session with location: "remote", the publisher’s sessionId, and the same trackName. Your backend maintains discovery and shares locators only with authorized subscribers. A room name or session ID is a locator, not proof of permission.

Separate publishing and receiving sessions when lifecycle complexity grows

Section titled “Separate publishing and receiving sessions when lifecycle complexity grows”

The custom video room example uses separate producer and consumer PeerConnections (and SFU sessions) so negotiation queues stay independent. Cloud gaming often uses one browser session for incoming media and outgoing control DataChannels.

Connection patterns: publish media, subscribe, message, and send controls

Section titled “Connection patterns: publish media, subscribe, message, and send controls”

The connection patterns guide maps common tasks to SFU operations:

Task Typical outcome Example
Publish audio or video Local media available to subscribers Video room
Receive a published track Play another endpoint’s media Video room
Send messages without media Application data over DataChannels DataChannel example
Receive media and send controls Watch and return authorized input Cloud gaming

Base URL for API calls: https://rtc.live.cloudflare.com/v1 with Authorization: Bearer <APP_SECRET> and Content-Type: application/json.

Serialize mutations on the same session: finish each API request and any required SDP exchange before starting the next mutation on that session. Different sessions may proceed in parallel. When an operation returns requiresImmediateRenegotiation: true, complete PUT .../renegotiate with the endpoint’s answer before further changes on that session.

For DataChannels on a new connection, establish transport with POST .../datachannels/establish, complete negotiation, then allocate named application channels with datachannels/new. Media-only first connections can add transport later using Add DataChannels to a media connection in the same guide.

WebSocket media adapter: backend audio and video without a WebRTC client

Section titled “WebSocket media adapter: backend audio and video without a WebRTC client”

The WebSocket adapter connects one SFU track to your service in one direction—useful for transcription, recording, speech generation, and frame analysis.

The WebSocket adapter bridges that gap by streaming WebRTC media from the SFU to a WebSocket endpoint as application-consumable payloads: PCM audio frames and JPEG video frames.

— Cloudflare, Realtime WebSocket adapter auto-reconnect

Your service needs Direction (location) Media
Generate audio for WebRTC clients local (ingest) 48 kHz stereo PCM in; published as Opus
Transcribe or process live audio remote (egress / stream mode) PCM from Opus track
Previews or vision on live video remote with outputCodec: "jpeg" ~1 FPS JPEG frames by default

Create adapters with POST /apps/{appId}/adapters/websocket/new (one to four entries per request). The endpoint must be a publicly reachable wss:// URL; localhost is rejected (websocket_localhost_not_allowed). Adapter creation does not send custom WebSocket headers—authenticate with a scoped token in the path or query, and keep tokens out of browser responses and logs.

Binary messages use Protocol Buffers (sequenceNumber, timestamp, payload). PCM is signed 16-bit little-endian, 48 kHz stereo interleaved. Ingest messages must stay within 32 KB including overhead (limits).

AI audio pipelines: separate ingest and egress adapters

Section titled “AI audio pipelines: separate ingest and egress adapters”

The AI audio pipelines example wires Workers AI speech-to-text and text-to-speech through Durable Object adapters: TTS publishes PCM into the SFU for browser listeners; microphone audio egresses as PCM to an STT adapter; transcripts use a separate application WebSocket—not the SFU media adapter.

For stream-mode egress, the SFU retries the same endpoint after brief disconnects—for up to 15 seconds with no extra API setting (platform limits, GA announcement). Audio uses a short bounded backlog; video resumes from the latest JPEG frame. Recovery is best-effort—not gapless or exactly-once. Ingest (local) does not auto-reconnect; recreate the adapter and redistribute the new sessionId and trackName. Close is idempotent via POST .../adapters/websocket/close.

DataChannels: messaging, delivery policies, readiness, and reply access

Section titled “DataChannels: messaging, delivery policies, readiness, and reply access”

Use DataChannels for chat, sensor updates, game state, and control events; use media tracks for standard A/V (DataChannels).

DataChannels are WebRTC channels for application messages. A client publishes a named DataChannel to Realtime SFU, and the SFU forwards its messages to every client that subscribes to that channel.

— Cloudflare, Control Realtime SFU DataChannel delivery

The publisher chooses one delivery policy per named channel; every subscriber mirrors it in the API and in createDataChannel()—negotiated channels do not propagate settings automatically.

Goal Settings Use when
Reliable, ordered (default) Omit ordered, maxRetransmits, maxPacketLifeTime Messages must arrive in order
Reliable, unordered ordered: false; omit retry fields Later messages must not wait on a delayed one
No retries or ordering ordered: false and maxRetransmits: 0 Stale updates can be dropped
Limited retries maxRetransmits: <COUNT> Brief recovery only
Time-limited transport retries maxPacketLifeTime: <MS> Cap transport retry window

Set at most one of maxRetransmits and maxPacketLifeTime. maxPacketLifeTime is a transport budget, not an end-to-end message-age limit—use application timestamps or sequence numbers for stale data.

Cloud gaming uses reliable ordered channels for keyboard and buttons and unordered maxRetransmits: 0 for pointer movement.

  • waitForAck: true (remote subscriptions only): SFU holds publisher-to-subscriber delivery until the subscriber’s first message (consumed by the SFU, not forwarded). Send within 30 seconds or the gated channel closes (limits).
  • canReply: true: at most one subscriber may hold reply access per publisher channel; granting another replaces the holder. Replies reach the publisher only—not other subscribers. Grant via datachannels/new or datachannels/update; the backend still authenticates the operator (embedded devices example).

Best practices stress boundaries the SFU does not enforce:

Store the SFU App Secret on trusted server infrastructure. In Workers, use a Worker secret. Browsers and devices authenticate to your application backend using credentials scoped to their own responsibilities.

— Cloudflare, Best practices

Avoid an unrestricted SFU proxy that lets clients pick arbitrary sessions or destructive operations. Check identity and ownership before create, publish, subscribe, permission updates, or close. WebSocket endpoint credentials are separate from the App Secret.

Define recovery explicitly: replacement connections need new attempt IDs so stale responses cannot mutate new sessions (negotiation and session lifecycle). Discarding a connection from application state does not stop SFU forwarding—close SFU resources and confirm results. Retain resource IDs for retry until cleanup completes; inspect per-item errorCode fields (error codes).

  • Treating sessionId, trackName, or room names as authorization instead of locators.
  • Overlapping tracks/new or datachannels/new on one session before the prior SDP exchange finishes (can yield HTTP 406 / invalid_session_description).
  • Mismatched DataChannel delivery settings between publisher API, subscriber API, and browser createDataChannel.
  • Assuming HTTP 200 means every track or channel succeeded—always read per-item results.
  • Using non-public WebSocket endpoints for adapters, or single-use tokens on egress URLs that must survive reconnect.
  • Leaving adapters or publications open when tabs close without backend expiry and forced close.
  1. Create an SFU app in the dashboard path described in Get started (Realtime > Serverless SFU), store the App Secret only on your Worker or server, and confirm the browser never receives it.
  2. Run the two-browser video room check at /rooms/two-browser-check and verify local and remote A/V on both participants.
  3. For a failing integration, use Observability: map the symptom to identity, API errors, negotiation ordering, getStats() on the receiving PeerConnection, DataChannel IDs and delivery flags, or adapter handshake errors.
  4. Inspect a session with GET /apps/{appId}/sessions/{sessionId} per Connection API and compare track/channel status with endpoint connection state (active does not guarantee packets are flowing).
  5. You can check automatically in Answerwell (our tool): https://answerwell.org/workspace

If something on this page is wrong or unclear, email yimasynthetic@gmail.com with the page URL and the exact statement you are asking about.