Repository navigation
feat: per-worker CPU, memory and subrequest limits - #2
Merged
Merged
Conversation
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.
… 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
force-pushed
the
feat/worker-limits
branch
from
November 20, 2026 21:47
0cd7085 to
370da0f
Compare
The class ActorNamespace builds directly never came through getDurableObjectClass(), so it gets the all-zero limits.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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 Workercan now opt in through a new
limitsgroup:Every dimension is a
UInt32whose default is0= unlimited. A Worker with no limits keepsthe
Null*enforcers and is byte-for-byte unaffected (same isolate params, same per-requestenforcer, same startup-snapshot path). Dynamic workers (
new Worker(...)/ Worker Loader) are nottouched by this PR.
Enforcement
cpuMsenterJs()turns. A process-global watchdog samples the JS thread's CPU clock every 5 ms and callsv8::Isolate::TerminateExecution()when the deadline passes.IoContextthen reportsEXCEEDED_CPUand the request fails withError: Worker exceeded CPU time limit.(CPU_LIMIT_DETAIL_ID).VrtLimitEnforcer::enterJs/endJs/getLimitsExceeded/requireLimitsNotExceeded,VrtLimitWatchdogmemoryMbv8::Isolate::CreateParams.constraintssized from the budget, plusAddNearHeapLimitCallback: 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 asEXCEEDED_MEMORY/Error: Worker has exceeded memory limit.VrtIsolateLimitEnforcer::getCreateParams/customizeIsolate,hasExcessivelyExceededHeapLimitsubRequestsLimitEnforcer::newSubrequest()before the request can have any side effect; the (N+1)th throwsError: Too many subrequests.Calls to in-house services (isInHouse, e.g. KV/R2/actor storage) are exempt, like Cloudflare.VrtLimitEnforcer::newSubrequestCPU is measured from the thread CPU clock (
CLOCK_THREAD_CPUTIME_ID/pthread_getcpuclockidon Linux, Machthread_infoon macOS), so awaiting I/O or waiting for theisolate lock is never billed. Subrequests and CPU are per invocation (one
IoContext); memory isper 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.rsreads the group and rejects out-of-range values as config errors (which break only thatservice, fail closed) instead of clamping silently:
cpuMs≤ 3,600,000 (1 h)memoryMb≤ 65,536 (64 GiB)subRequests≤ 10,000,0000(or unset) stays unlimited and is documented inworkerd.capnp.Deliberately approximated vs. Cloudflare
memoryMbbounds the V8 JavaScript heap (old + young generation). Native allocations,isolate-external caches and
ArrayBufferbacking stores are not counted; anexitJs()externalmemory check could tighten this later.
enterStartupJs/enterStartupPythonare still unbounded. Onlyinvocation CPU is enforced (the task did not ask for a startup budget).
newOutboundConnection()hook.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).
memoryMblimit skips the startup-snapshot zygote (a snapshot deserialized intoa 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.
through the
EXCEEDED_CPU/EXCEEDED_MEMORYoutcome, the stable exception + detail id, traceevents and logs. It does not synthesize Cloudflare edge's literal HTTP 1102.
Validation
VRT buildrun 44818216347(
feat/worker-limits@370da0f8f, x64 + arm64, release config,workerd --versionand theserve smoke test).
//src/workerd/server:vrt-limits-testcovers 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.
limits = (cpuMs = 100, memoryMb = 64, subRequests = 2):/okrequest works;await setTimeout()succeeds under the 100 ms CPU budget (I/O is not billed);subRequests=2with 5 fetches returnssub-error:Too many subrequests.;while (true)fails with HTTP 500 after 111 ms and logsWorker exceeded CPU time limit.;Worker has exceeded memory limit.,without aborting the process;
/okagain after both the CPU and the memory termination;memoryMb = 1still starts and serves.CPU_LIMIT_DETAIL_ID/MEMORY_LIMIT_DETAIL_IDdetail 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— thelimitsgroup.src/workerd/server/server/bridge.rs,server/worker.rs—WorkerSpec.limitsand validation.src/workerd/server/factory/worker-factory.c++,worker-factory-impl.h— wiring only.BUILD.bazelfiles,FORK.mdpatch list.Follow-up outside this repo: Vibeploy's
doc/platform/workers-runtime-quotas.mdshould describethe new config surface.
Scope note
The branch also carries dynamic-Worker limits (
code.limits/ entrypointoptions.limits), merged with the loading Worker'slimitsas a ceiling: a dynamic Worker may tighten but never widen it, and awd-testcovers it. Static Workers keep the zero default and theNull*enforcers.