skip to content

In a telehealth room on the Cloudflare Realtime SFU, subscriptions sometimes fail with HTTP 406 when two clinicians join at once; why, and how should the backend fix it?

level: seniorimportance: should knowfreq 15%

answer

  1. two handlers, one receiving session
  2. an exchange that is not finished yet
  3. where the answer must land
  4. a queue keyed by session

basics

~20 s

Two handlers sent tracks/new to the same receiving session before the first SFU offer had been answered through /renegotiate, so the SFU rejected the overlap. Route every mutation for a session through one queue that waits for the full exchange.

solid answer

~40 s

Each Realtime SFU session has one PeerConnection and one offer/answer state machine. When clinician A's join snapshot and clinician B's join notification both trigger a pull, two `tracks/new` calls can hit **A's receiving session** while the first SFU offer is still waiting for A's answer. The SFU can reject the second with HTTP `406`. The fix is to serialize mutations per session: put every pull, close and renegotiation for that session in one queue, and treat an item as done only after `PUT /renegotiate` accepts the answer. A browser reaching `signalingState: "stable"` is not enough. A `406` can have other causes, so read `errorCode` and `errorDescription`. Check every per-track result too, since a `200` can still carry a failed item.

code

javascript · 13 lines
javascript
// One promise chain per SFU session: each mutation starts only after the
// previous one, including its /renegotiate round trip, has settled.
const queues = new Map();

export function enqueue(sessionId, task) {
  const previous = queues.get(sessionId) ?? Promise.resolve();
  const next = previous.catch(() => {}).then(task);
  queues.set(sessionId, next);
  return next;
}

// Both the join snapshot and a later join notification call this:
// enqueue(receivingSessionId, () => pullAndRenegotiate(receivingSessionId, tracks));

go deeper

for a junior

Recall that an SFU session negotiates one exchange at a time and that pulling a track ends with a /renegotiate call.

for a middle

Explain why two handlers can overlap on one receiving session and where a mutation really ends.

for a senior

Diagnose from the error fields, add a per-session queue held across the browser round trip, and retry only after inspecting the session.

for a principal

Decide where room state and queues live, for example one Durable Object per room, and how reconnects get new attempt IDs.

## The symptom A telehealth app lets up to ten people join a group visit. Most of the time everyone sees everyone. But when two clinicians join within a second of each other, one of them sometimes never receives the other's video, and the backend logs an HTTP **406** from `tracks/new`. Retrying the request "fixes" it at random. ## Why it happens A Realtime SFU **session** has exactly one WebRTC PeerConnection and one offer/answer state machine. Pulling a remote track is not a single request: 1. The backend calls `POST /sessions/{receivingSessionId}/tracks/new` with remote entries. 2. The SFU returns an **offer**, with `requiresImmediateRenegotiation: true`. 3. The browser applies the offer, creates an answer and sends it back. 4. The backend submits it to `PUT /sessions/{receivingSessionId}/renegotiate`. The mutation is finished only after step 4 succeeds. Now picture clinician A joining: the room's snapshot handler starts pulling the existing participants into **A's receiving session**. Meanwhile B joins, and B's join notification fires a second handler that also pulls B's tracks into A's receiving session. If the second `tracks/new` arrives between steps 2 and 4 of the first, the session is mid-negotiation, and the SFU can reject the conflicting request with **406**. An `await` inside each handler does not help, because each handler only waits for its own requests: an `await` in one handler does not stop another handler from starting a request. ## The fix: one queue per session - **Serialize mutations per session.** Track creation, updates, closure, DataChannel operations and `/renegotiate` for one session go through one queue. Different sessions, such as B's publishing session, keep running in parallel. - **Hold the queue across the browser round trip.** An item ends when `/renegotiate` accepts the answer, not when the offer is sent to the browser and not when the browser shows `stable`. - **Queue the intent, then reconcile.** When a queued pull finally runs, compare it with the current publications: drop tracks that were withdrawn and de-duplicate repeated publication locators. - **Keep state where the room lives.** Cloudflare's video-room example keeps each room's membership and track discovery in one Durable Object, and gives every browser separate publishing and receiving sessions so the two negotiations never contend. ## Where the queue must live An in-memory queue only works if every request for a given session reaches the **same** instance of your code. Requests to a plain Worker can land on many isolates that share no memory, so a `Map` of queues inside it serializes nothing across them. Put the queue in the one place that owns the room, such as the room's Durable Object, so the snapshot handler and the join handler both go through it. The object still interleaves requests while one of them awaits the SFU or the browser, which is exactly why an explicit queue is needed there too. ## Read the error before blaming the race | What you see | What it means | | --- | --- | | HTTP `406` | Can be overlapping requests, but can also indicate other invalid requests; read `errorCode` and `errorDescription` | | `invalid_session_description` | SDP rejected or offer/answer order wrong, for example replaying an answer after its exchange finished | | HTTP `200` with an item `errorCode` | The batch partly failed; for example `not_found_track_error` when the publisher is not connected yet | | `session_error` with `410` | The session expired or closed; create a new one and rebuild publications and subscriptions | | `session_error` with `425` | Setup is not finished; wait for the connection before later operations | ## Retrying safely - A retry can make things worse: repeating `tracks/new` can allocate **duplicate** subscriptions, so inspect the session (`GET /sessions/{sessionId}`) before creating more. - If an SDP response was lost, replace the connection rather than guessing at its state. - The `correlationId` query parameter on `sessions/new` is only a diagnostic label. It does not make creation idempotent, so repeating it creates another session. ## How to verify the fix Log, per session, the order of queued operations with start and end times, then replay simultaneous joins in a test. Under load, no two operations on one session should overlap, while operations on different sessions should. The 406s from overlap should disappear. Any that remain point to a different invalid request, which the `errorDescription` names.

  • Would giving each participant one bidirectional session instead of two make the 406s go away?
    No. It concentrates more mutations on one state machine, so publish and pull would contend too. A single bidirectional session is valid only if all its mutations share one queue. Separate publishing and receiving sessions, as in Cloudflare's video-room example, keep the two negotiations independent.
  • The backend timed out waiting for a tracks/new response; should it just retry?
    Not blindly. The outcome is unknown, and a repeated pull can allocate duplicate subscriptions. Pause mutations on that session, inspect it with `GET /sessions/{sessionId}`, and if the SDP response was lost, replace the connection and rebuild its subscriptions with a new attempt ID.

  • An await in each handler is enough to keep requests on a session in order.
  • The pull is done once the offer has been sent to the browser.
  • Every HTTP 406 from the SFU means two requests overlapped.
  • Reusing the same correlationId makes a retried sessions/new idempotent.
  • A 200 response proves every track in the batch was subscribed.