# Observability and tracing

Read structured errors, durable audit records and Cloudflare spans as separate signals.

## Application errors and logs [#application-errors-and-logs]

The web middleware integrates evlog. Shared error codes and localized messages come from `packages/errors`; its server handler logs unexpected failures while the client resolver returns a safe user message. During development, inspect `.evlog/logs/` when available. Do not copy credentials, prompts or private payloads into logs.

Each RPC request has a request ID: `cf-ray` when Cloudflare set a well-formed one, otherwise a UUID. It is `context.requestId` on the server, the `x-request-id` header on every `/api/rpc` response (including the 500 when building the context fails), and a field of the error log. The MCP context derives its own `requestId` for the logs of its document tools; MCP responses do not carry the header. It serves only to correlate logs, never to decide anything: outside Cloudflare (local `wrangler dev`, Node) a client can send a well-formed `cf-ray` and it is used as is, and [Cloudflare's header reference](https://developers.cloudflare.com/fundamentals/reference/http-headers/) does not say whether a client-sent value is replaced. The error handler writes expected 4xx failures at debug level and unexpected ones (5xx, unknown codes, non-oRPC errors) as errors, both with the request ID, so a user's quoted header finds the matching line ([error handling](https://github.com/CarlosZiegler/template-cloudflare/blob/main/docs/error-handling.md)).

## Error reporting [#error-reporting]

Unexpected errors from the Worker, the browser and the Expo app can go to a Sentry-compatible tracker that groups them and sends alerts: [Rustrak](https://github.com/rustrak/rustrak) in Docker on your own server (`deploy/error-tracker/`, with GlitchTip as plan B; switching is a DSN). Everything is off until a DSN is set, and the alert rules live in the tracker, not in the app.

| Where   | Variable                                                | What reports                                                                                                                                                                                                                   |
| ------- | ------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| Worker  | `ERROR_REPORTING_DSN` (secret or var)                   | `withErrorReporting` wraps `fetch` and `scheduled` in `apps/web/src/server.ts` with `withSentry`; `/api/rpc` reports unexpected failures (5xx, unknown codes, thrown errors, never an expected 4xx) tagged with the request ID |
| Browser | `VITE_ERROR_REPORTING_DSN` (public, read at build time) | Uncaught errors, unhandled rejections, the route and component error boundaries; the next error after a failed API call carries that call's `x-request-id`                                                                     |
| Expo    | `EXPO_PUBLIC_ERROR_REPORTING_DSN`                       | JS errors and native crashes (`@sentry/react-native`, a native module: a new development build), and the route error boundary                                                                                                  |

`ERROR_REPORTING_ENVIRONMENT` (default `production`) and `ERROR_REPORTING_RELEASE` set the environment and release; without a release the Worker uses its version ID (the `CF_VERSION_METADATA` binding). The browser and the Worker may share one project's DSN, which lets one upload of source maps serve both. The Worker side runs only in workerd; the Node build reports from the browser and the tunnel.

All of it goes through `packages/error-reporting`. Sentry v11 collects cookies, headers, request bodies and query strings by default, so the package sets `dataCollection` to its restricted form and every event passes `scrub.ts` before it leaves: e-mail addresses, bearer and basic credentials, JWTs, `td_`/`mr_`/`sk_`/`pk_` tokens and CPFs become `[redacted]`, URLs lose their query and fragment, only a short list of headers stays, the user is reduced to `{ id }`, stack frames lose their local variables, and any key in the sensitive list (passwords, tokens, plus the project's own health keys in `PROJECT_SENSITIVE_KEYS`) is removed at any depth. Only errors are sent: no tracing, sessions, replays or screenshots. `pnpm lint` fails on an `@sentry/*` import or dependency anywhere else (`scripts/check-error-reporting-imports.mjs`; the one exception is `apps/mobile/metro.config.js`, which writes debug IDs at build time).

Nothing of it runs before the first paint ([W15](/docs/development/web-conventions)): with a browser DSN, `client.tsx` starts two listeners that keep up to 20 uncaught errors, and the SDK (33 KB gzip) is imported after hydration and takes them over. The Worker imports its SDK on the first request only when its DSN is set. Without DSNs the startup chunks grow by under 1 KB gzip and no Sentry code is evaluated; `assert-client-bundle-clean.mjs` fails a build whose startup chunks contain the SDK. Sizes and the end-to-end run against a local Rustrak: [the 2026-11-27 measurement](https://github.com/CarlosZiegler/template-cloudflare/blob/main/docs/measurements/2026-11-27-error-reporting.md).

The browser posts to `POST /api/errors/tunnel` on the site's own origin, so ad blockers do not drop reports and the tracker's address stays private. The tunnel forwards only envelopes for the browser's DSN (404 while it is unset), refuses bodies over 256 KB, and counts 30 envelopes a minute per signed-in User, or per client address otherwise, in the `rate_limit` table, so the limit holds across Cloudflare locations and on a Node host. If the database cannot be reached the envelope is forwarded anyway and the failure logged: errors matter most during an outage.

Production builds with `ERROR_REPORTING_AUTH_TOKEN` write hidden source maps; `node scripts/upload-sourcemaps.mjs` (a step of `deploy-prod.yml`) injects debug IDs, uploads them to `ERROR_REPORTING_URL` for the project named by the DSN, and deletes every map before deploy. Without the URL or the token it uploads nothing and passes. Expo builds upload their Hermes maps when `ERROR_REPORTING_URL` and `SENTRY_AUTH_TOKEN` are EAS environment variables; OTA updates use `npx @sentry/expo-upload-sourcemaps dist`. EAS Observe stays in the app for startup and navigation metrics.

`reportError` resolves to the tracker's event id (undefined while reporting is off), and the browser keeps the `x-request-id` of an API call that failed in the last minute; the error screen hands both to [Report a problem](/docs/features/feedback), and the Feedback inbox links the event in the tracker's dashboard (`ERROR_REPORTING_DASHBOARD_URL`).

Running the tracker (Cloudflare Tunnel, Access on the dashboard, PostgreSQL above about 1,000 events an hour): `deploy/error-tracker/README.md`.

An Audit Event is a durable domain record, not a log line. The Audit Log is the admin table; an Activity Timeline is one User's security history. Release notes belong to the public [changelog](/docs/changelog).

## Workers Logs and sampling [#workers-logs-and-sampling]

Workers Logs keeps what the Worker writes for seven days: one invocation event per request plus one event per `console` line (for example the evlog error handler's). `observability.logs.head_sampling_rate` in `apps/web/wrangler.jsonc` decides which share of requests is kept, and it is set explicitly to `1` (every request).

Sampling is decided per request before the Worker runs. An unsampled request keeps none of its lines, errors included: at `0.1`, nine of ten failures leave no trace, and a failure that happens once a day may never show up. Lower it only when the log bill matters more than that, and watch errors through the Worker's metrics (requests and errors per status in the dashboard), which this setting does not sample. Traces have their own rate (`observability.traces.head_sampling_rate`, default `1`); changing the logs rate does not change it.

What the logs cost on Workers Paid until 30 November 2026 (20 million events a month included, then US$ 0.60 per million), with one event per request and 15 ms of CPU per server render (an estimate from local workerd; every extra log line per request adds the logs column again). Prices read on 2026-11-05; the comparison is in [the 2026-11-06 measurement](https://github.com/CarlosZiegler/template-cloudflare/blob/main/docs/measurements/2026-11-06-web-quick-wins.md).

| SSR requests / month | Workers total (base + requests + CPU + logs) | Logs at rate 1 | Logs at rate 0.1 |
| -------------------: | -------------------------------------------: | -------------: | ---------------: |
|                 10 M |                                        US$ 7 |          US$ 0 |            US$ 0 |
|                 50 M |                                       US$ 49 |         US$ 18 |            US$ 0 |
|                100 M |                                      US$ 109 |         US$ 48 |            US$ 0 |
|                500 M |                                      US$ 589 |        US$ 288 |           US$ 18 |

From 1 December 2026 Workers Logs moves to [Cloudflare Observability pricing](https://developers.cloudflare.com/observability/pricing/): on Workers Paid, 50 GB of ingestion and 10 GB-month of storage per billing cycle are included, then US$ 0.25 per GB ingested and US$ 0.10 per GB-month stored. Sampling reduces both. Measure the bytes per event in the dashboard before choosing a rate under that model.

## Web Vitals [#web-vitals]

Real visits report their Core Web Vitals (LCP, INP, CLS, FCP, TTFB) when the visitor allows analytics in the cookie banner; without that consent nothing is observed or sent. `useWebVitals` (`apps/web/src/platform/analytics/web-vitals.ts`) starts after hydration, so it adds nothing before the first paint ([W15](/docs/development/web-conventions)), and sends one `navigator.sendBeacon` when the page is hidden or left. `POST /api/events/web-vitals` validates it with Zod (`web-vital-event.ts`), refuses bodies over 2 KB, asks the `WEB_VITALS_RATE_LIMITER` binding (30 requests a minute per client address and Cloudflare location; previews have no binding and do not limit) and writes one line to Workers Logs:

```json
{
  "event": "web_vital",
  "route": "/docs/$",
  "locale": "en",
  "navigationType": "navigate",
  "effectiveType": "4g",
  "LCP": 1180,
  "FCP": 640,
  "TTFB": 210,
  "CLS": 0.01,
  "INP": 72
}
```

`route` is the route pattern the document loaded on (`/{-$locale}/`, `/docs/$`, `/todos`), never the URL, so no id or query string is kept. Nothing identifies the visitor: no cookie, session, user, organization or address is logged (the address is the rate limiter's key and is not written anywhere). A metric that is not known yet when the page is hidden (INP without an interaction) is left out.

In the dashboard's Query Builder, filter `event = web_vital` and compute the 75th percentile of `LCP`, `INP` or `CLS` grouped by `route`; compare TTFB by `effectiveType` to see what the network adds. The endpoint is the first event of the planned analytics relay (`POST /api/events`): the relay takes `webVitalEvent` as its `web_vital` event and adds provider adapters beside the log line.

## Worker traces [#worker-traces]

Wrangler enables observability and traces. The scheduled handler passes `ctx.tracing` into `runScheduledJobs`; `workersTracer` adapts Effect spans to Cloudflare spans. It records scalar attributes, failures and interruption.

The native API cannot assign an explicit parent to each Effect span. Those spans appear as siblings under `jobs.scheduled`, alongside platform fetch and Hyperdrive spans. Node execution runs without this tracer. Local successful jobs do not prove that production custom spans are visible in the Cloudflare dashboard.

## Diagnose a failure [#diagnose-a-failure]

Trace the entry point, transport result and durable row together. For an import, inspect its state and persisted failure reason before assuming the queue lost it. For a webhook, inspect the delivery lease and next attempt. For a client error, keep the stable error code and correlation context rather than exposing an exception message.

Bundle and fault experiments are recorded in `docs/measurements`. Their local timings are not production latency or billing measurements. Add a dated report when changing runtime ownership, deadlines or a heavy dependency.

## Key files [#key-files]

- [`packages/api/src/platform/rpc/request-id.ts`](https://github.com/CarlosZiegler/template-cloudflare/blob/main/packages/api/src/platform/rpc/request-id.ts)
- [`packages/errors/src/server.ts`](https://github.com/CarlosZiegler/template-cloudflare/blob/main/packages/errors/src/server.ts)
- [`packages/error-reporting/src/scrub.ts`](https://github.com/CarlosZiegler/template-cloudflare/blob/main/packages/error-reporting/src/scrub.ts)
- [`deploy/error-tracker/compose.yml`](https://github.com/CarlosZiegler/template-cloudflare/blob/main/deploy/error-tracker/compose.yml)
- [`packages/api/src/platform/effect/tracer.ts`](https://github.com/CarlosZiegler/template-cloudflare/blob/main/packages/api/src/platform/effect/tracer.ts)
- [`packages/db/src/audit.ts`](https://github.com/CarlosZiegler/template-cloudflare/blob/main/packages/db/src/audit.ts)
- [`apps/web/wrangler.jsonc`](https://github.com/CarlosZiegler/template-cloudflare/blob/main/apps/web/wrangler.jsonc)
