Fan-out Rooms
Split a large room into receive-only listener shards with realtime.listeners — classification, sizing, sequence numbers, and the limits of this release.
A room is one Broadcaster Durable Object, and every publish costs O(sockets in the room). That is fine for a few hundred people. A keynote, a live scoreboard or a large event channel can have thousands of people who only watch. A fan-out room keeps the people who act (organizers, staff, admins) on the room's Broadcaster and moves the watchers onto receive-only listener shards.
publish
API ───────────────────────► Broadcaster "events:e1" (control object)
│ privileged sockets (admin, owner, …)
│ assigns qbseq, builds the listener frame once
├─ deliver ─► BroadcasterShard "events:e1#0" listener sockets
├─ deliver ─► BroadcasterShard "events:e1#1" listener sockets
└─ deliver ─► BroadcasterShard "events:e1#2" listener socketsThis page describes the first release of fan-out rooms. Shard counts only grow from the expected audience, fan-out is flat (at most 16 shards per room), and there is no retained state, throttling or resume endpoint yet. See Limits of this release.
Declaring listeners
realtime.listeners is keyed by the ws-ticket scope table. Rooms are
<scopeTable>:<id>, so the key must equal realtime.wsTicket.scopeTable:
providers: {
database: defineDatabase("cloudflare-d1", {
realtime: {
wsTicket: {
access: { roles: ["owner", "admin", "member"] },
requestField: "eventId",
scopeTable: "events",
},
listeners: {
events: {
roles: ["member"], // tickets carrying ONLY these roles are listeners
load: {
framesPerSecond: 4, // peak listener frames per second (default 4)
expectedFrom: "expectedAttendance", // column on events with the expected audience
// target: 1000, // sockets per shard (default derived, see below)
},
max: 16, // most shards per room (default and ceiling: 16)
},
},
},
}),
}| Field | Meaning |
|---|---|
roles | Roles that make a ticket a listener ticket. Concrete roles only, written as full identities: an org role (member) or a qualified scope role (scope:event:attendee). A bare name never matches a scope ticket. Pseudo-roles (AUTHENTICATED) and hierarchy suffixes (member+) are refused. |
load.framesPerSecond | Peak rate of frames that reach listeners. Sets the derived target. |
load.expectedFrom | Numeric column on the scope row. Every listener mint reads it and grows the room to fit. Without it a room has one shard. |
load.target | Sockets per shard. Default clamp(floor(6000 / framesPerSecond), 250, 1250), so 1,250 at 4 frames per second. At most 2,500. |
max | Most shards per room. Default 16, which is also the ceiling in this release. |
Fan-out rooms need inline realtime (realtimeMode: 'inline', the default) and a
platform scope table. Separate-Worker realtime and tenant-qualified rooms
(tenancy.isolation: 'durable-object') are refused at compile time with
REALTIME_LISTENER_UNSUPPORTED.
Ticket classification
POST /broadcast/v1/ws-ticket runs the same gate as before. For a listener
room it then classifies the ticket and signs the result into it:
- Listener — every role the ticket carries is a listener role. A scope
ticket is classified by its
scopeRolesonly (scope:event:attendee); an org ticket by itsrolesonly (member). The ticket getslane: "listener",shards(the room's shard count) andshard, a jump consistent hash of the user id. The same user always lands on the same shard. - Control — the ticket carries any other role. It gets
lane: "control"and connects to the room's Broadcaster exactly as before. An admin who is also a member is a control ticket.
Tickets for rooms whose scope declares no listeners are unchanged.
Role matching is exact because masking is. The Broadcaster never reveals a
bare show.roles entry to a scope ticket, so a scope ticket whose role reads
member (scope:event:member) is not the org role member. List
scope:event:member to make those holders listeners. When the ws-ticket
confers a scope role whose name you listed bare, the compile fails with
REALTIME_LISTENER_ROLE_UNQUALIFIED (a warning instead when an org ticket can
also carry the bare name).
The Worker verifies the ticket, then routes by lane: a listener ticket to
BroadcasterShard <room>#<shard>, any other ticket to the room's
Broadcaster. Each object checks again: the Broadcaster refuses a listener
ticket, and a shard refuses a control ticket, a ticket for another room, or a
ticket for another shard (all 403, codes below).
# separates a room from its shard index, so it is reserved: a request whose
eventId contains # is refused with 400 REALTIME_SCOPE_KEY_RESERVED, and a
listener scope key may not contain it.
Sizing
Every listener mint reads load.expectedFrom from the scope row and asks the
room's Broadcaster for its topology. The Broadcaster computes
shards = clamp(ceil(expected / target), 1, max)and raises the stored count when the result is larger. The count never
shrinks, so a room first used before its expected audience was set grows when
the value arrives. Growth is safe: the Broadcaster delivers every frame to
shards 0..n-1 of the current count, and a ticket minted at an earlier size
names a shard below it. An unsized room delivers to shard 0. A room that outgrows max fills its shards
up to the hard stop.
- An empty or non-positive
expectedFromvalue counts as one shard. - A failed read of
expectedFromis logged asREALTIME_EXPECTED_UNAVAILABLEand sizes nothing: the room keeps its current count and the next mint reads again. A transient database error cannot lock a room small. - If the Broadcaster cannot be reached, the mint is refused with
503 REALTIME_TOPOLOGY_UNAVAILABLEandRetry-After: 5. The route never guesses a shard count.
The ticket route caches the topology for 5 seconds per isolate, so a burst of
mints makes one call, and a growth reaches new tickets within 5 seconds. The
Broadcaster logs REALTIME_ROOM_SIZED on the first size and
REALTIME_ROOM_GREW on each growth.
Each shard reports its socket count to the Broadcaster at most every 5 seconds.
topology() returns { shards, target, max, sockets }, where sockets holds
the last count each shard reported.
What listeners receive
On connect a shard sends:
{ "type": "hello", "v": 1, "seq": 41, "retained": {}, "snapshot_url": null,
"reconnect_ms": 5000, "heartbeat_ms": 25000, "now": 1764806400000 }seq is the room sequence at connect time. retained is always empty in this
release. reconnect_ms is max(5000, sockets × 1000 / 150), so a full shard
reconnecting spreads its upgrades over time. Wait a random delay up to
reconnect_ms before reconnecting.
After that, a listener receives every frame whose targeting reaches every listener role:
- Which frames. A
broadcastorpostgres_changesframe addressed to the room (scopeKey= the room) whosetargetRolesreach each listener role, matched the way the Broadcaster matches a ticket holding that role (scope:event:attendeematches exactly; a bareattendeealso matches it). A shard sends each frame to every socket it holds, so a frame that reaches only some listener roles stays on the Broadcaster, reaches no listener, and logsREALTIME_LISTENER_PARTIAL_TARGET. A frame targeted only at privileged roles (for example["owner", "admin"]) stays on the Broadcaster. Frames targeted by identity tag or user id, live view deltas, andPUBLIC/AUTHENTICATEDaudiences also stay on the Broadcaster in this release. qbseq. The Broadcaster gives each such frame the next room sequence and stores it before any socket or shard sees the frame. The CloudEvents envelope carries it asqbseq. Privileged sockets on the Broadcaster see the sameqbseqon the same frame.- One projection. Masking is applied once for all listeners: a field is
revealed only when every listener role would see it, evaluated with the
role sets a ticket holding that role carries (
rolesandscopeRoles), or when the row's own state reveals it (show.or: { record }). A listener never sees more than the Broadcaster would show its ticket. There is no owner reveal on a shard.
The Broadcaster sends to the shards without waiting for them, through one stub
per shard, so a shard receives frames in qbseq order. A failed delivery is
retried once on a fresh stub unless the shard is overloaded. A shard drops a
frame at or below the last qbseq it saw (a retried duplicate), logged as
REALTIME_SHARD_DUPLICATE_DROPPED. A frame a shard misses is not repaired:
its listeners see a jump in qbseq.
Client contract. Start last at hello.seq. For each frame:
qbseq <= last— drop it. This includes a frame whoseqbseqequalshello.seq: the hello already covers it.qbseq == last + 1— apply it and setlast.qbseq > last + 1— a gap: refetch the current state over HTTP, then setlast.
After a reconnect whose hello.seq is ahead of yours, refetch too. There is no
replay. A lost last frame is not detectable until the next frame arrives;
a periodic watermark arrives in a later release.
Listeners are receive-only
A listener socket may only send heartbeats. Send exactly {"type":"ping"} and
the runtime answers {"type":"pong"} without waking the shard. Any other
message closes the socket with 1008 and logs
REALTIME_LISTENER_SENT_DATA. Listener writes go over HTTP.
The authorization lease
applies on shards too: an alarm closes lapsed sockets with 4401. Each socket's
lease ends up to 10% of its remaining length early, chosen at random when it
connects, so listeners who joined together do not all reconnect in the same
sweep. With the default 15-minute lease, expect each listener to reconnect
every 13.5 to 15 minutes (plus up to a minute of sweep granularity). A shard does
no per-socket check when it delivers, so a lapsed socket can receive frames
until the next sweep (at most about a minute). In-place reauth is not
available on a shard. Reconnect with a fresh ticket instead.
Capacity
| Sockets on one shard | Behavior |
|---|---|
| over 2,000 | Logged as REALTIME_SHARD_OVER_ALERT on each connect |
| 2,500 | Upgrades refused: 503 REALTIME_SHARD_FULL with Retry-After: 5 |
The socket count is read after a cold shard's first call to the Broadcaster, right before the socket is accepted, so concurrent upgrades cannot overshoot the hard stop.
Compile checks
A frame that reaches listeners is one projection for every listener, so
nothing per-socket may decide what it carries, and it must reach every
listener role or none. "Publishes into the room" means the table's
realtime.scopeKeyFrom starts with <scopeTable>:.
| Code | When |
|---|---|
REALTIME_LISTENER_OWNER_MASK | A table whose realtime audience includes a listener role masks a field it sends with show.or: 'owner'. Drop the field from realtime.fields, or send the owner a targeted frame. |
REALTIME_LISTENER_USER_TARGET | A table targets a listener role together with the USER pseudo-role. |
REALTIME_LISTENER_PARTIAL_TARGET | A table that publishes into the room has a realtime audience reaching some listener roles but not all. Add the missing roles, or remove the reached ones. |
REALTIME_LISTENER_ROLE_UNQUALIFIED | roles lists a bare name that the ws-ticket confers only as a scope role (attendee where tickets carry scope:event:attendee). Write the qualified form. A warning when an org ticket can also carry the bare name. |
REALTIME_LISTENER_ROLE_OVERLAP (warning) | A ws-ticket lane confers a listener role and a privileged role in one ticket, so its holders are control tickets. |
REALTIME_LISTENER_PSEUDO_AUDIENCE (warning) | A table that publishes into the room has only PUBLIC / AUTHENTICATED in its realtime audience. Those frames stay on the Broadcaster and never reach listeners. |
REALTIME_LISTENER_SCOPE_UNKNOWN | The key is not realtime.wsTicket.scopeTable. |
REALTIME_LISTENER_SCOPE_KEY_INVALID | The key is not a table name (it contains # or :). |
REALTIME_LISTENER_ROLE_INVALID | A pseudo-role or a + suffix in roles. |
REALTIME_LISTENER_EXPECTED_COLUMN | load.expectedFrom names no column of the scope table. |
REALTIME_LISTENER_MAX_UNSUPPORTED | max above 16. |
REALTIME_LISTENER_UNSUPPORTED | Separate-Worker realtime or tenant-qualified rooms. |
REALTIME_LISTENER_CONFIG_INVALID | Anything else malformed, including keys from later releases (retain, throttle, snapshot). |
Runtime errors
| Status | Code | Where |
|---|---|---|
| 400 | REALTIME_SCOPE_KEY_RESERVED | ws-ticket route: the request id contains # |
| 503 | REALTIME_TOPOLOGY_UNAVAILABLE | ws-ticket route: the room's Broadcaster could not be reached for its shard count; Retry-After: 5 |
| 403 | REALTIME_TICKET_LANE_MISMATCH | Broadcaster got a listener ticket, or a shard got a control ticket |
| 403 | REALTIME_TICKET_ROOM_MISMATCH | A shard got a ticket for another room |
| 403 | REALTIME_TICKET_SHARD_MISMATCH | A shard got a ticket for another shard |
| 401 | AUTH_INVALID_TOKEN | A shard got a malformed, expired or badly signed ticket. The body is generic; the log names the exact reason |
| 403 | REALTIME_TICKET_SHARD_INVALID | Worker route: the ticket's shard / shards are out of range |
| 503 | REALTIME_SHARD_FULL | The shard is at 2,500 sockets |
| 503 | REALTIME_SHARD_COLD | A cold shard could not read the room sequence from the Broadcaster; retry |
Each refusal logs one JSON line with the room, the shard and the reason.
Delivery and reporting problems are logged as REALTIME_SHARD_DELIVER_FAILED,
REALTIME_SHARD_DELIVERY_REFUSED, REALTIME_SHARD_REPORT_FAILED and
REALTIME_LISTENER_PARTIAL_TARGET.
Generated output
A project that declares listeners also gets:
src/lib/BroadcasterShard.ts, exported fromsrc/index.ts;- a
BROADCASTER_SHARDDurable Object binding with migrationqb-do-BroadcasterShardinwrangler.tomlandquickback.deploy.json; - lane routing in the WebSocket route, and classification helpers
(
withListenerLane,jumpConsistentHash,listenerShardName) insrc/lib/ws-ticket.ts.
A project without listeners generates the same files as before, and may use
BroadcasterShard as a bindings.serviceEntrypoints name (it is reserved only
when listeners are declared).
Limits of this release
- The shard count only grows, from the expected audience. It does not follow the live socket count, and it never shrinks.
- Fan-out is flat, up to 16 shards (40,000 listener sockets at the hard stop).
- No retained event values, current-state documents, throttling or compact
frames.
hello.retainedis always{}. - No resume endpoint: a gap means refetch over HTTP.
- No admission rate limit beyond the per-shard hard stop.
- Targeted frames (identity tags, user id) and live-view deltas reach privileged sockets only.