Skip to main content
Chat persists messages in Postgres. The tuturuuu-chat-realtime Worker delivers committed events to hibernating WebSockets. The Web API authorizes each subscription before it issues a short-lived ticket. It signs publish tickets against the exact request body. See the Chat realtime contract.

Configuration

The Bun sidecar serves local development when the Cloudflare URL is unset. The Web API returns polling mode in production when the Worker origin or dedicated secret is unavailable. Setting the Worker origin disables the SSE proxy and prevents the local Supabase service-key fallback. Enable the origin after the web and mobile clients pass staging.

Local verification

From the repository root, run these commands through resource admission.
The runtime tests launch workerd through the Cloudflare Vite plugin on an available loopback port, with disposable secrets and isolated SQLite persistence. The harness stops its child processes and removes its temporary state. The fixture exercises the Worker and Durable Objects with synthetic callers. The live-socket stop fixture switches the room binding in process. Hosted secret rotation, Web API authorization, Supabase and push delivery require staging checks. The local ticket probe uses a second Supabase stack so it cannot attach to the shared tuturuuu project. From the repository root:
Run it through resource admission. The script writes a temporary project chatrtprobe20 with API port 18521, database port 18522, and the rest of that block through 18529. It copies this repo’s migrations, templates, and seed into that project, seeds one fixture, and starts workerd with a disposable HMAC secret. The ticket and publish calls are createChatRealtimeSubscribeTicket and publishChatRealtimeWorkerEvent. Membership is the same private.chat_get_conversation RPC the ticket route uses. The probe does not boot Next, so session authentication stays on the staging workflow below. It prints PASS or FAIL names and removes the temporary stack and workdir when it finishes.

Staging Worker

Staging is a separate Worker, named in cloudflare.config.ts and selected by CHAT_REALTIME_DEPLOY_ENV=staging. It has its own Durable Object namespaces and is reached only on its workers.dev origin, with no zone route or custom domain. Production keeps the canonical name with workers.dev off. The Chat Realtime Staging Deploy workflow is workflow_dispatch only, from main. Its build job holds no credentials: it runs the chat tests and the workerd runtime checks, builds the staging config, asserts the staging name, workers.dev, no domains or fetch triggers, staging Durable Object bindings and no previous ticket secret, and uploads the tar with its SHA-256. The deploy job runs behind the reviewer-gated chat-realtime-staging environment, which holds two secrets:
  • CHAT_REALTIME_STAGING_CLOUDFLARE_API_TOKEN: a short-lived account token (Workers Scripts Write and Account Settings Read). Mint it for one run, record it in the token ledger and revoke it afterwards.
  • CHAT_REALTIME_STAGING_TOKEN_SECRET: the staging-only ticket HMAC secret, at least 32 characters. Never reuse the production value.
The deploy job verifies the digest and publishes the default build once, with CHAT_REALTIME_STOPPED=false and the ticket secret from a JSON secrets file. It then confirms by secret name that CHAT_REALTIME_TOKEN_PREVIOUS_SECRET is unset. It then runs scripts/staging-smoke.mjs --phase=live, which checks that a signed ticket connects and that one publish is accepted and delivered. It also checks that a subscribe ticket, a body digest mismatch, a foreign signing key and an oversized body are refused. The job then raises the stop fence with scripts/ci/chat-realtime-staging-fence.sh and runs --phase=stopped: health reports stopped, and connect and publish are refused. A final always() step raises the fence again, so staging is fenced whenever the job exits. The live window is bounded by the job timeout. The smoke uses synthetic workspace, conversation and user IDs, so it touches only its own two rooms. The runtime tests run both phases against local workerd. The staging Web path is separate from this Worker smoke. Point a staging Web deployment’s CHAT_REALTIME_URL at the staging origin, give it the same staging ticket secret, lower the fence, and then run the qualification below.

Staging qualification

The Chat Realtime Staging Qualification workflow is workflow_dispatch only, and only from main on tutur3u/platform. Store the QUALIFY_* settings as repository secrets. The job fails before any request when one is unset, and the qualification script prints check names rather than identities, tokens, origins, or message text. Phases are live, stopped, and disabled. Do not set QUALIFY_LOCAL on that workflow; the local workerd path is the probe above.

Artifact and acceptance

  1. Use the Chat Realtime Cloudflare Artifact workflow at the reviewed source SHA. Pin that SHA, the workflow run and attempt, and the artifact ID.
  2. Download the tar and its SHA-256 file from the same run. Run sha256sum -c chat-realtime-output.tar.sha256 before extracting. Compare the digest with the run summary and inspect the emitted Worker configuration under output/v0/workers/default.
  3. Check the target account, Worker name, SQLite classes, config and existing deployment versions. Keep the prior deployment ID for rollback. Only the release owner can authorize publication and routing. Use the pinned cf toolchain and the approved prebuilt path to publish the verified artifact.
  4. Probe GET /health, the authenticated /v1/connect upgrade and POST /v1/publish on the approved staging origin. Use disposable test identities to confirm the intended audience receives the event and a second workspace cannot receive it. Confirm reconnect behavior and the Worker stop switch. Enable the Web origin only after the staged client and fallback behavior pass, including confirmation on mobile.
