Few production alerts waste more engineering hours than Error 1102: Worker exceeded resource limits. Teams see the error during a file upload, an SSR render, or a login burst, assume their Worker ran out of timeout budget, bump limits.cpu_ms in wrangler.jsonc, redeploy, and watch the exact same Error 1102 crash production ten minutes later.
The trap is that Cloudflare uses one HTTP error code (1102) for two completely unrelated V8 isolate limits: synchronous CPU execution time (exceededCpu) and the hard 128 MB V8 isolate memory ceiling (exceededMemory). Below is how to separate them in telemetry in under sixty seconds, tune limits.cpu_ms without inviting a runaway CPU bill, and refactor buffered payloads and pure-JS crypto so your Worker stays rock-solid under concurrency.
Does Cloudflare error 1102 mean CPU time exceeded or 128 MB out of memory?
Error 1102 fires when a Worker isolate hits either its per-request CPU time cap (10 ms on Free, 30s default / 5m max on Paid) or the fixed 128 MB V8 isolate memory limit. Inspect the outcome field in wrangler tail or Workers Logs (exceededCpu vs. exceededMemory) before changing a single line of code.
Run npx wrangler tail --status error while reproducing the failure (or filter Workers Logs by outcome in the Cloudflare dashboard). You will see one of two terminal outcomes:
"outcome": "exceededCpu"(cpuTimeMshits plan ceiling): Your JavaScript thread spent too many milliseconds actively executing synchronous instructions, pure-JSbcryptjshashing,JSON.parse()on multi-megabyte strings, catastrophic regex backtracking, or Cheerio/JSDOM HTML parsing. Crucially, network I/O wait time costs0 msof CPU. A Worker awaiting a40-second OpenAI stream uses~2 msof CPU and never tripsexceededCpu."outcome": "exceededMemory"(cpuTimeMsis low, isolate evicted): Your isolate's V8 heap plus externalArrayBufferallocations crossed128 MB. Upgrading from Workers Free to Workers Paid ($5.00/mo) does not raise the128 MBmemory ceiling.
Compare the verified December 2026 platform ceilings and billing rules across plans:
| Resource / Metric | Workers Free | Workers Paid ($5.00/mo Base) |
Triggers Error 1102? |
|---|---|---|---|
| Request quota & overage | 100,000 req/day |
10M req/mo included, +$0.30/M |
No (Free cap returns 1027) |
| CPU time per HTTP request | 10 ms hard cap |
30,000 ms (30s) default, up to 300,000 ms (5m) via limits.cpu_ms |
Yes (exceededCpu) |
| Monthly CPU ms billing | Included in 10 ms cap |
30M CPU ms/mo included, +$0.02/M |
Billing metric only |
| Wall-clock I/O duration | Unlimited while client connected | Unlimited while client connected | No (idle await is free) |
| V8 isolate memory limit | 128 MB per isolate |
128 MB per isolate |
Yes (exceededMemory) |
How should you configure limits.cpu_ms in wrangler.jsonc without runaway bills?
Set limits.cpu_ms explicitly in wrangler.jsonc to match each Worker's real p99 compute profile, up to 300000 (5 minutes) for heavy Paid batch Workers, or clamped down to 250–1000 ms on public API Workers as a financial circuit breaker against infinite loops and regex DoS attacks.
On the Workers Paid plan, HTTP invocations default to 30,000 ms (30s) of CPU time and can be raised up to 300,000 ms (5 minutes) using the limits block in wrangler.jsonc:
{
"$schema": "node_modules/wrangler/config-schema.json",
"name": "report-exporter",
"main": "src/index.ts",
"compatibility_date": "2026-12-04",
"limits": {
// Raise above 30,000 ms ONLY on dedicated heavy compute Workers (max 300,000)
"cpu_ms": 60000
},
"observability": {
"enabled": true,
"logs": { "enabled": true, "head_sampling_rate": 1 },
"traces": { "enabled": true, "head_sampling_rate": 0.05 }
}
}
Resist the temptation to paste "cpu_ms": 300000 onto your main public API Worker. Do the math against December 2026 Workers Paid rates (30M CPU ms included, $0.02 per extra million CPU ms):
- Healthy edge JSON and D1 API routes average
1.5 msto6 msof CPU per request. At10Mmonthly requests (40Mtotal CPU ms), CPU overage is(40 - 30) * $0.02 = $0.20/mo. - Now imagine an attacker sends crafted input into a vulnerable regular expression (ReDoS) across
50,000requests. With"cpu_ms": 300000(5m),50,000stuck invocations burn15,000,000,000(15,000M) CPU milliseconds before Cloudflare kills them, generating$299.40in pure CPU overage from a tiny50K-request probe. - Clamping your public API Worker to
"limits": { "cpu_ms": 250 }kills runaway loops1,200xfaster, capping that exact same attack at12.5MCPU ms ($0.00overage inside your30Mmonthly allowance).
You can stress-test different p99 CPU millisecond profiles alongside request and D1/R2 volumes in the Cloudflare Workers, D1 & R2 Cost Calculator.
Why do response.json() and arrayBuffer() crash the 128 MB V8 isolate limit?
Reading a 35 MB payload into V8 with await response.json(), response.text(), or request.arrayBuffer() allocates multiple simultaneous copies (raw network bytes, decoded UTF-16 JavaScript strings, and V8 object graphs) easily exceeding 128 MB on a single request or across concurrent requests sharing one warm isolate.
Engineers frequently ask why a 35 MB JSON export or R2 file upload crashes an isolate rated for 128 MB. Count the live allocations inside V8 when you run this common anti-pattern:
// ANTI-PATTERN: Multiplies memory 3x-5x and crashes on payloads >= 30 MB!
const obj = await env.EXPORTS_BUCKET.get("tenant-dump.json");
const rawText = await obj!.text(); // Copy 1 (bytes) + Copy 2 (JS string ~35-70 MB)
const parsed = JSON.parse(rawText); // Copy 3 (V8 object graph ~70-110 MB)
return Response.json({ count: parsed.items.length, items: parsed.items }); // Copy 4!
Three compounding mechanics push heap memory over the cliff:
- String + Object amplification: Decoding UTF-8 bytes into V8 strings and materializing millions of small JS object keys routinely expands a
35 MBJSON file into130 MB–170 MBof live heap before garbage collection can reclaim intermediate buffers. - Isolate concurrency sharing: A single warm Worker isolate handles multiple concurrent in-flight requests on the same edge machine. Three users uploading
25 MBmultipart files viaawait request.formData()at the same instant allocate75 MB+of buffers on top of your bundle's baseline heap. - Module-scope memory retention & schema libraries: Storing request data in global
Mapcaches (or running older pre-4.5.0Zod builds with thousands of chained schemas) elevates idle heap to40–60 MB, leaving barely65 MBof headroom beforeexceededMemorystrikes.
How do TransformStream and HTMLRewriter fix memory and CPU spikes?
Pass ReadableStream bodies (r2Object.body or upstreamResponse.body) straight to new Response() for zero-copy proxying, pipe chunked data transformations through TransformStream, and replace DOM parsers like Cheerio with Cloudflare's native streaming HTMLRewriter.
1. Zero-Copy R2 streaming & chunked NDJSON transformation
Cloudflare R2 charges $0.00/GB egress ($0.36/M Class B reads after 10M free/mo), making it ideal for serving multi-gigabyte archives, CSV exports, and AI dataset dumps through a Worker auth check. If you only need access control and custom headers, pass r2Object.body directly, peak Worker memory stays under 5 MB even for a 4 GB video:
export async function streamR2Download(key: string, env: Env): Promise<Response> {
const object = await env.ASSETS_BUCKET.get(key);
if (!object) return new Response("Not Found", { status: 404 });
const headers = new Headers();
object.writeHttpMetadata(headers);
headers.set("etag", object.httpEtag);
return new Response(object.body, { headers });
}
When you must redact or filter a 200 MB newline-delimited JSON (.ndjson) stream on the fly, process 64 KB chunks incrementally with TransformStream and TextDecoder({ stream: true }) so V8 never holds more than one line batch in RAM:
export function filterNdjsonStream(
source: ReadableStream<Uint8Array>,
allowedTenantId: string
): ReadableStream<Uint8Array> {
const decoder = new TextDecoder();
const encoder = new TextEncoder();
let carry = "";
return source.pipeThrough(
new TransformStream<Uint8Array, Uint8Array>({
transform(chunk, controller) {
carry += decoder.decode(chunk, { stream: true });
const lines = carry.split("\n");
carry = lines.pop() ?? "";
const kept: string[] = [];
for (const line of lines) {
if (!line.trim()) continue;
const row = JSON.parse(line) as { tenant_id?: string };
if (row.tenant_id === allowedTenantId) kept.push(line);
}
if (kept.length > 0) {
controller.enqueue(encoder.encode(kept.join("\n") + "\n"));
}
},
flush(controller) {
if (carry.trim()) {
const row = JSON.parse(carry) as { tenant_id?: string };
if (row.tenant_id === allowedTenantId) {
controller.enqueue(encoder.encode(carry + "\n"));
}
}
},
})
);
}
2. replace JSDOM / cheerio with streaming HTMLRewriter
Loading cheerio or linkedom inside a Worker to inject OpenGraph meta tags or rewrite image URLs buffers the entire HTML document into V8 and burns 12–40 ms of synchronous JS CPU, instantly failing the 10 ms Workers Free cap. Cloudflare's built-in HTMLRewriter executes in compiled native code on streaming chunks using < 0.5 ms of JS CPU and flat memory:
export async function injectCanonical(
upstream: Response,
canonicalUrl: string
): Promise<Response> {
return new HTMLRewriter()
.on("head", {
element(head) {
head.append(
`<link rel="canonical" href="${canonicalUrl}" />`,
{ html: true }
);
},
})
.transform(upstream);
}
Even better, if your pages come from a Next.js static build, inject metadata at build time and serve HTML directly from Cloudflare Workers Static Assets (0 CPU ms, $0.00 request cost) as detailed in Fixing Next.js Static Export Trailing Slash 404s on Cloudflare Workers, and handle responsive images at the edge using Next.js Image Optimization Cloudflare Loader Fix.
Why does Pure-JS bcrypt trigger error 1102 on Workers free and paid?
Pure-JavaScript password libraries like bcryptjs run tens of thousands of synchronous Blowfish rounds on the V8 thread, consuming 45 ms to 180 ms of CPU per login, exceeding the 10 ms Free limit on every call. Offload hashing to native crypto.subtle (PBKDF2), which runs in compiled C++ in under 1.5 ms of Worker CPU.
If Error 1102 (exceededCpu) fires exclusively on /api/auth/login or /api/auth/register, inspect package.json for bcryptjs or pure-JS argon2/scrypt polyfills. Because V8 executes those bitwise loops in JavaScript, a single bcrypt.compare(password, hash) at cost 10 burns ~65 ms of synchronous CPU (100% failure rate on Workers Free, and severe p99 latency + CPU billing spikes during Paid login bursts).
Switch password hashing to the runtime's native Web Crypto PBKDF2 (SHA-256, 100,000 iterations) paired with crypto.subtle.timingSafeEqual:
export async function hashPasswordWebCrypto(
password: string,
saltBytes = crypto.getRandomValues(new Uint8Array(16))
): Promise<string> {
const keyMaterial = await crypto.subtle.importKey(
"raw",
new TextEncoder().encode(password),
"PBKDF2",
false,
["deriveBits"]
);
const derived = await crypto.subtle.deriveBits(
{ name: "PBKDF2", salt: saltBytes, iterations: 100_000, hash: "SHA-256" },
keyMaterial,
256
);
const toHex = (buf: Uint8Array) =>
Array.from(buf, (b) => b.toString(16).padStart(2, "0")).join("");
return `pbkdf2_sha256$100000$${toHex(saltBytes)}$${toHex(new Uint8Array(derived))}`;
}
export async function verifyPasswordWebCrypto(
password: string,
stored: string
): Promise<boolean> {
const [, iterStr, saltHex, hashHex] = stored.split("$");
const fromHex = (h: string) =>
new Uint8Array(h.match(/.{1,2}/g)!.map((byte) => parseInt(byte, 16)));
const salt = fromHex(saltHex);
const expected = fromHex(hashHex);
const recomputed = await hashPasswordWebCrypto(password, salt);
const actual = fromHex(recomputed.split("$")[3]);
if (actual.byteLength !== expected.byteLength || Number(iterStr) !== 100_000) {
return false;
}
return crypto.subtle.timingSafeEqual(actual, expected);
}
Because crypto.subtle.deriveBits runs natively in BoringSSL outside V8, login CPU time plummets from ~65 ms to ~1.1 ms, working reliably on both Workers Free and Workers Paid.
Production triage checklist for eliminating error 1102
Split exceededCpu from exceededMemory in Workers Logs, eliminate response.text() / arrayBuffer() buffering above 5 MB, migrate pure-JS crypto to crypto.subtle, and bound D1 result sets.
- Check
outcomefirst: Filter Workers Logs byoutcome IN ("exceededCpu", "exceededMemory")so you never tune CPU limits for a128 MBmemory crash. - Ban unbounded body buffering: Grep your Worker codebase for
.arrayBuffer(),.text(),.json(), and.formData()on user uploads or R2/fetch responses; stream bodies >5 MBviaTransformStreamor R2 presigned URLs. - Bound D1 query result sizes: Fetching
25,000unpaginated rows from D1 into Worker memory spikes both V8 heap and D1 read bills, enforceLIMIT+ cursor pagination as shown in our Cloudflare D1 rows_read Spike & Covering Index Fix. - Clear module-scope mutable state: Remove global
let/Mapcaches that accumulate across warm isolate reuses, and upgradezodto>= 4.5.0if large validation schemas inflate baseline heap. - Right-size
limits.cpu_msand forecast costs: Set explicitcpu_msceilings inwrangler.jsonc(250–1000ms for APIs; higher only on dedicated batch Workers) and verify your monthly compute and storage budget in the Cloudflare Workers, D1 & R2 Cost Calculator.