Skip to content

Build the Cloudflare control-plane runtime once per isolate - #296

Merged
tnkuehne merged 3 commits into
mainfrom
runtime-per-isolate
Nov 22, 2026
Merged

tnkuehne merged 3 commits into
mainfrom
runtime-per-isolate

Conversation

@tnkuehne

@tnkuehne tnkuehne commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

The Cloudflare request hook built the whole control-plane runtime for every request: Better Auth with its plugins, endpoints and schema check, plus every service. A 40-second production CPU profile of the hosted control plane spent 51 percent in garbage collection, 13 percent building the runtime and 11 percent creating Better Auth. On hosted, a request such as getApps now spends more of its server time on CPU than on the database.

Changes

  • One runtime per isolate: createCloudflareRuntime builds the runtime on an isolate's first request and reuses it afterwards. If initialization fails, the next request builds it again instead of keeping the failure.
  • Per-request I/O: Workers do not allow I/O on behalf of another request. So each request still opens its own database pool, PostHog analytics client and installation reporting client. The shared runtime receives stand-ins that reach the current request's instances through AsyncLocalStorage:
    • the database: a proxy over the request's Drizzle instance
    • analytics: an explicit Observation that forwards to the request's client
    • reporting: an object with every reporting method, so a new method fails to typecheck until it is forwarded
  • Request hook: hooks.cloudflare.ts runs request handling in that scope and closes the three clients when the response finishes, as before. Deferred rendering keeps the scope because it continues from that call.
  • Better Auth schema check: stays off on Cloudflare. At low traffic isolates start often, and the check would run on each start. Node still runs it, so tests compare Better Auth's expected schema with ours.
  • Unchanged: Node and Workflows. Workflows already open their own database connection per step.

Validation

  • pnpm check
  • Cloudflare control-plane tests against workerd with the local Hyperdrive binding (RUN_CLOUDFLARE_TESTS=1): 16 passed. This includes "keeps sessions and PostgreSQL connections scoped correctly across concurrent requests" and initialization error reporting.
  • Control-plane Vitest suite: 956 passed, 656 skipped.
  • Local Worker timing for 40 signed-in requests to /: median 14 ms on this branch, 15 to 17 ms on main. A local machine shows little of the difference. A production CPU profile after deploy will show the real effect.

RetriggerView in GreptileConfidence Score: 5/5

The PR appears safe to merge; the previous crash-report issue is fixed.

Summary

Builds one shared Cloudflare runtime per isolate while keeping database, analytics, and reporting clients separate for each request.

  • Cloudflare reuses one control-plane runtime per isolate.
  • Cloudflare request handling keeps its own services through deferred work and error reporting.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart TD
  A[Request] --> B[Create request clients]
  B --> C[Run with request scope]
  C --> D[Shared runtime]
  C --> E{Hook outcome}
  E -->|Response| F[Close clients when body ends]
  E -->|Unexpected error| G[Save request runtime]
  G --> H[Report inside saved scope]
  H --> I[Close request clients]
Loading

Reviews (2) · Last reviewed commit: "Report unexpected hook errors with their..." · Reviewed by Greptile

Each request built the whole runtime again, including Better Auth with
its plugins, endpoints and schema check, and every service. A CPU profile
of the hosted control plane spent about half its time collecting the
resulting garbage and 13 percent building the runtime.

Workers forbid I/O on behalf of another request, so the database pool and
the analytics and reporting clients stay per request. The shared runtime
reaches them through AsyncLocalStorage. The request hook runs request
handling in that scope and closes the three clients afterwards as before.
A failed initialization is retried by the next request.
At low traffic isolates start often, and the check would run at each
start. Node still runs it, so tests compare the schemas.
@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented Nov 22, 2026 •

Copy link
Copy Markdown

Deploying with  Cloudflare Workers  Cloudflare Workers

The latest updates on your project. Learn more about integrating Git with Workers.

Status Name Latest Commit Updated (UTC)
✅ Deployment successful!
View logs
widefleet-docs c503bbc Nov 22 2026, 03:01 PM

