skip to content

A production Cloudflare Worker API returns intermittent 500s; how do you find the failing invocations and their cause with Workers Logs and `wrangler tail`, without redeploying?

level: seniorimportance: must knowfreq 40%

answer

  1. outcome is not the HTTP status
  2. two kinds of 500
  3. filter, then read the fields
  4. sampling may have dropped it

basics

~20 s

Query Workers Logs for $workers.outcome = "exception" and for a 5xx $workers.event.response.status, because a handled 500 finishes with outcome ok. Read the exception and structured console.error fields, then confirm live with wrangler tail --status error or --search.

solid answer

~50 s

First separate the two kinds of 500. An uncaught exception ends the invocation with outcome `exception` and the client gets Cloudflare's error 1101 page; code that catches an error and returns a 500 ends with outcome `ok`. In Workers Logs, filter `$workers.outcome = "exception"` (or `$metadata.error EXISTS`) for the first kind, and filter `$workers.event.response.status` of 500 or more, grouped by `$workers.event.request.path`, for the second. Read the exception, its stack trace and the fields your `console.error` objects logged. Other outcomes redirect the hunt: `exceededCpu` and `exceededMemory` are resource limits, `canceled` is a client that disconnected. Then watch live with `wrangler tail --status error`, or `--search` on your error event's name. Two gaps need a deploy to close, so close them before the next incident: a low `head_sampling_rate` may have dropped the failing invocations, and without uploaded source maps the stacks point into the bundle.

code

javascript · 21 lines
javascript
export default {
  async fetch(request) {
    const url = new URL(request.url);
    try {
      return await loadOrder(url.searchParams.get("id"));
    } catch (err) {
      console.error({
        event: "order_lookup_failed",
        route: url.pathname,
        orderId: url.searchParams.get("id"),
        error: err.message,
      });
      return Response.json({ error: "internal" }, { status: 500 });
    }
  },
};

async function loadOrder(id) {
  if (!id) throw new Error("missing order id");
  return Response.json({ id });
}

go deeper

for a junior

Recall that Workers Logs can be filtered by outcome and response status, and that wrangler tail shows failing invocations live with their exceptions and console output.

for a middle

Explain why outcome and HTTP status differ, what each outcome value means, and which Workers Logs fields find each kind of 500.

for a senior

Run the diagnosis end to end: split handled from uncaught failures, read stacks and structured fields, rule out client cancellations and limits, and spot sampling gaps.

for a principal

Turn the incident into defaults: sampling rates high enough to catch rare failures, source maps and structured error events everywhere, and an alert on 5xx as well as exceptions.

## Separate the two kinds of 500 A Cloudflare Worker can produce a 500 in two different ways, and the logs record them differently: - **An uncaught exception.** The handler throws and nothing catches it. The invocation's **outcome**, Cloudflare's exit status for that run, is `exception`, and a browser receives Cloudflare's error page with code **1101**, "Worker threw a JavaScript exception". - **A handled error.** The code catches the failure and returns `new Response(..., { status: 500 })`. The invocation finished normally, so its outcome is `ok`, though the client still sees a 500. Keeping these apart is most of the diagnosis. A filter on outcome finds only the first kind; a filter on response status is how you find the second. ## Query Workers Logs Workers Logs stores invocation logs, `console` output and exceptions for every sampled invocation, for 3 days on Workers Free and 7 on Workers Paid. In the dashboard's Observability view or its Query Builder: 1. Filter `$workers.outcome = "exception"` to list the uncaught exceptions. `$metadata.error EXISTS` is a wider net for any log with an error attached. 2. Filter `$workers.event.response.status` for 500 or more and group by `$workers.event.request.path` to see which routes return errors and how often. 3. Open a failing invocation and read it whole: the request, the exception name, message and stack trace, and every `console` line it wrote. 4. Group the failures by the fields your structured logs carry, such as `orderId` or an upstream name, to find what the failing requests share. 5. Compare `$workers.cpuTimeMs` across failing and healthy invocations when the failures look load-related. ## Read the outcome | Outcome | What it means | Where to look next | |---|---|---| | `exception` | Uncaught JavaScript exception, or a handler that returned no Response | The stack trace and the code path it names | | `exceededCpu` | The invocation ran out of CPU time | The isolate's CPU limit and the work done per request | | `exceededMemory` | The invocation ran out of memory | Large bodies or payloads read into memory | | `canceled` | Cut short, commonly because the client disconnected | Client timeouts and slow upstream calls | | `ok` with status 500 | Your code chose to return a 500 | The `console.error` your error path wrote | Outcome and status disagree in a second way too: a Worker can return a 200 and then have work registered with `ctx.waitUntil()` exceed a limit, so its outcome shows a failure the client never saw. ## Confirm live with `wrangler tail` Workers Logs shows what was stored; `wrangler tail` shows what happens now, with no deploy: - `wrangler tail orders-api --status error` streams only the `exception`, `exceededCpu`, `exceededMemory` and `unknown` outcomes. - `--search order_lookup_failed` catches the handled 500s, if the error path logs that name. - `--version-id` narrows to one version, which tells you whether the failures began with a particular upload. - Uncaught-exception stack traces in the stream are remapped to your sources if source maps were uploaded with that version. ## Rule out the platform and the network A few signals point away from your own code: - An `11xx` error other than the documented ones generally indicates a problem with the Workers runtime itself; check Cloudflare's status page before digging further. - A runtime error `Network connection lost` is a connection failure on a `fetch` or binding call. It does not produce an error page; it shows up in logs, and the documented remedy is to catch the call and retry it. - `Memory limit would be exceeded before EOF` means the code tried to read a stream or buffer larger than the memory limit, usually a body read whole instead of streamed. ## What only a deploy can change Some gaps cannot be closed mid-incident, which is the argument for setting them up in advance: - **Sampling.** With `head_sampling_rate: 0.01`, about 99 in 100 invocations store nothing, failures included, because the decision is made before the outcome is known. Raising it is a Wrangler file change and a deploy. - **Readable stacks.** `upload_source_maps` takes effect for versions uploaded with it; traces from earlier versions stay in bundle coordinates. - **Context.** A handled error that logs nothing, or logs a concatenated string, leaves little to query. Structured `console.error` objects with a stable `event` name make step 4 possible. - **Alerting.** A Tail Worker that checks both outcome and response status turns the next spike into an alert instead of a report from users.

  • Why might the failing requests be missing from Workers Logs entirely?
    Head sampling: at `head_sampling_rate: 0.01`, about 99% of invocations store nothing, and the choice is made before anyone knows the request will fail. An account over 5 billion logs in a day is also cut to a 1% sample, and logs older than the plan's retention are gone. Watch live with `wrangler tail` meanwhile, and raise the rate in the next deploy.
  • What does a cluster of `canceled` outcomes during the 500 spike tell you?
    Those invocations were cut short, commonly because the client disconnected before the response was sent. That points away from an exception in your code and toward slow responses that make clients give up, such as a slow upstream `fetch`. Compare wall time with CPU time, and use traces to see which subrequest is slow.
  • How do you tell whether the 500s started with a particular Worker version?
    Run `wrangler tail --version-id <id>` against the newest version and against the previous one and compare the failures, or compare failure counts before and after the deploy time in Workers Logs. If one version owns the failures, rolling back to the previous version is the fastest mitigation.

  • Every 500 from a Worker shows up in the logs with outcome exception.
  • A canceled outcome means the Worker's code crashed with an error.
  • Uploading source maps now will remap the stack traces already stored from last week.
  • wrangler tail can replay the failures that happened earlier today.
  • At a 1% head sampling rate Workers Logs still keeps every failed request.