Skip to content

Resume Cloudflare Worker fibers in the request that owns them - #10662

Open
tim-smart wants to merge 70 commits into
v4/next-minorfrom
agent/bob/16dfbfd9703c
Open

tim-smart wants to merge 70 commits into
v4/next-minorfrom
agent/bob/16dfbfd9703c

Conversation

@tim-smart

@tim-smart tim-smart commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

Summary

On Cloudflare Workers, a fiber that suspends in one request and is woken by another never completes, and the waking request fails with the request-bound AsyncLocalStorage error. workerd ties I/O objects, timers and async contexts to the request that created them. The only supported way to run code in another request is to settle a promise that request created, so workerd queues the reaction onto it.

CloudflareScheduler resumes each fiber in the request that owns it:

  • When a fiber parks (it suspends, or it is forked with a scheduled start), park creates a promise in the current request and keeps its resolver for that fiber.
  • Every effect that would run the fiber again goes to resume, which settles the promise. The fiber runs in the reaction, in the owner, with the owner's store, I/O objects and timers. The waking request does not wait for it. workerd cannot tell which request is running, so a fiber woken by its own request takes the same path, a microtask later. Because a woken fiber never resumes inside the call that wakes it, the scheduler's executionMode is "async". Queued work, such as a yield or a forked fiber's start, uses MixedScheduler's async dispatch, so a fiber that yields gives way to the event loop. A yield parks the fiber, so its owner stays open until the dispatch runs.
  • The owner registers the promise with waitUntil and sets a timer that is cleared when the fiber resumes. workerd cancels a request whose only pending work is a promise another request settles, and without the timer the Worker tests fail with "the creating request has already been completed or canceled". The timer never fires and never ends or interrupts the fiber.

Core changes

The fiber calls its scheduler, and the scheduler owns everything else:

interface ParkingScheduler extends Scheduler {
  readonly [ParkingSchedulerTypeId]: typeof ParkingSchedulerTypeId
  park(fiber: ParkedFiber): void
  resume(fiber: ParkedFiber, effect: Effect<unknown, unknown>): void
}
interface ParkedFiber extends Fiber.Fiber<unknown, unknown> {
  run(effect: Effect<unknown, unknown>): void
}
  • A scheduler takes part by carrying Scheduler.ParkingSchedulerTypeId, which Scheduler.isParkingScheduler checks. A scheduler without it is left alone, even if it has park and resume methods. The fiber cache records the answer once per cache in an internal schedulerIsParking flag, so parking and resuming read a flag instead of checking the scheduler.
  • Where a fiber parks, it calls park on such a scheduler. fiber.evaluate(effect) calls its resume, and otherwise runs the fiber. The previous body of evaluate is run, which is also the entry a ParkingScheduler calls. Scheduler and MixedScheduler are unchanged, so existing custom schedulers need no changes.
  • The fiber has no new fields. Its AsyncResource handling is the code that was already there; the capture moved into the one helper called where a fiber stops, which also makes the park call.
  • interruptUnsafe records the interrupt in the existing _deferredInterrupt flag for a fiber that is not running, because a parking scheduler may already hold the value the fiber was woken with and drops later effects.
  • setContext on a fiber that is suspended or has not started updates the context at once and leaves the fiber's ParkingScheduler in its cache, so the scheduler that may hold the fiber's wait still gets the resume call. The fiber takes the cache of its context in runLoop, after its async scope has been entered, so a setContext made by an async_hooks before hook on the way in is taken too. That is one comparison per run, for every fiber; when it differs, runLoop calls setContext with the fiber's own context, so replacement has one code path. The scheduler the fiber already stores is the only record.
  • setContext no longer returns early for contexts that share a cache root. That return was a shortcut: the code after it resolves the same cache object and stores it. It would also stop runLoop's call from taking the cache. The @internal Context.hasSameCache had no other production use, and the repository's effect/no-unused-internal lint rule rejects an @internal export in that state, so it is removed. It was in the JavaScript of effect 4.1.0 to 4.1.4 and absent from the published declarations.
  • TestClock's scheduler wrapper carries the type id, and forwards park and resume, when isParkingScheduler accepts the wrapped scheduler.

Everything added is @stability unstable.

