# Cloudflare Workers Error 1102 Fix: CPU Time & 128 MB Memory Limits

> Canonical URL: https://stackquota.com/guides/cloudflare-workers-error-1102-cpu-memory-limit-fix/
> Checked: 2026-12-04 · Published: 2026-12-04

Fix Cloudflare Workers Error 1102 (Worker exceeded resource limits): separate 10ms/30s CPU caps from 128 MB V8 OOMs with limits.cpu_ms and streaming.

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?

**Quick answer:** `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:

1. **`"outcome": "exceededCpu"` (`cpuTimeMs` hits plan ceiling):** Your JavaScript thread spent too many milliseconds actively executing synchronous instructions, pure-JS `bcryptjs` hashing, `JSON.parse()` on multi-megabyte strings, catastrophic regex backtracking, or Cheerio/JSDOM HTML parsing. Crucially, **network I/O wait time costs `0 ms` of CPU**. A Worker awaiting a `40`-second OpenAI stream uses `~2 ms` of CPU and never trips `exceededCpu`.
2. **`"outcome": "exceededMemory"` (`cpuTimeMs` is low, isolate evicted):** Your isolate's V8 heap plus external `ArrayBuffer` allocations crossed **`128 MB`**. Upgrading from Workers Free to Workers Paid (`$5.00/mo`) **does not raise the `128 MB` memory 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?

**Quick answer:** 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`:

```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 ms` to `6 ms` of CPU per request. At `10M` monthly requests (`40M` total 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,000` requests. With `"cpu_ms": 300000` (`5m`), `50,000` stuck invocations burn `15,000,000,000` (`15,000M`) CPU milliseconds before Cloudflare kills them, generating **`$299.40` in pure CPU overage** from a tiny `50K`-request probe.
- Clamping your public API Worker to `"limits": { "cpu_ms": 250 }` kills runaway loops `1,200x` faster, capping that exact same attack at `12.5M` CPU ms (`$0.00` overage inside your `30M` monthly allowance).

You can stress-test different p99 CPU millisecond profiles alongside request and D1/R2 volumes in the [Cloudflare Workers, D1 & R2 Cost Calculator](/calculators/cloudflare-workers-d1-r2-cost/).

## Why do response.json() and arrayBuffer() crash the 128 MB V8 isolate limit?

**Quick answer:** 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:

```ts
// 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:
1. **String + Object amplification:** Decoding UTF-8 bytes into V8 strings and materializing millions of small JS object keys routinely expands a `35 MB` JSON file into **`130 MB–170 MB`** of live heap before garbage collection can reclaim intermediate buffers.
2. **Isolate concurrency sharing:** A single warm Worker isolate handles multiple concurrent in-flight requests on the same edge machine. Three users uploading `25 MB` multipart files via `await request.formData()` at the same instant allocate `75 MB+` of buffers on top of your bundle's baseline heap.
3. **Module-scope memory retention & schema libraries:** Storing request data in global `Map` caches (or running older pre-`4.5.0` Zod builds with thousands of chained schemas) elevates idle heap to `40–60 MB`, leaving barely `65 MB` of headroom before `exceededMemory` strikes.

## How do TransformStream and HTMLRewriter fix memory and CPU spikes?

**Quick answer:** 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:

```ts
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:

```ts
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:

```ts
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](/guides/nextjs-static-export-cloudflare-workers-trailing-slash-404/), and handle responsive images at the edge using [Next.js Image Optimization Cloudflare Loader Fix](/guides/nextjs-image-optimization-bill-spike-cloudflare-loader-fix/).

## Why does Pure-JS bcrypt trigger error 1102 on Workers free and paid?

**Quick answer:** 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`:

```ts
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

**Quick answer:** 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.

1. **Check `outcome` first:** Filter Workers Logs by `outcome IN ("exceededCpu", "exceededMemory")` so you never tune CPU limits for a `128 MB` memory crash.
2. **Ban unbounded body buffering:** Grep your Worker codebase for `.arrayBuffer()`, `.text()`, `.json()`, and `.formData()` on user uploads or R2/fetch responses; stream bodies > `5 MB` via `TransformStream` or R2 presigned URLs.
3. **Bound D1 query result sizes:** Fetching `25,000` unpaginated rows from D1 into Worker memory spikes both V8 heap and D1 read bills, enforce `LIMIT` + cursor pagination as shown in our [Cloudflare D1 rows_read Spike & Covering Index Fix](/guides/cloudflare-d1-rows-read-spike-unindexed-query-fix/).
4. **Clear module-scope mutable state:** Remove global `let`/`Map` caches that accumulate across warm isolate reuses, and upgrade `zod` to `>= 4.5.0` if large validation schemas inflate baseline heap.
5. **Right-size `limits.cpu_ms` and forecast costs:** Set explicit `cpu_ms` ceilings in `wrangler.jsonc` (`250–1000` ms for APIs; higher only on dedicated batch Workers) and verify your monthly compute and storage budget in the [Cloudflare Workers, D1 & R2 Cost Calculator](/calculators/cloudflare-workers-d1-r2-cost/).