SvelteKit calls handleError after the hook has returned, outside the
request scope, so the installation's crash report could not reach the
request's reporting client. The services now stay open until handleError
has reported the error, then close. Redirects and HTTP errors, which do
not reach handleError, still close them right away.
@tnkuehne
tnkuehne merged commit 697a6b6 into main Nov 22, 2026
16 checks passed
@tnkuehne
tnkuehne deleted the runtime-per-isolate branch November 22, 2026 15:22
tnkuehne added a commit that referenced this pull request Nov 22, 2026
After #296, every request to the hosted control plane failed with 500:
"The control plane runtime was used outside a request".

## Cause

Building the runtime starts Better Auth's initialization, and the hosted
extension's authentication plugin reads the installation from the
database in its `init`. #296 built the runtime in
`createCloudflareRuntime`, before the request hook enters the
`AsyncLocalStorage` scope that holds the request's database pool. That
read therefore ran outside any request. The public Cloudflare tests did
not catch it because their build has no extension with such a plugin.

## Changes

- `get` creates and awaits the shared runtime inside the request's
scope. Initialization reads the database with the pool of the request
that first needs the runtime. This also holds when the runtime is first
needed outside the hook's `run`, for example while reporting an error.
- The Cloudflare CI job builds the control plane with
`plugin-init-extension.fixture.ts`. That extension's authentication
plugin reads the installation during Better Auth's initialization, as
the hosted extension does.

## Validation

Locally, with the control plane built with the fixture extension:
- Without this change, the Cloudflare control-plane suite fails during
setup, as hosted did.
- With this change, all 16 tests pass.

Typecheck, lint and format pass.


<!-- greptile_comment -->

<!-- greptile_summary -->

<h2><a
href="https://app.greptile.com/api/retrigger?id=115798572&amp;sig=bab0f2614f144ec9561458327dfad23d77a3af949245b28f951244bcd0eed160"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://greptile-static-assets.s3.amazonaws.com/badges/RetriggerDark.svg?v=2"><source
media="(prefers-color-scheme: light)"
srcset="https://greptile-static-assets.s3.amazonaws.com/badges/Retrigger.svg?v=2"><img
alt="Retrigger"
src="https://greptile-static-assets.s3.amazonaws.com/badges/Retrigger.svg?v=2"
align="right"></picture></a><a
href="https://app.greptile.com/-/switch-tenant?tenant=mendra&amp;next=%2Fwidefleet%2Fwidefleet%2Fpull%2F302&amp;utm_source=greptile_review&amp;utm_medium=github&amp;utm_campaign=view_in_greptile"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://greptile-static-assets.s3.amazonaws.com/badges/ViewInGreptileDark.svg?v=2"><source
media="(prefers-color-scheme: light)"
srcset="https://greptile-static-assets.s3.amazonaws.com/badges/ViewInGreptile.svg?v=2"><img
alt="View in Greptile"
src="https://greptile-static-assets.s3.amazonaws.com/badges/ViewInGreptile.svg?v=2"
align="right"></picture></a>Confidence Score: 5/5</h2>

<!-- greptile-impact-verdict --> The PR appears safe to merge; no
actionable issues were found.

<details open><summary><h3>Summary</h3></summary>

Builds the shared Cloudflare runtime inside the request scope so
authentication plugins can read the database during startup.
- Cloudflare requests initialize the shared runtime inside their request
scope.
</details>

<details open><summary><h3>Diagram</h3></summary>

```mermaid
sequenceDiagram
  participant Request
  participant Scope as Request scope
  participant Shared as Shared runtime
  participant DB as Request database
  Request->>Scope: get()
  Scope->>Shared: Create if missing
  Shared->>DB: Initialize authentication plugins
  DB-->>Shared: Installation
  Shared-->>Scope: Ready runtime
  Scope-->>Request: Runtime
```
</details>

<!-- greptile_confidence_score:5 -->

<sub>Reviews (1) · Last reviewed commit: ["Build the shared Cloudflare
runtime
insi..."](11efbd1)
· [Reviewed by
Greptile](https://www.greptile.com/?utm_source=greptile_review&utm_medium=github&utm_campaign=review_public&utm_content=widefleet/widefleet)</sub>

<!-- /greptile_comment -->
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant