Skip to content

feat: per-worker CPU, memory and subrequest limits - #2

Merged
airyland merged 4 commits into
vrtfrom
feat/worker-limits
Nov 20, 2026
Merged

airyland merged 4 commits into
vrtfrom
feat/worker-limits

Conversation

@airyland

@airyland airyland commented Nov 20, 2026 •

Copy link
Copy Markdown

What this adds

Per-Worker resource limits for statically configured Workers. Until now the standalone server
used NullIsolateLimitEnforcer / NullLimitEnforcer, so a config Worker ran unbounded. A Worker
can now opt in through a new limits group:

( name = "api",
  worker = (
    modules = [ (name = "api.js", esModule = embed "api.js") ],
    compatibilityDate = "2026-09-01",
    limits = (
      cpuMs = 50,        # CPU budget per invocation; 50 ms
      memoryMb = 128,    # JS heap budget for the isolate
      subRequests = 50,  # outbound subrequests per invocation
    ),
  ),
)

Every dimension is a UInt32 whose default is 0 = unlimited. A Worker with no limits keeps
the Null* enforcers and is byte-for-byte unaffected (same isolate params, same per-request
enforcer, same startup-snapshot path). Dynamic workers (new Worker(...) / Worker Loader) are not
touched by this PR.

Enforcement

Limit Mechanism Where
cpuMs Per-invocation thread CPU time accumulated across enterJs() turns. A process-global watchdog samples the JS thread's CPU clock every 5 ms and calls v8::Isolate::TerminateExecution() when the deadline passes. IoContext then reports EXCEEDED_CPU and the request fails with Error: Worker exceeded CPU time limit. (CPU_LIMIT_DETAIL_ID). VrtLimitEnforcer::enterJs/endJs/getLimitsExceeded/requireLimitsNotExceeded, VrtLimitWatchdog
memoryMb v8::Isolate::CreateParams.constraints sized from the budget, plus AddNearHeapLimitCallback: the callback blames the running invocation, terminates V8 and grants bounded emergency headroom so the process unwinds instead of aborting. hasExcessivelyExceededHeapLimit() reflects the flag synchronously. Reported as EXCEEDED_MEMORY / Error: Worker has exceeded memory limit. VrtIsolateLimitEnforcer::getCreateParams/customizeIsolate, hasExcessivelyExceededHeapLimit
subRequests Counter checked in LimitEnforcer::newSubrequest() before the request can have any side effect; the (N+1)th throws Error: Too many subrequests. Calls to in-house services (isInHouse, e.g. KV/R2/actor storage) are exempt, like Cloudflare. VrtLimitEnforcer::newSubrequest

CPU is measured from the thread CPU clock (CLOCK_THREAD_CPUTIME_ID /
pthread_getcpuclockid on Linux, Mach thread_info on macOS), so awaiting I/O or waiting for the
isolate lock is never billed. Subrequests and CPU are per invocation (one IoContext); memory is
per isolate. CPU/memory violations fail the invocation, not the isolate: the next request runs
normally (the standalone server has no isolate-recycling hook).

Configuration validation

worker.rs reads the group and rejects out-of-range values as config errors (which break only that
service, fail closed) instead of clamping silently:

  • cpuMs ≤ 3,600,000 (1 h)
  • memoryMb ≤ 65,536 (64 GiB)
  • subRequests ≤ 10,000,000

0 (or unset) stays unlimited and is documented in workerd.capnp.

Deliberately approximated vs. Cloudflare

  • memoryMb bounds the V8 JavaScript heap (old + young generation). Native allocations,
    isolate-external caches and ArrayBuffer backing stores are not counted; an exitJs() external
    memory check could tighten this later.
  • No startup-CPU limit: enterStartupJs/enterStartupPython are still unbounded. Only
    invocation CPU is enforced (the task did not ask for a startup budget).
  • No outbound-connection limit: upstream has no newOutboundConnection() hook.
  • The watchdog samples every 5 ms, so a CPU overrun overshoots by at most one sample. If a turn
    ends in the window between budget exhaustion and the next sample, the invocation is marked
    exceeded but the already-produced response can still succeed (documented in the code).
  • A Worker with a memoryMb limit skips the startup-snapshot zygote (a snapshot deserialized into
    a smaller heap can fail fatally). It evaluates top level in its own isolate, where the
    near-heap-limit callback can terminate gracefully; unlimited Workers keep the snapshot path.
  • The standalone HTTP layer still returns its usual 500 for a failed request; the limit is visible
    through the EXCEEDED_CPU/EXCEEDED_MEMORY outcome, the stable exception + detail id, trace
    events and logs. It does not synthesize Cloudflare edge's literal HTTP 1102.

Validation

  • CI green: VRT build run 44818216347
    (feat/worker-limits @ 370da0f8f, x64 + arm64, release config, workerd --version and the
    serve smoke test).
  • New //src/workerd/server:vrt-limits-test covers unlimited defaults, memory-budget arithmetic,
    the subrequest budget (in-house exemption, exact exception text), CPU/memory outcome mapping and
    exception detail ids, actor top-up, and termination counter bookkeeping.
  • Manual end-to-end run of the built arm64 binary (ubuntu:24.04 container) with
    limits = (cpuMs = 100, memoryMb = 64, subRequests = 2):
    • plain /ok request works;
    • 300 ms of await setTimeout() succeeds under the 100 ms CPU budget (I/O is not billed);
    • subRequests=2 with 5 fetches returns sub-error:Too many subrequests.;
    • while (true) fails with HTTP 500 after 111 ms and logs
      Worker exceeded CPU time limit.;
    • an allocation loop fails with HTTP 500 and logs Worker has exceeded memory limit.,
      without aborting the process;
    • the Worker serves /ok again after both the CPU and the memory termination;
    • a separate Worker with memoryMb = 1 still starts and serves.
  • The same config/code paths were manually checked against the reported exception text and the
    CPU_LIMIT_DETAIL_ID / MEMORY_LIMIT_DETAIL_ID detail ids.

Files

  • src/workerd/server/vrt-limits.{h,c++} — the whole implementation (isolate/request enforcers,
    watchdog, thread CPU clock, stable exceptions). Self-contained so upstream syncs see new files
    rather than edits.
  • src/workerd/server/vrt-limits-test.c++ — unit tests.
  • src/workerd/server/workerd.capnp — the limits group.
  • src/workerd/server/server/bridge.rs, server/worker.rs — WorkerSpec.limits and validation.
  • src/workerd/server/factory/worker-factory.c++, worker-factory-impl.h — wiring only.
  • BUILD.bazel files, FORK.md patch list.

Follow-up outside this repo: Vibeploy's doc/platform/workers-runtime-quotas.md should describe
the new config surface.


Scope note

The branch also carries dynamic-Worker limits (code.limits / entrypoint options.limits), merged with the loading Worker's limits as a ceiling: a dynamic Worker may tighten but never widen it, and a wd-test covers it. Static Workers keep the zero default and the Null* enforcers.

Add a `limits` group to the config Worker and enforce it in the standalone
server, where config Workers previously ran on the null limit enforcers.

- cpuMs: per-invocation CPU budget accumulated from the thread CPU clock
  across enterJs() turns. A process-global watchdog samples the JS thread's
  CPU every 5 ms and terminates the isolate through V8, so IoContext reports
  EXCEEDED_CPU with the stable "Worker exceeded CPU time limit." error.
- memoryMb: per-isolate V8 heap budget from CreateParams constraints, plus a
  near-heap-limit callback that blames the running invocation and terminates
  it instead of aborting the process.
- subRequests: per-invocation outbound subrequest budget, throwing
  "Too many subrequests." before the request has any effect. In-house
  services (KV, R2, actor storage) are exempt, like Cloudflare's.

Zero keeps every dimension unlimited: such a Worker still uses the Null
enforcers and behaves exactly as before. Limits are validated in the Rust
config path with explicit ceilings.

The implementation lives in src/workerd/server/vrt-limits.{h,c++} so the
wiring is limited to the Rust config/bridge, worker-factory.c++ and the
capnp schema.
@airyland airyland added the limits Per-Worker resource limits label Nov 20, 2026
… parent ceiling

Dynamically loaded Workers previously accepted `WorkerCode.limits` and
`getEntrypoint()`/`getDurableObjectClass()` `options.limits` but the
standalone server dropped them on the floor: new_dynamic hardcoded
WorkerLimits{0,0,0} and the options were never forwarded past the C++
stub channel. This wires them end to end with Cloudflare's documented
semantics:

- code.limits becomes the worker's own limits, merged with the loading
  Worker's limits group (its spec.limits) — the lower of the two wins,
  matching "a dynamic worker's limits may tighten but never exceed the
  loading worker's plan". Memory, which ResourceLimits cannot express,
  therefore inherits the parent's heap budget.
- options.limits rides WorkerStub::entrypoint/actor_class through Rust
  into worker_start_request, where createEntrypoint merges it with the
  worker's own limits the same documented way.
- Dynamic workers always get isolate limit state so a per-invocation
  CPU or subrequest limit has liveness to enforce against even when the
  worker itself is unlimited.

worker-loader-vrt-limits-test covers code.limits, both options, the
lower-of-two merge in both directions, a DO-class invocation, and the
parent ceiling inherited by a worker that cannot express memory.
airyland and others added 2 commits November 20, 2026 16:47
The class ActorNamespace builds directly never came through
getDurableObjectClass(), so it gets the all-zero limits.
@airyland
airyland merged commit 8bb1fe0 into vrt Nov 20, 2026
3 checks passed
@airyland
airyland deleted the feat/worker-limits branch November 20, 2026 22:08
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

limits Per-Worker resource limits

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant