Request Logs Need Structure and Correlation
A log line records that something happened, not why. Waypoint's shipment API returns a success status while support hears "the page is blank", and the record tracking lookup AB12 ok 200 names no tenant, release, cache key, or upstream call. A log event is one record from the runtime, an invocation is one Worker execution, and structured logging emits named fields the platform can index separately. Workers Logs indexes JSON fields for filtering and grouping; a value buried in a message needs a text match (Workers Logs).
Three identities matter, and none substitutes for another. The Ray ID in cf-ray identifies one request at Cloudflare's edge. The trace ID is the 32-character hexadecimal identity shared by every span in one invocation. Your request ID is one you control: it survives a retry and travels to an upstream service. Figure 1 shows where each is created and where redaction must happen.
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','titleColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','activationBorderColor':'#132440','signalColor':'#5a6e82','signalTextColor':'#132440','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
C["Client request"] --> E["Cloudflare edge: assigns Ray ID"]
E --> W["Worker invocation: assigns trace ID"]
W --> R{"Client sent x-request-id?"}
R -->|"valid format"| K["Adopt the client request ID"]
R -->|"missing or malformed"| G["Generate a request ID"]
K --> H["Handler: route, tenant, release"]
G --> H
H --> B["Bindings: KV, D1, R2, Durable Object"]
H --> U["Upstream fetch with x-request-id"]
B --> L["Build one JSON event"]
U -->|"timeout or 5xx"| X["Record outcome and upstream status"]
U -->|"success"| L
X --> L
L --> D["Allowlist fields and redact values"]
D --> S["Workers Logs: indexed, 7-day retention"]
S --> Q["Query by request_id, trace_id, or Ray ID"]
H --> P["Response with x-request-id and x-trace-id"]
classDef primary fill:#132440,color:#ffffff,stroke:#0b172b;
classDef secondary fill:#16476A,color:#ffffff,stroke:#0f314a;
classDef ok fill:#3B9797,color:#ffffff,stroke:#2a6f6f;
classDef danger fill:#BF092F,color:#ffffff,stroke:#7a0420;
classDef warn fill:#c4873b,color:#132440,stroke:#8a5a1f;
class E primary;
class C,W,R,K,G,H,B,U,L,X,S,Q secondary;
class D,P ok;
Treat the request ID as untrusted input and the event as an allowlist. Validate the header shape, generate a UUID when it fails, and never treat the value as identity. Record one flat event per request; the shape below is illustrative.
Redaction runs before the event leaves the Worker. Use an allowlist and drop authorization headers, cookies, query strings, request bodies, emails, and raw IPs. Figure 2 places those decisions on the trust, execution, and storage boundaries.
Log volume is a cost decision
The cost starts before your first custom log. Each request already writes an automatic invocation log, so one custom event doubles volume. At a billion requests per month and a 10% sample, Cloudflare's own example is about $108 per month under the pricing published before December 2026 (Workers Logs pricing).
Log one event per request and one per exceptional branch, not one per loop iteration, per retry, or per body. A log is capped at 256 KB and truncated beyond that, with $cloudflare.truncated set to true.
Traces Show Where a Request Spends Time
A log says the request took 2,412 ms; it cannot say where. Suppose the trace shows 6 ms in the handler, 11 ms in a KV miss, 38 ms in D1, 2,280 ms in the carrier fetch, and 9 ms parsing. The Worker is not slow; it is waiting. Without spans, the likely response is more CPU or a handler rewrite, neither of which touches the 2.3 seconds. The numbers are illustrative, not a measurement.
A span is one timed operation; a trace is the tree of spans from one invocation. A span carries a name, start, duration, attributes, and a parent. Tracing instruments fetch calls, bindings, RPC, and handlers automatically, and a log written inside a span is attributed to that span (Traces). The code widget at the end of this section adds custom span attributes, exceptions, and status.
Tracing is still in open beta
Tracing retains traces for seven days, defaults head sampling to 1, and samples independently of logs. Trace context travels across service bindings and Durable Objects inside Cloudflare, but not to services outside it, so a vendor's trace will not join yours; forward x-request-id instead.
Non-I/O spans may report 0 ms because the runtime does not advance time without I/O. Span status is exported to OpenTelemetry but not shown in the dashboard, and the span context's trace flags do not indicate whether the request was sampled, so do not build a traceparent header from them.
Tail Workers are a separate tool. They receive events after each producer invocation, require Workers Paid or Enterprise, and bill by CPU time (Tail Workers).
| Signal | Question it answers | Data shape | Retention | Sampling control | Cost driver |
|---|---|---|---|---|---|
| Workers Logs | What happened in this invocation? | JSON event per log call, plus an invocation log | 7 days on Paid, 3 on Free | head_sampling_rate, 0 to 1 | Events written; 20 million per month included on Paid, then $0.60 per million |
| Workers Traces | Where did this request spend time? | Span tree with attributes and exceptions | 7 days | observability.traces.head_sampling_rate, independent of logs | Spans ingested and stored; open beta |
| Tail Workers | What should run when an invocation ends? | Per-invocation event stream to your Worker | None by default; you choose the sink | Filtering and sampling in tail(); no head-sampling setting | CPU time; Paid or Enterprise only |
| Analytics Engine | How is the service behaving over time? | Indexed time series: blobs, doubles, one index | 3 months | Index-based downsampling; weight with _sample_interval | Data points written and read queries |
| OpenTelemetry export | How do I feed my existing tool? | Batched OTLP logs and traces | Destination-defined | Same per-signal sampling; persist: false skips Cloudflare storage | Destination ingestion, plus storage if persisted |
Figure 3 follows that request through cache, database, upstream, and timeout.
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','activationBorderColor':'#132440','signalColor':'#5a6e82','signalTextColor':'#132440','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
sequenceDiagram
autonumber
participant C as Client
participant W as Worker
participant K as KV
participant D as D1
participant U as Carrier API
participant O as Observability
C->>W: GET /v1/shipments/AB12 with x-request-id
W->>W: start root span and request event
W->>K: kv_get shipment:AB12
alt cache hit
K-->>W: cached shipment in 11 ms
else cache miss
K-->>W: null
W->>D: d1_first shipment row
D-->>W: row in 38 ms
end
W->>U: fetch carrier with x-request-id
alt carrier responds
U-->>W: 200 and event list in 2280 ms
else carrier timeout
U--xW: 504 after 2280 ms
W->>W: recordException and setStatus error
W-->>C: 504 with x-request-id and x-trace-id
end
W->>O: span tree and one JSON event
Note over O: traces and logs are sampled independently
Workers Logs moves to Observability pricing on 2026-12-01, when traces share the same allowance; the table reflects the earlier terms.
Errors, CPU, Wall Time, and Service Objectives
Invocation status is not HTTP status. Cloudflare reports both, and a Worker can return a success response while an upstream sent an empty payload (Metrics and analytics). The invocation status separates a client disconnect from a thrown exception or an exceeded resource limit.
| Invocation status | What happened | Supporting signal |
|---|---|---|
success | The handler completed and returned a response | May still carry an empty or stale payload |
clientDisconnected | The client went away before the response | No error code; compare with wall time |
scriptThrewException | An uncaught exception ended the invocation | Error 1101 |
exceededResources | A runtime limit was exceeded, such as CPU | Error 1102, shown as Exceeded CPU Time Limits and recorded as exceededCpu |
internalError | A platform-side failure ended the invocation | Check the Cloudflare status page |
CPU time is active processing; wall time is the context's lifetime. Wall time includes I/O and waitUntil() work. A Worker waiting 2.3 seconds on a carrier has low CPU and high wall time; fix the dependency. A Worker parsing a large CSV has high CPU and modest wall time; stream, chunk, or move the work to a Queue consumer. High quantiles can exceed the CPU limit without errors because the runtime allows some rollover for requests under the limit.
An SLI is good events divided by valid events; an SLO is a target over a window; the error budget is the remainder. A burn rate of 1 spends the budget exactly at the window's end, and 14.4 spends it in roughly 1/14 of the window (Google SRE Workbook).
| Target over 30 days | Error budget | If spent evenly per day |
|---|---|---|
| 99.9% | 43 minutes 12 seconds | 1 minute 26 seconds |
| 99.95% | 21 minutes 36 seconds | 43 seconds |
| 99% | 7 hours 12 minutes | 14 minutes 24 seconds |
Alert on two windows, not one. The classic scheme pages at 14.4x over one hour and 6x over six hours, so a spike does not page but a sustained leak does.
Define the SLI at the user action, not the platform. "The request returned a known shipment status within 800 ms" is user-level. "The Worker did not throw" misses empty payloads, stale cache, and contract changes. Status codes and invocation outcomes are supporting evidence.
Monitors fire only when both windows breach. Cloudflare Monitors support SLO detection with a bad-events query, a total-events query, short and long windows, a target, and an optional minimum event count. The short window reacts and recovers quickly, the long window absorbs blips, the minimum count suppresses low-traffic noise, and the repeat interval prevents a message every minute (Monitors). This addresses noisy alerts, but exposes no separate burn-rate multipliers; window length and target are the knobs.
A 200 is not a success
If the success signal is the HTTP status, an empty or stale payload consumes no error budget while users experience the failure. Define the SLI on the user-visible outcome, then use status codes and invocation outcomes as supporting evidence.
A composite, illustrative incident shows why. A release moves a KV key from the v1 prefix to a v2 suffix but leaves one read path on the old prefix. New shipments return a success status with {"status":"unknown"} in the body. The 5xx rate is flat, invocation status is success, and latency improves because the Worker skips D1 and the carrier; only the application-level success ratio moves.
Grouping logs by release and cache prefix isolates the cohort. The trace shows a 3 ms KV miss and an early return, and the request ID on the response ties a complaint to the event. The fix is a rollback, but detection came from the SLO, not the error graph.
Analytics Engine and Application-Level Measurements
A receipt settles one charge; a statement shows the trend. Workers Logs keeps individual events for seven days and charges per event; Analytics Engine keeps high-cardinality time series for three months, writes without blocking the request, and answers aggregate SQL (Analytics Engine). A 30-day SLO needs the statement, not a pile of receipts.
A data point carries blobs, doubles, and exactly one index. Blobs are string dimensions, doubles are numbers, and the index is the sampling key. The documented limits are twenty blobs, twenty doubles, 16 KB of blobs per point, 96 bytes per index, and 250 points per invocation (limits). More than one index means the point is not recorded: a silent failure in an otherwise correct write.
Pick the sampling index
Analytics Engine downsamples by index at high volume. A tenant key lets a noisy tenant be sampled without destroying everyone else's resolution; a per-request key gives every request its own bucket and defeats useful downsampling. Keep the request ID in a blob for debugging, and put route, outcome, method, and release in blobs alongside duration, upstream duration, and a 1/0 success flag in doubles.
Sampling changes the arithmetic. A dashboard that ignores it looks stable and is wrong by the sampling factor (SQL sampling).
| Naive query | Weighted replacement |
|---|---|
COUNT() | SUM(_sample_interval) |
AVG(double) | SUM(_sample_interval * double) / SUM(_sample_interval) |
quantile(0.95)(double) | quantileExactWeighted(0.95)(double, _sample_interval) |
Never gate the point on trace sampling
Logs and traces are head-sampled per signal, Analytics Engine applies its own index-based downsampling, and writing a data point is not gated by the log sampling rate. Wrapping the write in a trace check biases the SLO toward requests the tracing sampler chose, and the trace flag does not even reflect head sampling.
Write the point unconditionally and let Analytics Engine own its sampling. Figure 4 shows the two lanes and the biased path.
Retention sets the question you can answer
Seven days debugs a deploy, three months covers a monthly SLO and a quarterly review, and year-over-year needs an export to R2 or a warehouse. Analytics Engine is priced per point written and per read query, with 10 million points and 1 million queries included monthly on Workers Paid (pricing).
As of the April 2026 documentation, usage was not yet billed. Treat that as dated.
Volume limits are blunt. One invocation can write 250 points, so a batch consumer logging 1,000 messages loses 750 silently; aggregate inside the batch or write counts in doubles. Logs have a 5-billion-per-account-per-day cap, after which an automatic 1% head sample applies for the rest of the day (Workers Logs limits). That is a safety valve, not a capacity plan.
Design a Dashboard for a Worker-Backed API
Start from one Worker, three bindings, and sampling you can change. The commands scaffold and deploy the project; the config shows the bindings and sampling rates the exercise assumes.
Design a Dashboard for a Worker-Backed API
Status: design-only. These steps were not executed for this article, and no latency, error-rate, log-volume, or cost measurements are reported.
Prerequisites. A Cloudflare account, Node.js, and current Wrangler. Workers Logs works on Free and Paid; tracing is open beta, so confirm the Traces panel appears. Tail Workers need Paid or Enterprise and are optional. Analytics Engine has Free and Paid allowances. Monitors deliver to email, webhooks, or PagerDuty; webhooks work on all plans and PagerDuty needs a Business or higher zone (Monitors).
Minimal setup. Copy the bindings and sampling block from the widget above, deploy, then send one valid, one missing, and one malformed request with test data.
Steps.
- Emit one JSON event per request with the fields shown in the event widget.
- Filter on
$cloudflare.$metadata.type = "cf-worker-event"for invocation logs, then on your custom event field. Confirm each field appears as its own column. - Search one request ID. Confirm the invocation log, custom event, and response header agree.
- Open the trace. Confirm the root, KV, D1 on a miss, and upstream spans, and compare the event's duration with the child spans.
- Query a five-minute success ratio in one-minute buckets with the weighted expression from the sampling table. Compare it with the log-derived count within sampling error.
- Build five panels: volume, success ratio, p95 duration, upstream share of duration, and upstream errors.
- Define availability at 99.9% over 30 days and latency at 95% under 800 ms, then create an SLO monitor over
events.analyticsEngine.waypoint_requestswith bad and total queries, a five-minute short window, a one-hour long window, a 99.9 target, and a minimum of 50 events. - Inject the controlled 504 for one tenant. Watch the short window breach, then the long one, and confirm the alert fires only after both.
Expected observations.
- Every event field is filterable as its own column.
- The trace shows upstream fetches dominating duration while CPU stays low.
- The Analytics Engine success ratio falls before the Workers error graph moves.
- The monitor ignores one slow request and stays quiet below 50 events.
Failure checks.
- No logs. Check that observability is enabled for the Worker and that you are not viewing Preview telemetry.
- No traces. Check that tracing is enabled and that the 0.1 sample has not excluded the request.
- Missing Analytics Engine point. Check for exactly one index and fewer than 250 points.
- Monitor never fires. Ensure the bad query is a subset of the total and both return a numeric value.
- No rows. Check dataset, account filter, and time range before changing the target.
Cost dimensions. Log events, spans ingested and stored, Analytics Engine points and queries, monitor evaluations, and destination charges. Sampling before storage reduces ingestion and storage. Workers Logs moves to Observability pricing on 2026-12-01; Analytics Engine billing was not active in the April 2026 documentation.
Cleanup. Delete the monitor, Worker, KV namespace, and D1 database; remove local .wrangler state. Analytics Engine data ages out after three months; stop the load generator.
Inject One Controlled Failure and Follow Its Evidence
One controlled flag should produce four pieces of evidence. The failure is a flag that makes the carrier path return 504 for one tenant while others stay healthy. The evidence chain is a log event with a request ID, a trace with a failed upstream span, an Analytics Engine point with outcome = "upstream_error", and a monitor that fires only after both windows breach. A missing link makes the dashboard decorative.
A quieter failure returns a success status with an unknown body. The 5xx graph and invocation status stay flat, and only the application-level flag moves. A status-code SLO cannot see it, which is why the flag belongs in the Analytics Engine point.
Pass/fail evidence.
- PASS, documented: Workers Logs indexes JSON fields, retains seven days on Paid and three on Free, caps a log at 256 KB, and applies a 1% head sample after 5 billion logs per account per day (https://developers.cloudflare.com/workers/observability/logs/workers-logs/).
- PASS, documented: tracing instruments fetch, bindings, RPC, and handlers automatically; retains seven days; samples independently of logs; remains in open beta (https://developers.cloudflare.com/workers/observability/traces/).
- PASS, documented: trace context is not propagated outside Cloudflare, non-I/O spans may report 0 ms, and span status is not shown in the dashboard (https://developers.cloudflare.com/workers/observability/traces/known-limitations/, https://developers.cloudflare.com/workers/observability/traces/custom-spans/).
- PASS, documented: Tail Workers receive per-invocation events after the producer finishes, require Workers Paid or Enterprise, and bill by CPU time (https://developers.cloudflare.com/workers/observability/logs/tail-workers/).
- PASS, documented: Analytics Engine accepts one index per point, caps blobs at 16 KB and points at 250 per invocation, retains three months, and exposes
_sample_interval(https://developers.cloudflare.com/analytics/analytics-engine/limits/, https://developers.cloudflare.com/analytics/analytics-engine/sql-api/). - PASS, documented: an SLO monitor evaluates bad and total queries over short and long windows, fires only when both are below target, and supports a minimum count and repeat interval (https://developers.cloudflare.com/notifications/monitors/).
- PASS, documented: invocation statuses distinguish success, client disconnect, script exception, exceeded resources, and internal error; error 1102 is the CPU-limit response (https://developers.cloudflare.com/workers/observability/metrics-and-analytics/).
- NOT RUN: the dashboard exercise, the controlled 504, the silent 200, alert timing, and every cost figure. No Wrangler, runtime, or tracing version was tested, and no hosted lab was executed.
Self-check.
- Why log both IDs? The request ID follows the business operation across retries and into an upstream service; the trace ID finds the span tree inside one invocation, and a retry can reuse the request ID while producing a new trace.
- Why is a success response with an empty body invisible to an error-rate SLO? The SLI uses the signal you define; an HTTP success is not success unless the body is checked.
- Why weight by the sample interval? A busy index retains only a fraction of points, and the interval restates how many original events each retained point represents.
- Why wait for both windows? The short one catches a fast burn; the long one prevents a brief spike from paging.
Unresolved limitations. Tracing is an open beta, and span names, attributes, and availability may change. Trace context does not cross Cloudflare's boundary automatically, so a vendor's trace will not join yours without a supported path; the request ID is the reliable bridge. Non-I/O spans can read 0 ms, making a CPU-only optimization look pointless. Workers Logs pricing changes on 2026-12-01, and Analytics Engine billing was not active in the April 2026 documentation, so cost figures are dated. Monitors evaluate SQL API datasets, while Workers Logs is queried through the Observability API; I found no documented direct log-row monitor, so the SLO path here is Analytics Engine. Re-check that boundary before standardizing a dashboard.
Verification. Documentation checked on 2026-11-05 against the Cloudflare Workers observability, traces, Tail Workers, Analytics Engine, and Monitors pages; the planning baseline was 2026-11-02. No hosted lab was run, and no product version was tested.
References. - Workers observability overview: https://developers.cloudflare.com/workers/observability/ - Workers Logs, including structured logging, sampling, limits, and pricing: https://developers.cloudflare.com/workers/observability/logs/workers-logs/ - Workers traces, including automatic instrumentation and sampling: https://developers.cloudflare.com/workers/observability/traces/ - Trace spans and attributes: https://developers.cloudflare.com/workers/observability/traces/spans-and-attributes/ - Custom spans and spanContext(): https://developers.cloudflare.com/workers/observability/traces/custom-spans/ - Tracing known limitations: https://developers.cloudflare.com/workers/observability/traces/known-limitations/ - Automatic tracing across Durable Object and Worker subrequests: https://developers.cloudflare.com/changelog/post/2026-05-07-automatic-tracing-across-do-and-worker-subrequests/ - Tail Workers: https://developers.cloudflare.com/workers/observability/logs/tail-workers/ - Workers metrics, invocation statuses, CPU time, and wall time: https://developers.cloudflare.com/workers/observability/metrics-and-analytics/ - Workers Observability Query Builder: https://developers.cloudflare.com/workers/observability/query-builder/ - Workers Analytics Engine: https://developers.cloudflare.com/analytics/analytics-engine/ - Analytics Engine limits and retention: https://developers.cloudflare.com/analytics/analytics-engine/limits/ - Analytics Engine SQL API and sampling: https://developers.cloudflare.com/analytics/analytics-engine/sql-api/ - Analytics Engine pricing: https://developers.cloudflare.com/analytics/analytics-engine/pricing/ - Cloudflare Monitors, including SLO detection: https://developers.cloudflare.com/notifications/monitors/ - Cloudflare Observability pricing: https://developers.cloudflare.com/observability/pricing/ - Google SRE Workbook, alerting on SLOs: https://sre.google/workbook/alerting-on-slos/ - Choosing a data or storage product: https://developers.cloudflare.com/workers/platform/storage-options/
Next in the Series
In Troubleshoot From DNS to Origin to Worker, we'll explore Use a layered runbook rather than random configuration changes.