# 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 Worker entry derives it once and every handler receives it ([backend conventions](/docs/development/backend-conventions#the-entry-forwards-the-request-facts)); the MCP context carries the same ID for the logs of its document tools, and 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/fofo/blob/main/docs/error-handling.md)).

## Error reporting [#error-reporting]

Both error-envelope routes mount the same API handler. The ingest module owns the Worker settings, the wire size cap, the fail-closed sender budget and the tracker forward. Web and Expo share the tunnel path through a client-safe leaf.

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`. Through the tunnel                                                                               |
| Expo    | `EXPO_PUBLIC_ERROR_REPORTING_DSN`                       | JS errors, unhandled rejections, the route error boundary, native crashes, app hangs and ANRs (`@sentry/react-native`, a native module: a new development build). Through the relay; a DSN on the tracker goes through the tunnel and reports JS errors only |

`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, the tunnel and the relay.

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/fofo/blob/main/docs/measurements/2026-11-27-error-reporting.md).

Clients never post to the tracker. The browser (and the Expo app, when its DSN names the tracker) sends its envelopes to `POST /api/errors/tunnel` on the Worker (`${EXPO_PUBLIC_SERVER_URL}/api/errors/tunnel` for the app), so ad blockers do not drop reports and a tracker can require a secret only the Worker holds. The tracker's host is no secret: it is in every DSN. The tunnel forwards an envelope only when the DSN in its header names the host and project of a DSN in `ERROR_REPORTING_TUNNEL_DSNS` (comma-separated, the browser's and the app's) or of `VITE_ERROR_REPORTING_DSN`, which is always allowed; anything else is 403, and with neither set the tunnel answers 404. It forwards to that allowed DSN's `/api/<id>/envelope/` with its public key as `?sentry_key=` (Rustrak does not read the key from the envelope), never follows a redirect (a 3xx becomes 502), 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. The app posts without a session, so its senders count per address like signed-out browsers. A foreign or malformed envelope is refused before it is counted. If the database budget check cannot be reached, the endpoint logs the failure and answers 503 with `Retry-After: 60` instead of forwarding without a verified budget. If any error-reporting setting does not parse, the tunnel is off (404) along with the Worker's reporting, and one warning names the settings.

**Native crash reports: the relay.** The native SDKs inside `@sentry/react-native` 8.28.1 (sentry-cocoa 9.29.3, sentry-android 8.57.0, whose NDK crashes go out through the same Java transport) ignore `tunnel`: they post gzipped envelopes to `<DSN host>/api/<project id>/envelope/` with the public key in `X-Sentry-Auth`, and use no other ingest path. So the app's DSN names your server instead of the tracker: `EXPO_PUBLIC_ERROR_REPORTING_DSN` is the tracker's DSN for the app project with the host of `EXPO_PUBLIC_SERVER_URL` (`https://<key>@app.example.com/3` for `https://<key>@errors-ingest.example.com/3`), and the Worker's `ERROR_REPORTING_RELAY_DSNS` lists the real one (comma-separated, one DSN per project id; two for one id turn reporting off). When the DSN's scheme and host are the server's, the app starts the SDK with the native SDKs on and no tunnel, so JS errors (handed to the native transport), native crashes, app hangs and ANRs all reach `POST /api/<project id>/envelope/` on the Worker (`apps/web/src/routes/api/$projectId/envelope.ts`, with or without the trailing slash). Before counting anything the relay answers 404 to a project id not in the list (and to every id while unset) and refuses empty or >256 KB wire bodies. It then counts the request in the tunnel's bucket (30 a minute per sender for both routes) before decoding or scrubbing: 415 to unsupported `Content-Encoding`, 413 past 1,000,000 bytes unpacked or forwarded (gzip and deflate are unpacked; already-decoded bodies are read as is), 400 to malformed envelopes, and 403 unless the request carries that DSN's public key (`X-Sentry-Auth`, `?sentry_key=` or an envelope header DSN naming this project). Every event then runs through `scrubEvent` with a 16 KB per-string cap (native events never ran `beforeSend`: HTTP breadcrumbs carry `http.query`, messages can be objects; an unreadable event is 400) and forwards unpacked to the real DSN like the tunnel: the ingest header only for the Worker's own tracker, no redirect followed, 10 s. Project ids are digits and every other `/api/*` route starts with a fixed segment, so the route shadows none of them; it behaves the same on Workers and on the Node build. A DSN on the tracker keeps the old behaviour: the tunnel, `enableNative: false`, no native crashes. Native stack frames are symbolicated only with the build's debug files on the tracker (dSYM, ProGuard; Rustrak takes no Android NDK symbols).

**A locked-down tracker.** A DSN is public, so an open ingest host takes events from anyone who has one. `deploy/error-tracker` ships a vhost (`Caddyfile`, compose profile `locked`) that passes only `POST /api/<id>/envelope/` with the header `X-Rustrak-Ingest-Key` and sentry-cli's `/api/0/` uploads with their bearer token, answers 403 to an envelope without the key and 404 to everything else. Set the same key (at least 32 characters) as the Worker secret `ERROR_REPORTING_INGEST_KEY` (header name `ERROR_REPORTING_INGEST_HEADER`, default `X-Rustrak-Ingest-Key`). It goes only to the host of `ERROR_REPORTING_DSN`, which it therefore requires, over HTTPS (plain http only to a loopback host): the Worker's SDK sends it on its own events (`transportOptions.headers`, redirects not followed) and the tunnel and the relay add it to forwards to that host, never to an allowed DSN on another tracker. No client bundle or response carries it. Without a key nothing changes: the Worker, the tunnel and the relay post to an open tracker without the header.

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 (the locked-down ingest host, the dashboard on a tailnet or behind Cloudflare Access, 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).

## When an error happens, with or without a DSN [#when-an-error-happens-with-or-without-a-dsn]

An error never blanks the web app or closes the native app, and none of this depends on a DSN. Without one, every handler below still runs and passes the error to `reportError`, which keeps nothing and sends nothing.

**Web.** `client.tsx` calls `installGlobalErrorHandlers` before hydration (`platform/errors/global-handlers.ts`). With a DSN the early queue keeps uncaught errors and unhandled rejections until the SDK takes over; without one, two `error` and `unhandledrejection` listeners report them. `hydrateRoot` gets `onUncaughtError`, `onCaughtError` and `onRecoverableError`, each reported with a `boundary` tag (`react-uncaught`, `react-caught`, `react-recoverable`). One error can reach React's callback and an error screen; `reportErrorOnce` reports it once and gives both the same event id. Every route has `FeedbackRouteError` as its error component, so an error shows inside the layout that failed. Retry resets the query errors a `useSuspenseQuery` threw to the boundary, then re-runs the loaders, and "Report a problem" is offered only for a server or unexpected error (`errorKind` in `@fofo/errors/error-kind`), never for not signed in, no access, not found or offline. An unknown URL renders the translated `NotFound`. Widgets that can fail on their own (the analytics chart, an assistant conversation) sit in `platform/errors/error-boundary.tsx`, so the rest of the page stays.

**Stale deploys.** After a deploy, a tab on the old build asks for lazy chunks that are gone. A failed dynamic import, a failed CSS preload (`vite:preloadError`) or iOS Safari's invalid-MIME `TypeError` reloads the page once (`platform/errors/chunk-reload.ts`, from the router's `defaultOnCatch`, the route error screen, React's uncaught callback and the two listeners). The error is kept in `sessionStorage` and reported by the next page, because a report sent in the same turn as `location.reload()` dies with the page. A tab reloads at most once in 10 minutes for this, so a chunk that is really missing shows the error screen, which reports it at once, instead of a reload loop. Once a page has started its reload, every other handler that sees the same error leaves it alone, so it is reported once, after the reload. When the error was queued but the reload marker could not be written (storage full), the queued entry is rolled back and the page does not reload, so the error screen's report is the only one. The handlers themselves never throw: an error value that breaks string coercion (no prototype, a throwing `message` getter or `toString`, a symbol, a hostile Proxy) is read through `safe-error-text.ts` and still reaches reporting unchanged.

**Native, per navigator.** Expo Router puts a route in an error boundary only when its module exports `ErrorBoundary`. Every route in `apps/mobile/src/app` exports `FeedbackErrorBoundary` (`route-error-boundaries.test.ts` checks each file): the root layout, the `(tabs)` and `(auth)` layouts, each tab stack and every screen. An error in a tab screen keeps the tab bar, and one in a pushed screen keeps Back. The screen picks its title and message by kind (offline, signed out, no access, not found, server, unexpected) and offers "Report a problem" for the technical ones. If the localized screen or its own hooks throw, `PlainErrorView` takes over: core views, static colors and strings read straight from the catalog modules, no providers. Render-time dates go through `safeFormatDate` (`platform/i18n/format.ts`), which renders an invalid date as an empty string instead of throwing.

**Native fatal errors: the last-crash record.** A fatal JS error in a release build ends the process, and without a DSN nothing kept it. `index.ts` imports `platform/errors/fatal-capture.install` as its first statement (a test checks the order), before Expo Router loads any route. It chains a global handler (`ErrorUtils.setGlobalHandler`, the previous handler still runs, so with Sentry nothing is reported twice) and registers `ExceptionsManager.unstable_setExceptionDecorator`; both run synchronously before native code ends the process. The first fatal of a run is written to `Documents/last-fatal.json`: message, error name, the top 50 stack frames, the route pattern from `useSegments` (never a pathname), the native version and build, the OTA update id and a timestamp. Before it is written, `fatal-scrub.ts` removes email addresses, URL queries and fragments, UUIDs, numbers of six digits or more and id-shaped values (letters and digits mixed, letters whose case flips like a random string, or letters in one case that read like no word, such as `KQZRTWPXBN`), including ids glued to a name such as `todo_Ab3dEf7G`, the query or fragment of a relative URL or a bare word (`/x?debug`, `todos?debug`, `#frag`; inside a URL every `?` and `#` starts the removed tail, while in code `?.` and `??` between operands, a private member such as `#getValue` or `Store.#getValue` and the Hermes frame name `?anon_0_` stay), and formatted numbers of six digits or more (a CPF such as `123.456.789-09`, phone and card numbers, IBANs), and caps the record at 32 KiB of UTF-8. Stack frames keep only frame lines: the header line of `error.stack` repeats the message, which is scrubbed as text. In a frame the id part of an identifier goes and the name stays (`loadTodoAb3dEf7G` becomes `loadTodo<id>`, `load_todo_abc12345` becomes `load_todo_<id>`; `utf8Length`, `setIPv6ToIPv4` and `base64ToUint8Array` stay, while `load_todo_ABv12CD3` becomes `load_todo_<id>`). Scrubbing runs synchronously on the JS thread, so every rule runs in linear time (hand-written scans for URL tails and addresses, regexes that cannot rescan) on at most 16,384 characters; a test scrubs adversarial strings of that length in under 50 ms each. The rules are heuristics: the one-case rule misses about one random one-case id in ten and also hides some long words, so the copy hint asks the person to check the report rather than promising it holds no personal data. The write goes to a temporary file; the record is moved aside (never deleted) and the temporary file moved into its place, so a write that fails at any step keeps the previous record, which the reader finds under either name. On Android a move may copy and then delete, and an interrupted copy leaves a partial file: a file counts only when it parses as a whole record, so the reader falls back to the aside copy and a write never moves a partial record over it. A record that cannot be read right now (data protection during a background launch) is kept; one that is unparsable, expired or dated in the future is deleted. On the next launch Profile shows "Last crash": tapping it copies the scrubbed record with `expo-clipboard` (on iOS `localOnly`, so not to Universal Clipboard, expiring after ten minutes; on Android marked sensitive), and dismissing it deletes the file (a delete that fails says so and keeps the row). The record never leaves the device unless the person pastes it somewhere, and it is deleted after 14 days. A record written by an older build is scrubbed again and rewritten when it is read. Development builds have a "Simulate a crash" row to try it; a development build shows the red error screen instead of closing, so reload to see the row. Not covered: a fatal while the initial bundle evaluates, before the JS runtime is ready. React Native (0.86 and later) handles those in C++, and neither hook sees them.

## 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`: production keeps one request in ten (`0.1`) because every procedure call opens a span, while PR previews keep every request (`scripts/preview-config.mjs` sets `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/fofo/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 came first; the analytics relay (`POST /api/events`) now sits beside it with the same shape and counts page views without cookies for `/admin/analytics`. Web Vitals stay on their own endpoint and in Workers Logs. See [Analytics](/docs/features/analytics).

## 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.

Every oRPC procedure call is one span named after its path, `rpc.todo.list`, with the request id in the attribute `requestId`: filter a trace by it to find the call behind an `x-request-id`. The span is opened for every procedure by the head of the procedure chain (`traced` in `platform/rpc/procedures.ts`), not per feature. The Effect spans of the call's program and the platform's Hyperdrive and fetch spans are its children. A known client refusal carries its code in `rpc.error` (`NOT_FOUND`, `UNAUTHORIZED`). Unexpected failures carry `INTERNAL_SERVER_ERROR` and a fixed exception message. Failed Effect child spans carry `effect.failed=true`. Use the request ID to find the corresponding error report. See [ADR-0010](/docs/adr/0010-procedures-run-one-effect-program).

In the scheduled tick 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/fofo/blob/main/packages/api/src/platform/rpc/request-id.ts)
- [`packages/errors/src/server.ts`](https://github.com/CarlosZiegler/fofo/blob/main/packages/errors/src/server.ts)
- [`apps/web/src/platform/errors/global-handlers.ts`](https://github.com/CarlosZiegler/fofo/blob/main/apps/web/src/platform/errors/global-handlers.ts)
- [`apps/web/src/platform/errors/chunk-reload.ts`](https://github.com/CarlosZiegler/fofo/blob/main/apps/web/src/platform/errors/chunk-reload.ts)
- [`apps/mobile/src/platform/errors/fatal-capture.ts`](https://github.com/CarlosZiegler/fofo/blob/main/apps/mobile/src/platform/errors/fatal-capture.ts)
- [`apps/mobile/src/platform/errors/fatal-scrub.ts`](https://github.com/CarlosZiegler/fofo/blob/main/apps/mobile/src/platform/errors/fatal-scrub.ts)
- [`packages/error-reporting/src/scrub.ts`](https://github.com/CarlosZiegler/fofo/blob/main/packages/error-reporting/src/scrub.ts)
- [`deploy/error-tracker/compose.yml`](https://github.com/CarlosZiegler/fofo/blob/main/deploy/error-tracker/compose.yml)
- [`packages/api/src/platform/effect/tracer.ts`](https://github.com/CarlosZiegler/fofo/blob/main/packages/api/src/platform/effect/tracer.ts)
- [`packages/db/src/audit.ts`](https://github.com/CarlosZiegler/fofo/blob/main/packages/db/src/audit.ts)
- [`apps/web/wrangler.jsonc`](https://github.com/CarlosZiegler/fofo/blob/main/apps/web/wrangler.jsonc)
