Rooms, Delivery and Scaling
Tenant rooms, the broadcaster architecture, delivery and failure handling, heartbeats, and scaling a room.
How realtime rooms are laid out, what delivery guarantees a broadcast has, and how a room scales. Start at Durable Objects Setup to enable realtime.
Tenant rooms
With tenancy.isolation: 'durable-object', an
instance-bound OAuth kind whose tables live in tenant objects is
tenant-backed.
For such a kind, every realtime identity names its tenant:
- A room on a tenant table is
t1:<tenant>:<key>, for examplet1:org_a:events:evt_1. Rooms of two organizations never collide, even when their row ids do. - The kind's identity tag is
t1:<tenant>:scope:<kind>:<provingTable>:<subjectId>. It names the proving table because subjects proven by different tables can share an id. - The ws-ticket mint derives the same keys, and the tenant admits every
ticket. A bound token uses the tenant it pins and
qb.admitScopefor its exact subject. A session ticket routes the body's instance id through the kind's lookup (409 TENANT_AMBIGUOUS; an unknown id is the same403as an instance you can't prove; a failed lookup read503 TENANT_UNAVAILABLE), never the active organization, and is admitted byqb.admitScopein that tenant under its current epoch, as at authorize. Admission picks the user's highest role in the kind's precedence, so the gate's lanes must confer a prefix of that precedence (every role ranked above the ones they confer), or a user holding a higher role would get403; otherwise the build fails (TENANCY_TICKET_GATE_UNSUPPORTED). The room and the subject tag use the tenant the object answered for; the ticket carries no organization. The edge reads no tenant table. So a session gate on a tenant room must be the kind's own admission:realtime.wsTicket.namespacenaming a namespace whose relationship lanes each confer roles of the kind. The namespace may also have one{ roles }lane of plain organization roles (for example{ roles: ['member', 'admin', 'owner'] }). That lane is checked first, as in the namespace gate. It admits a caller at the edge, without reading the tenant, only when the caller's verified active organization is the tenant the lookup returned and the caller holds one of those roles. The ticket is an organization-role ticket: roomt1:<tenant>:<scopeTable>:<id>,organizationIdset to the tenant, the caller's membership roles, and only theuser:<userId>tag. The lane trusts the lookup and reads no row, so after an instance is deleted, members of the same organization can still mint its ticket until the lookup row is removed. Other organizations can't. A caller whose active organization is another organization falls through to the relationship lanes in the tenant. Unknown ids, ambiguous ids and failed lookup reads get the same answers as above. An org-role (access), team, FGA or single-probe gate fails the build (TENANCY_TICKET_GATE_UNSUPPORTED). So does a{ team }lane, or a{ roles }lane naming a pseudo-role, ascope:role orrole+hierarchy. An open socket's revocation bound differs by credential: a bound-token ticket is capped at the source token's expiry (at most 180 seconds); a session ticket gets the ordinary authorization lease (default 15 minutes), after which a reconnect or renewal re-runs tenant admission. - A resource-backed room whose
access.resourceis a tenant table can't be checked against the platform D1, because the row isn't there. Its room key column needs a lookup:tenancy.lookups.<name>: { table, column: <key> }. Without one, the build fails (TENANCY_ROOM_LOOKUP). The room's role gate (access.roles, or the table'sread.access) runs on the edge before any read. Then the edge resolves the room id through the lookup and requires the caller's verified active organization to be that tenant. The table firewall and room-key match then run in that organization's object (qb.roomAccess), with the caller's user id, organization roles and active team, so a team-scoped row admits the same callers asGET /:id. An unknown, ambiguous or denied id, or one in another organization, gets403. A failed lookup read or an unavailable tenant gets503. Only organization members of the row's tenant can open such a room. Several forms fail the build (TENANCY_ROOM_UNSUPPORTED): multi-resource rooms (access.resources) that reach a tenant table, rooms on partitioned tables, and an inheritedread.accesswith arecord:predicate. The room class runs in the edge Worker, so keep it outside tenant feature folders. - Broadcasts from a tenant object reach the edge through its outbox. The edge
replays them with
createRealtime(env, { tenantId }), taking the tenant from the object's own name, never from tenant code. The one send step every helper ends in qualifies them: CRUD broadcasts,scopeKeyFromdeliveries, actionemit, changesets, invalidations, custom namespaces and raw sends. A room key on a tenant table moves undert1:<tenant>:. The send throws, and nothing is sent, when a tenant object addresses a room that is not on a tenant table (TENANT_REALTIME_PLATFORM_ROOM, refused at build time where the room is declared), another tenant's room, or another organization (TENANT_REALTIME_CROSS_TENANT). The drain logs the error. - Tags are qualified the same way. Because a tag only narrows a send, a tag
that cannot be qualified is dropped and logged, not the whole send. That covers
another tenant's tag, or
scope:<kind>:<subjectId>for a kind with several proving tables and none named. A send whose tags are all dropped reaches nobody.scope:<kind>:<subjectId>qualifies when the kind has one proving table, andscope:<kind>:<provingTable>:<subjectId>qualifies when it names one of them. A recipients resolver names the proving table withrecipient.scope({ kind, subjectId, provingTable }), which becomesscope:<kind>:<provingTable>:<subjectId>. It may leaveprovingTableout for a kind with one proving table. For a kind with several, a call the compiler can see that leaves it out fails the build (TENANCY_REALTIME_TAG_AMBIGUOUS, with the call's file and line), and an identity that reaches the send without it is dropped. A literalprovingTablethat is not one of the kind's fails the build in any mode (REALTIME_RECIPIENT_PROVING_TABLE). Tenant code can build keys itself withtenantRoomKey/tenantScopeTag, exported bysrc/tenant/realtime.ts. - On the edge,
createRealtime(env)throwsTENANT_REALTIME_UNQUALIFIED, before sending, for an unqualified key that names a tenant table or a view rooted on one. Build the key withtenantRoomKey(tenantId, key)fromsrc/lib/realtime.ts. A tenant-backed kind's tag without a tenant is dropped. Sends run after the write commits, so this throw doesn't undo the write: the write stands, and the send doesn't happen. - A tenant object can still send a
userId-only message to any user's personaluser-<id>room, as edge code can. That room belongs to the user, not to an organization. Tenant code is your application's own code, so this is intended.
Organization rooms (organizationId) and personal user-<id> rooms keep
their names. View rooms on tenant tables are still refused at build time,
because the view materializer runs on the edge (TENANCY_ADMISSION_DEPENDENCY,
and TENANCY_REALTIME_VIEW_ROOM while a kind is tenant-backed).
Architecture
1. POST /ws-ticket
┌───────────────────────────────────────────────┐ ┌─────────────────┐
│ Quickback Worker │ ◄──│ Browser Client │
│ │ ──►│ │
│ ┌──────────┐ DO binding ┌────────────────┐ │ └───────┬─────────┘
│ │ Hono API │ ───────────► │ Broadcaster DO │ │ │
│ └──────────┘ (in-process)└───────┬────────┘ │ 2. WS ?ws_ticket=...
│ │ │ │
└────────────────────────────────────┼──────────┘ │
│◄──────────────────────┘
WebSocket (verified at upgrade)- Client gets a ticket —
POST /broadcast/v1/ws-ticketon the main API (session-authenticated). Returns a 60-second HMAC-signed ticket. - Client connects — Opens WebSocket with
?ws_ticket=<ticket>. The Worker verifies the ticket's HMAC and expiry before it touches a Durable Object, so an invalid ticket gets401without waking any room. It then routes to the room named by the verified ticket only (scopeKey, elseorganizationId). Query parameters never pick the room. The Durable Object verifies the ticket again and attaches the socket to the ticket's scope. Each Broadcaster instance is one room (itsctx.id.name), and it refuses with 403 a valid ticket for a different room. If the runtime doesn't exposectx.id.name(wrangler/workerd older than March 2026), upgrades fail with 500 and a log line telling you to update wrangler. - API broadcasts — After CRUD ops, or from custom handlers, the API calls the Broadcaster DO directly via its binding (in-process, no network hop) using the same target model.
Delivery and Failure Handling
Sends are awaited and best-effort: a failed publish never fails the request that emitted it. The generated helper follows Cloudflare's Rules of Durable Objects for stub errors:
| Error | Behavior |
|---|---|
durableObjectReset (the object restarted) | Retried once on a fresh stub |
retryable (and not overloaded) | Retried once on a fresh stub |
overloaded | Not retried (a retry feeds the overload). Logged as a structured warning, {"event":"durable_object.dropped","reason":"overloaded","drops":N,…}, where drops counts per isolate |
Subrequest depth limit exceeded | Not retried; logged as durable_object.failed |
| anything else | Not retried; logged as durable_object.failed |
Every call into the Broadcaster (the publish including its one retry, the
live-view seq read, and in separate-Worker mode the service-binding fetch)
also races a 5-second deadline. A stalled Broadcaster therefore costs the
emitting request at most 5 seconds, not the client's whole timeout, even
though the write has already committed. An expired call is logged like any other
failed publish (durable_object.failed for the inline stub), and the tenant
outbox treats it as retryable. If the
first attempt lands late, the publish id dedupes it.
Every send carries one publish id, and a retry reuses it. The Broadcaster
remembers its 64 most recent ids. When a retry arrives for a first attempt that
actually landed (only the reply was lost), it is acknowledged without a second
fan-out or a new live-view seq. So a retry can never make a concurrent update
look older than it is. Webhook bodies carry the same value as id, so
receivers can dedupe too. A dropped frame is never redelivered. Live views
heal the gap through qbseq: a jump in the sequence triggers a resync (see
Live Views). For table changes and broadcasts,
refetch on reconnect. In separate mode the broadcast Worker applies the same
retry and answers an overloaded publish with 503, which the helper counts
as the same drop.
Heartbeats
Send exactly {"type":"ping"} (no whitespace) and the runtime answers
{"type":"pong"} through setWebSocketAutoResponse, without waking a
hibernated Broadcaster. No duration is billed per socket per beat. A ping
serialized any other way still gets the same pong, but it wakes the object.
Protocol-level WebSocket pings, such as OkHttp's pingInterval or
URLSessionWebSocketTask.sendPing, are also answered without a wake.
Neither kind of ping enforces the authorization lease. An alarm closes lapsed sockets with 4401 instead.
Scaling a room
Fan-out is O(sockets in the room) per publish, and one Durable Object handles
roughly 1,000 simple requests per second. Each Broadcaster is one room: the
scopeKey you target, else the organization. When a single organization gets
very large, or one surface publishes very frequently, target a finer
scopeKey (for example per event or per channel instead of per org) so that
each room holds fewer sockets and receives fewer publishes. Live views already
shard this way: each view:<name>:<rootId> surface is its own object.
Your own room classes can also leave the edge Worker: a
declared Worker hosts a bindings.durableObjects class
(runsOn) in a lean Worker with its own deploy, bundle and CPU budget, and the
edge binds it by script_name.
When one room really is large, and most of its sockets only watch (an
audience, attendees of a keynote), declare
fan-out rooms with
realtime.listeners. Tickets whose roles are all listener roles then connect
to receive-only BroadcasterShard objects (<room>#<n>), and the room's
Broadcaster keeps only the privileged sockets. It numbers each listener frame
(qbseq) and hands one masked copy to every shard. A room's shard count grows
(never shrinks) as its expected attendance rises, up to 16 shards of up to
2,500 sockets each.