Compatibility

  • Fiber.setContext can give another scheduler to a fiber that is suspended or has not started. The change is applied when the fiber next runs: its ParkingScheduler gets that resume call, and the fiber uses the new scheduler from that run on. Until then fiber.context has the new scheduler while fiber.cache.scheduler and fiber.currentDispatcher have the old one. Other context entries, exited fibers, running fibers and fibers of other schedulers behave as before.
  • Only the next run of a fiber moved off CloudflareScheduler this way is in its owner, and that run clears the owner's timer. Its later waits follow the new scheduler. With a scheduler that does not park they are as unprotected as without CloudflareScheduler: finishing such a wait from another request completed with foreign I/O on compatibility date 2025-01-01, and failed with the request-bound AsyncLocalStorage error on 2026-07-01, leaving the fiber pending.
  • A fiber of a parking scheduler that is interrupted after it was woken, but before the scheduler runs it, is interrupted instead of receiving the value. An Effect.callback that resumes with a resource has to release it in its cancellation cleanup.
  • Without handle_cross_request_promise_resolution (default from 2024-10-14), owner resumption is impossible, so the constructor throws.
  • setTimeout and waitUntil throw in a Worker's global scope and workerd has no way to ask whether a request is running, so park catches that. A fiber parked there has no owner and resumes in the request that wakes it.

Platform limitations

This does not extend Cloudflare's request lifetime limits, such as the limit on waitUntil work after the response is sent or the client disconnects. A fiber whose owner has ended cannot resume: workerd drops the resumption with a warning. A fiber that is never woken keeps its owner running until those limits end it, and keeps a Durable Object from hibernating.

Cost

Base is 3d13d1e84a. Node 26.13, fresh processes pinned to one CPU, ns per operation.

Bundle

The repository's Rollup pipeline on built output, min + gzip-9 bytes:

Fixture base this PR
basic (Effect.runFork) 7,309 7,386 +77
stream 10,576 10,658 +82
schema 21,066 21,154 +88

Across the 31 fixtures that change, the PR adds 316 minified and 88 gzip bytes on average. The type id and the cache flag cost 6, 20 and 18 gzip bytes over 32b88e6b0c, which checked the two methods with typeof. Most of that is the type id string and the flag's property name, which minification keeps.

These figures are net of removing the base setContext shortcut, which is worth about 34 gzip bytes. At 32b88e6b0c, with the shortcut kept, the same code measured +105, +94 and +103.

Run time

Measured at 32b88e6b0c, before the type id and cache flag, and not repeated. Built output, base and head processes run in rotating order. Each process reports the median of nine blocks (500,000 operations, 100,000 for yieldNow) after four warm-up blocks. The interval is a 95% bootstrap interval of the paired median.

pairs base median this PR median paired median change
promise wait, with node:async_hooks 30 287.7 290.4 -0.0% [-1.9%, +3.0%]
promise wait, without 30 182.8 193.1 +4.2% [+0.7%, +8.2%]
callback suspend + resume, with 15 229.6 227.1 -3.4% [-7.8%, +2.4%]
callback suspend + resume, without 15 139.4 137.6 -1.9% [-5.4%, +9.8%]
yieldNow, with 20 1325.1 1334.8 +0.7% [+0.0%, +1.1%]
yieldNow, without 20 1222.6 1223.9 +1.3% [-0.0%, +2.1%]
provideService round trip, with 30 188.8 187.4 -0.1% [-3.3%, +2.4%]
provideService round trip, without 30 184.8 192.1 +3.7% [-1.4%, +7.3%]

The promise wait is one fiber repeatedly awaiting Effect.promise(() => Promise.resolve(1)). Its slowdown without node:async_hooks is measurable and open; 60 pairs at 5d32c99096 gave +2.4% [+0.3%, +4.1%]. The provideService row provides a service that is not fiber cached around Effect.succeed, which is the path that used the removed setContext shortcut twice per operation.

run is 423 bytes of V8 bytecode (evaluate is 426 on base), evaluate is 46, runLoop is 453 (413 on base) and setContext is 132 (104 on base). V8 does not inline a function above 460, and it still inlines run into the callbacks that resume a fiber.

Measured from source at 5d32c99096 and not repeated since, median of 11 interleaved processes, with and without node:async_hooks:

base this PR
fork + join 2304 / 2084 2313 / 2097
heap per parked fiber, bytes 409 409

