# Durable Objects: runaway and silent billing Read this before you change any Durable Object (DO) class, or any code a DO runs. That includes every `/triggers/*` handler that a queue can run, because the queue DOs run those handlers inside a DO. A mistake here does not fail a test. It shows up as a bill: thousands of objects that each stay billed for a minute or more, every hour, until someone notices. ## Why a DO is different from a Worker request When a normal Worker request ends, Cloudflare cleans up for you. It waits for `waitUntil` work (about 30 s), then drops every pending timer and closes every socket. A DO has no such end. It is billed for wall-clock time (128 MB per object) for as long as **anything** is still pending: | Pending thing | How long it keeps the object billed | | ---------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | an uncleared `setTimeout` | until it fires | | an `AbortSignal.timeout(ms)` passed to a `fetch` that already finished | until it fires (the timer outlives the fetch) | | a `waitUntil` / `backgroundTask()` promise | until it settles | | an open TCP socket, including a Hyperdrive `pg` client | up to 15 minutes per connection | | an alarm that re-arms itself | it wakes again and again until something stops it. A short interval (the dispatcher's 1 s) keeps it billed nearly all the time; a long one lets it sleep between wakeups, but every wakeup still costs | Measured on 2026-12-01 (20 objects per case, one call each): | Case | Billed time per object | | ----------------------------------------------------- | ---------------------- | | no timer | 0.08 s | | `setTimeout(fn, 60_000)` left pending | 60.07 s | | `fetch(..., { signal: AbortSignal.timeout(60_000) })` | 60.03 s | | same timers, then `ctx.abort()` | 0.28 s | One leftover timer made each object about 750 times more expensive. The backend has about a hundred `AbortSignal.timeout(...)` and `setTimeout(...)` calls, so in a DO you have to assume that some handler leaves one behind. ## The DOs in this repo and what keeps each one safe | Class | Worker | Objects | What stops it from running away | | ------------------------------------------- | ------------------------------------------------------------ | -------------------------------------------- | --------------------------------------------------------------------------------------------------------- | | `QueueMessage` | api (`cloudflare_workers/api/queue_do.ts`) | one per message run (`queue:msg_id:read_ct`) | `settle()` (30 s cap), then a reset with `ctx.abort()` after every run | | `QueueConsumer` | api (`queue_do.ts`) | one per pgmq queue | `settle()` after every run. No timers of its own. Not reset (see below) | | `QueueDispatcher` | api (`cloudflare_workers/api/queue_dispatcher.ts`) | exactly one (`global`) | The one allowed forever loop: a 1 s alarm. Stops when its binding is removed | | `ConsoleEvents` | api (`cloudflare_workers/api/console_events.ts`) | one per org | Hibernatable WebSockets. The alarm only exists while sockets do, and every socket expires after 5 minutes | | `UploadHandler` / `AttachmentUploadHandler` | files (`supabase/functions/_backend/files/uploadHandler.ts`) | one per upload | One cleanup alarm per upload (1 day), which does not re-arm | | `GoTrue` | gotrue (`cloudflare_workers/gotrue/index.ts`) | exactly one (`gotrue`) | Kept warm on purpose (`sleepAfter = '24h'`). It is a single container, not a fan-out | The queue DOs are the dangerous ones, because the number of objects grows with traffic. Busy queues (`on_channel_update`, `webhook_dispatcher`) see around 1,000 messages per hour each, and each message gets its own `QueueMessage`. `on_manifest_create` (around 13,000 per hour) is the exception: it runs directly inside its `QueueConsumer`. ### How the queue DOs stay safe 1. **`DoRequestScope.settle()`** (`supabase/functions/_backend/utils/do_request_scope.ts`). The scope stands in for the end of a Worker request. `backgroundTask()` hands work to its `waitUntil`. `pg.ts` registers every Hyperdrive client with `onEnd`. `settle()` waits for the background work, including work started while it waits, and then closes the clients. `QueueMessage` caps this wait at 30 s, the same limit Cloudflare puts on `waitUntil`. 2. **Reset after every message.** `settle()` cannot clear timers that trigger code left behind. So once its result is read, the caller resets the `QueueMessage` with `ctx.abort()`. That drops every timer and socket, like the end of a Worker request. The caller uses a **fresh stub** for the reset, because a stub whose call threw cannot be used again. The reset runs after a timeout too. 3. **One object per message run.** The id includes `read_ct`, so a retry gets a new object, and an object never holds two runs. 4. **No alarms and no loops** in `QueueConsumer` or `QueueMessage`. They run only when called. 5. **`QueueConsumer` is not reset on purpose.** Runs for the same queue can overlap (the dispatcher can send several wakeups per tick), and a reset would kill the other run. That is safe only because the consumer path, including `on_manifest_create` which runs directly in it, leaves no timers behind. Do not add any to this path. 6. **Every reset shows up as one DO "error".** That is the expected `ctx.abort()`. "Errors = runs" on `QueueMessage` is normal. Real errors are errors beyond one per message, and the `queue_message_reset_failed` log. ## Rules You MUST NOT: - Remove or skip the `ctx.abort()` reset of `QueueMessage`, or the `scope.settle()` call in `QueueMessage` or `QueueConsumer`. - Reuse one object for many messages, or drop `read_ct` from the `QueueMessage` id. - Add an alarm that re-arms itself without a stop condition. If an alarm must repeat, it needs a condition that ends it (no sockets left, no work left, a binding removed), and there must be only one such object. - Add a timer, `AbortSignal.timeout`, socket or unawaited promise to the `QueueConsumer` path (it is never reset), unless you clear or close it before the call returns. `QueueDispatcher` already uses `AbortSignal.timeout`; that is harmless only because its single object is awake every second anyway. - Open a database connection in a DO outside the `pg.ts` helpers. They are the only code that registers clients with `DoRequestScope`. - Add a DO class without reading this page and adding it to the table above. In new code on DO paths, prefer an `AbortController` plus `setTimeout` that you clear in a `finally` block over `AbortSignal.timeout`. `withTimeout` in `queue_do.ts` is the pattern to copy. ## Checklist before merging DO code - [ ] How many objects can exist at once? One, one per queue, or one per message? - [ ] When the call returns, is anything still pending (timer, socket, promise, alarm)? If you cannot prove it is not, the object must be reset. - [ ] If there is an alarm, what stops it? - [ ] Does it still go through `DoRequestScope.settle()`, and for `QueueMessage`, the reset? - [ ] Do the tests prove the cleanup? (`tests/queue-do*.test.ts`, `tests/do-request-scope*.test.ts`) ## How to check a change after deploy Billed time and request time come from two Cloudflare GraphQL datasets. For each class, compare them over the same window: - `durableObjectsPeriodicGroups` → `sum.activeTime`: the time objects were billed. - `durableObjectsInvocationsAdaptiveGroups` → `sum.wallTime`: the time spent handling calls. If `activeTime` is clearly above `wallTime` (more than about 20%), objects stay billed after their work ends: something is left pending. A high `wallTime` on its own is not a leak. Handlers that call slow outside APIs are real work. ```graphql { viewer { accounts(filter: { accountTag: "" }) { periodic: durableObjectsPeriodicGroups( limit: 1000 filter: { datetimeMinute_geq: "", datetimeMinute_leq: "" } ) { dimensions { namespaceId } sum { activeTime duration } } invocations: durableObjectsInvocationsAdaptiveGroups( limit: 1000 filter: { datetime_geq: "", datetime_leq: "", scriptName: "" } ) { dimensions { namespaceId } sum { requests wallTime errors } } } } } ``` What normal looked like during the December 2026 rollout: - `QueueMessage`: about 0.35 s billed per message (about 0.05 GB-s) for fast handlers. `activeTime` matched `wallTime` (1,737 s vs 1,737 s over one window). - `QueueConsumer`: about 1.6 s per run. - Errors on `QueueMessage` equal the number of runs (the resets), and no `queue_message_reset_failed`, `queue_dispatcher_queue_do_error` or `queue_dispatcher_queue_do_failed` logs. Something stuck at 60 s, 300 s or 15 minutes per object is the signature of a leftover timer or open connection. ## Emergency stop - **A queue on the Queue DO:** delete its row in `public.queue_do_targets`. The next dispatcher claim (about 1 s) sends that queue back to `/triggers/queue_consumer/sync`. No deploy needed. Objects already running finish their current run. - **Every queue at once:** delete all rows in `public.queue_do_targets`, or set `QUEUE_DO_ROUTING` to anything but `on` in the API worker (needs a deploy). - **The `QueueDispatcher` loop:** remove the `QUEUE_DISPATCHER` binding and deploy. The next alarm sees no binding and deletes itself. Queue wakeups then stop entirely, so only do this if the dispatcher itself is the problem.