The Worker runs on ingress, socket events and one expiry alarm per room. It schedules no retry queues or crons. Socket counts, frame sizes, frame rates and replay rows are bounded as documented in the Chat realtime contract. An accepted publish addresses at most two rooms. Each room retains up to 200 event IDs and ignores a duplicate while that event is retained. Connect throttles, revocations and replay survive Worker restarts. Presence broadcasts stop after the room budget for the current window. Each room keeps a single alarm at its earliest open socket’s ticket expiry. The alarm closes expired sockets, or every socket while the stop fence is set, and reschedules only while open sockets remain, so an empty or stopped room has no further wakes. Wakes are bounded by accepted connects, which are throttled per user. Hosted request volume and account cost require monitoring during acceptance.

Ticket secret rotation

Signers (apps/web and Cron Control) use CHAT_REALTIME_TOKEN_SECRET. A rotation build also accepts tickets signed with CHAT_REALTIME_TOKEN_PREVIOUS_SECRET, which must be at least 32 characters. cf deploy refuses to publish while any declared secret is unset, so cloudflare.config.ts declares the previous secret only when CHAT_REALTIME_TOKEN_ROTATION=overlap is set at build time. That build also carries a CHAT_REALTIME_TOKEN_ROTATION=overlap text binding, and the Worker reads the previous secret only while it is present. cf deploy keeps existing secret bindings, so a default build ignores a previous secret that is still bound instead of accepting it. The artifact workflow and the staging deploy build without either binding, and the build steps assert that both are absent.
  1. Build with CHAT_REALTIME_TOKEN_ROTATION=overlap and publish it with a secrets file that sets CHAT_REALTIME_TOKEN_PREVIOUS_SECRET to the current secret and CHAT_REALTIME_TOKEN_SECRET to the new one.
  2. Update CHAT_REALTIME_TOKEN_SECRET on apps/web and Cron Control.
  3. After 15 minutes (the longest ticket lifetime), publish the default build, which stops accepting the previous secret. Then remove the leftover binding with cf workers secrets delete for CHAT_REALTIME_TOKEN_PREVIOUS_SECRET, and confirm with cf workers secrets list that it is gone. Publishing a default build during the overlap ends it early.
For a suspected leak, skip the overlap: replace the secret everywhere with a default build, delete any bound previous secret, and leave it unset. Clients re-ticket and reconnect. The retained Bun sidecar and the Admin and Web development token paths accept only CHAT_REALTIME_TOKEN_SECRET. They never fall back to a Supabase service key.

Revocation recovery

Conversation tickets use the workspace recorded on the conversation. The Web API checks permissions in the workspace where the user opened Chat before it issues the ticket. Shared direct and group conversations therefore use the same room when viewed from different personal workspaces. A leave or archive writes its audit entry in the same Postgres transaction as the membership change. Immediate publication and recovery use that entry’s ID and timestamp. Repeated delivery applies the same cutoff. Tickets issued after the removal and clock-skew allowance can reconnect after the user regains access. The chat-realtime-revocations native Cron Control processor uses the existing five-minute schedule. It stays off until named in CRON_CONTROL_ENABLED_JOBS. Before enabling it, configure the Cron Control Worker’s CHAT_REALTIME_URL and dedicated CHAT_REALTIME_TOKEN_SECRET. It reads the existing private PostgREST tables using Cron Control’s database binding, and publishes body-bound tickets to the Chat Worker. Recovery checks the durable job fence and Worker health before reading Postgres. One invocation scans completed slots within the Worker’s 15-minute event window and leaves time for processing and clock skew. It takes up to 32 undelivered records oldest first, with at most four concurrent publishes. The job ledger retains up to 96 confirmed audit IDs until they age out, so later slots can reach older rows and retry failed deliveries. Overflow is degraded and does not charge the failure budget. Sustained overflow can outlast the event window. A record whose actor account was deleted has nobody to notify. Recovery records it as handled (skipped) without publishing. Archive recovery uses at most two membership reads per archive to notify up to 1,500 members archived in the audit transaction, plus the actor. Cron Control dispatches this processor once per slot. The Worker deduplicates by audit ID during replay retention. The Web API keeps the audit record when delivery fails. Workspace membership and view_chat changes take effect when Web checks the next ticket request. An existing ticket can still admit its holder until it expires, up to five minutes for an inbox and 15 minutes for a conversation. Rooms check expiry before they deliver further frames. Before enabling the job, verify the read query plan against staging data and exercise a publish failure followed by recovery with disposable actors. Check both stop fences, partial delivery, overflow, and old-ticket denial in workerd. Cron Control and the Web environment require separate deployment acceptance.

Stop and rollback

  • Set the Worker secret CHAT_REALTIME_STOPPED=true for an emergency stop. GET /health must report stopped: true and new authenticated upgrades and publishes must return 503. Existing sockets close with 4503 on their next frame or at the room’s expiry alarm, within one ticket lifetime (at most 15 minutes) even when idle.
  • Unset CHAT_REALTIME_URL at apps/web to stop Worker ticket minting and publishing. Confirm the ticket endpoint returns enabled: false and clients resume polling. Check that messages sent while stopped appear after refetch. Stop chat-realtime-revocations through Cron Control to pause recovery too.
  • Roll back to the recorded Worker version if the problem is in the emitted artifact. Keep the Web origin unset until staging validation passes again. Postgres remains authoritative through every step, so rollback requires no message migration.