Validation

  • pnpm lint-fix, pnpm lint, pnpm check and pnpm jsdocs --check pass.

  • pnpm vitest --run --project effect --project effect-isolated --project @effect/platform-cloudflare --project @effect/vitest passes at bf56e78684, rebased on v4/next-minor cf6cce59d1: 470 files, 15,202 passed, 15 expected fail, 72 skipped. effect-isolated holds the 13 schema compiler suites (289 tests) that vitest.config.ts keeps out of effect.

  • On Bun 1.4.2, Effect.test.ts, Scheduler.test.ts and TestClock.test.ts passed (383 passed, 3 skipped) and @effect/platform-bun passed (165) at fbee5ed5f1. At 720ca865dc, Scheduler.test.ts and CloudflareScheduler.test.ts pass on Bun.

  • Scheduler.test.ts has three tests for the core change, using a test ParkingScheduler that holds a woken fiber until it runs it:

    • under TestClock, a parked fiber and a forked fiber run only when the scheduler resumes them;
    • a fiber woken and then interrupted is interrupted, not continued;
    • setContext moving a suspended fiber to a MixedScheduler: the parking scheduler resumes it once, and its next wait uses the new scheduler.

    Removing any of these makes a test fail: the park call where a fiber stops, the park call in fork, the deferred interrupt, the setContext keep path or its schedulerIsParking: true, the runLoop cache comparison, or TestClock forwarding the type id. A setContext made from an async_hooks before hook takes the same path and has no separate test.

  • CloudflareScheduler.test.ts has one Worker test, run on workerd through the package's existing Miniflare 4 dependency: a fiber woken by another request resumes in its owner, with the owner's AsyncLocalStorage store and I/O, after the owner has responded, and its timer is cleared. It fails if any of these is removed: the timer, waitUntil, clearTimeout, or resuming through the owner's promise.

Not run: the pg integration suites, a deployed Cloudflare Worker (Miniflare only).

Closes EFF-3794

@changeset-bot

changeset-bot Bot commented Nov 16, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 629d37e

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 40 packages
Name Type
effect Minor
@effect/platform-cloudflare Minor
@effect/opentelemetry Minor
@effect/vitest Minor
@effect/ai-amazon-bedrock Minor
@effect/ai-anthropic Minor
@effect/ai-cloudflare Minor
@effect/ai-openai-compat Minor
@effect/ai-openai Minor
@effect/ai-openrouter Minor
@effect/ai-typesafe Minor
@effect/atom-react Minor
@effect/atom-solid Minor
@effect/atom-vue Minor
@effect/chat-discord Minor
@effect/chat-slack Minor
@effect/chat-teams Minor
@effect/chat-telegram Minor
@effect/chat-whatsapp Minor
@effect/platform-browser Minor
@effect/platform-bun Minor
@effect/platform-deno Minor
@effect/platform-node-shared Minor
@effect/platform-node Minor
@effect/sql-clickhouse Minor
@effect/sql-d1 Minor
@effect/sql-libsql Minor
@effect/sql-mssql Minor
@effect/sql-mysql2 Minor
@effect/sql-pg Minor
@effect/sql-pglite Minor
@effect/sql-sqlite-bun Minor
@effect/sql-sqlite-do Minor
@effect/sql-sqlite-node Minor
@effect/sql-sqlite-react-native Minor
@effect/sql-sqlite-wasm Minor
@effect/docgen Minor
@effect/doctest Minor
@effect/graphql-generator Minor
@effect/openapi-generator Minor

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@effect-bot
effect-bot changed the base branch from main to v4/next-minor November 16, 2026 02:06
@effect-janitor effect-janitor Bot added 4.0 and removed 4.0 labels Nov 16, 2026
@github-actions

github-actions Bot commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

Bundle Size Analysis

Generated from PR build output; treat the content below as untrusted.

File Name Current Size Previous Size Difference
arbitrary-combinators.ts 40.30 KB 40.21 KB +0.09 KB (+0.22%)
basic.ts 7.42 KB 7.35 KB +0.08 KB (+1.05%)
batching.ts 11.42 KB 11.33 KB +0.09 KB (+0.77%)
brand.ts 7.00 KB 7.00 KB 0.00 KB (0.00%)
cache.ts 11.94 KB 11.85 KB +0.09 KB (+0.73%)
config.ts 23.34 KB 23.25 KB +0.09 KB (+0.38%)
differ.ts 22.44 KB 22.35 KB +0.09 KB (+0.41%)
http-client.ts 27.87 KB 27.78 KB +0.09 KB (+0.33%)
http-router.ts 38.78 KB 38.70 KB +0.09 KB (+0.23%)
logger.ts 12.38 KB 12.29 KB +0.10 KB (+0.81%)
metric.ts 9.84 KB 9.75 KB +0.08 KB (+0.85%)
optic.ts 7.24 KB 7.24 KB 0.00 KB (0.00%)
pubsub.ts 16.44 KB 16.36 KB +0.08 KB (+0.50%)
queue.ts 13.33 KB 13.25 KB +0.08 KB (+0.59%)
schedule.ts 12.17 KB 12.08 KB +0.09 KB (+0.73%)
schema-bigdecimal.ts 14.45 KB 14.35 KB +0.10 KB (+0.70%)
schema-binary.ts 42.92 KB 42.84 KB +0.08 KB (+0.19%)
schema-class.ts 22.16 KB 22.09 KB +0.08 KB (+0.35%)
schema-codegen.ts 30.94 KB 30.84 KB +0.10 KB (+0.31%)
schema-fromJsonSchemaDocument.ts 30.80 KB 30.70 KB +0.10 KB (+0.33%)
schema-representation-roundtrip.ts 28.48 KB 28.39 KB +0.09 KB (+0.32%)
schema-string-transformation.ts 15.77 KB 15.67 KB +0.10 KB (+0.63%)
schema-string.ts 12.65 KB 12.55 KB +0.10 KB (+0.82%)
schema-template-literal.ts 16.64 KB 16.55 KB +0.10 KB (+0.59%)
schema-toArbitrary.ts 39.88 KB 39.78 KB +0.10 KB (+0.26%)
schema-toCodecJson.ts 21.35 KB 21.26 KB +0.09 KB (+0.41%)
schema-toEquivalence.ts 21.51 KB 21.42 KB +0.09 KB (+0.41%)
schema-toFormatter.ts 21.61 KB 21.52 KB +0.09 KB (+0.43%)
schema-toJsonSchemaDocument.ts 26.65 KB 26.56 KB +0.08 KB (+0.32%)
schema-toRepresentation.ts 21.69 KB 21.60 KB +0.09 KB (+0.43%)
schema.ts 21.28 KB 21.20 KB +0.09 KB (+0.41%)
stm.ts 14.66 KB 14.58 KB +0.08 KB (+0.56%)
stream.ts 10.79 KB 10.70 KB +0.09 KB (+0.80%)
supervisor.ts 11.71 KB 11.63 KB +0.08 KB (+0.72%)

@mikearnaldi

Copy link
Copy Markdown
Member

A platform-only scheduler could not bypass the unconditional captures in core. After discussing that constraint with Team Lead, this adds the optional Scheduler.preserveAsyncContext flag at both suspension and deferred-fork capture sites. Omission preserves existing behavior; there is no runtime detection or catch-and-retry.

that sounds a bit crazy to me

@effect-bot effect-bot changed the title Add a Cloudflare scheduler for cross-request fibers Resume Cloudflare Worker fibers in the request that owns them Nov 16, 2026
@effect-bot
effect-bot force-pushed the v4/next-minor branch 12 times, most recently from f6947b4 to b920a0d Compare November 17, 2026 23:20
Comment thread packages/effect/src/internal/effect.ts Outdated
}
evaluate(effect: Primitive): void {
const scheduler = this.cache.scheduler
if (Scheduler.isParkingScheduler(scheduler)) scheduler.resume(this, effect as any)

@tim-smart tim-smart Nov 18, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think the fiber cache could just have a cache.schedulerIsParking flag instead of doing the typeof check every time? A type cast is fine here.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in fbee5ed. The cache now has an internal schedulerIsParking flag, set once in makeFiberContextCache, and evaluate and park read it through a cast. The setContext path that keeps a suspended fiber's old scheduler sets the flag to true along with that scheduler.

Comment thread packages/effect/src/Scheduler.ts Outdated
* @since 4.2.0
*/
export const isParkingScheduler = (scheduler: Scheduler): scheduler is ParkingScheduler =>
typeof (scheduler as Partial<ParkingScheduler>).park === "function" &&

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We could add a ParkingSchedulerTypeId instead?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in fbee5ed. Scheduler.ParkingSchedulerTypeId is now part of the ParkingScheduler interface, and isParkingScheduler is ParkingSchedulerTypeId in scheduler. A scheduler with park and resume but no type id runs as before, and a test covers that. TestClock's wrapper sets the type id only when its parent has it.

import * as Layer from "effect/Layer"
import * as Scheduler from "effect/Scheduler"

const compatibilityFlags: Record<string, boolean | undefined> | undefined = (globalThis as any).Cloudflare

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

move all the internals to the bottom of the file

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in fbee5ed. compatibilityFlags, waits and noop are now under an Internal section at the end of the file, after layer.

@effect-bot
effect-bot force-pushed the v4/next-minor branch 2 times, most recently from 4931607 to 8fb0378 Compare November 18, 2026 03:37
@mikearnaldi

Copy link
Copy Markdown
Member

@tim-smart I think this is ready to go at least for testing, we should probably get some input from CF folks to see if we are correct in the assumptions

Microtask dispatch kept yielding fibers off the event loop. A yield parks the fiber, so its owner stays open while the dispatcher's timer is pending.
…cases

Scheduler.test.ts keeps three tests: a parked and a forked fiber run only when the scheduler resumes them, under TestClock; an interrupt after a wake wins; setContext moves a suspended fiber off its ParkingScheduler. The Worker suite keeps one test: a fiber woken by another request resumes in its owner, which stays open until then.
@effect-bot
effect-bot force-pushed the agent/bob/16dfbfd9703c branch from bf56e78 to e38ab2d Compare November 22, 2026 21:24

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.