WORKINGCHAPTER 14

Frontend and mobile: RUM, Core Web Vitals, session replay

The part of the request your servers never see: measuring it in the user's browser, joining it to the backend trace, and not recording their password while you do

55 MINOBSERVABILITYUPDATED 2026-11-02
PREDICT

The frontend team configures the browser OTel SDK to keep 10% of traces to save money. The backend services use the default ParentBased(AlwaysOn) sampler and keep everything. After the change, what fraction of checkout requests that start in the browser have a gateway trace in Tempo?

Everything in this course so far has started at the gateway. A user’s experience starts earlier. The browser resolves DNS, opens TLS, downloads HTML, parses it, fetches scripts and styles, runs JavaScript, renders, waits for a click, runs handlers, calls your API, and repaints. Your backend trace covers one slice of that. Real user monitoring (RUM) measures the rest from inside the browser or the app, on the user’s device and network, and sends it home.

This chapter covers what to measure (Core Web Vitals and the browser Performance APIs they are built on), how to join a browser span to the backend trace, what client-side sampling does to that trace, what session replay records and what it costs you in privacy, and what changes on mobile. The lab puts an instrumented page in front of the demo app’s gateway and follows one click into Tempo.

RUM and synthetic answer different questions

Synthetic monitoring runs a scripted browser from a data centre on a schedule: load the page, click checkout, assert on the result, record the timings. It is consistent, it runs at 3 a.m. when nobody is shopping, and it catches a broken deploy before users do. Module O3 builds one. It also measures a fast machine on a fast network with a warm DNS cache and no browser extensions, so its numbers are a floor, not a distribution.

RUM measures every real page view, or a sample. Its numbers are the distribution your users experience, split by country, device class, browser, connection type and release. It is noisy, it needs volume to say anything, and it cannot tell you about a page nobody visited. You want both: synthetic to know it works, RUM to know how it feels.

Google publishes a public RUM dataset for popular origins, the Chrome UX Report (CrUX), collected from opted-in Chrome users. It is the data behind the Core Web Vitals assessment in Search Console and PageSpeed Insights, and it is a useful check on your own RUM: if your numbers are much better than CrUX for your origin, your sampling or your instrumentation is missing your slow users.

Core Web Vitals

Core Web Vitals are three user-centred metrics with published thresholds, assessed at the 75th percentile of page loads, separately for mobile and desktop. A page passes when all three are good at p75.

metric measures good needs improvement poor
LCP, Largest Contentful Paint when the largest image or text block in the viewport rendered ≤ 2.5 s 2.5 s to 4.0 s > 4.0 s
INP, Interaction to Next Paint delay from a click, tap or key press to the next frame ≤ 200 ms 200 ms to 500 ms > 500 ms
CLS, Cumulative Layout Shift how much visible content moves unexpectedly ≤ 0.1 0.1 to 0.25 > 0.25

LCP is measured from navigation start to the render of the largest element: an <img>, a video poster, a CSS background image, or a block of text. It is usually dominated by server response time plus the time to discover and download the hero image. The backend owns the first part, and that is where the browser span and the backend trace meet.

INP replaced First Input Delay as a Core Web Vital in March 2024. FID measured only the delay before the first interaction’s handler started. INP observes every click, tap and key press in the visit, measures each from input to the next paint (input delay, then handler processing, then presentation delay), and reports roughly the worst: one of the highest is ignored for every 50 interactions so a single outlier on a long session does not dominate. Scrolling and hovering do not count. A poor INP almost always means long JavaScript tasks on the main thread.

CLS sums layout-shift scores (fraction of the viewport that moved times the distance it moved) within the worst burst of shifts. Images without dimensions and late-injected banners are the usual causes.

The Performance APIs underneath

You will use the web-vitals library rather than compute these yourself, because the edge cases (background tabs, back-forward cache restores, prerendering) are many. It is still worth knowing what it reads, because the same APIs answer questions the vitals do not.

API entry type what it gives you
Navigation Timing navigation one entry per page load: DNS, TCP, TLS, request start, response start (TTFB), DOM content loaded, load event
Resource Timing resource one entry per fetched resource: same phases per URL, plus transfer and encoded sizes
Paint / LCP paint, largest-contentful-paint first contentful paint, then each new LCP candidate
Event Timing event, first-input per-interaction timings that INP is built from
Layout Instability layout-shift each shift and its score
Long Tasks longtask every main-thread task over 50 ms

All of them are read with a PerformanceObserver. The buffered: true flag delivers entries that happened before you subscribed, which matters because your script loads after the navigation started:

new PerformanceObserver((list) => {
  for (const e of list.getEntries()) console.log('long task', Math.round(e.duration), 'ms at', Math.round(e.startTime));
}).observe({ type: 'longtask', buffered: true });

Two traps. Resource Timing for a cross-origin URL (your CDN, your API on another host) reports only the total duration unless that origin sends Timing-Allow-Origin; the phase breakdown is zeroed. And PerformanceObserver.supportedEntryTypes differs by browser: Safari has long lagged on Long Tasks, LCP and Event Timing, so check support before you trust a vitals dashboard to represent your iPhone users. A RUM chart of LCP is a chart of the browsers that report it.

OpenTelemetry in the browser

The OpenTelemetry JavaScript SDK runs in the browser, and the project marks browser instrumentation as experimental. The packages you need, as listed on opentelemetry.io:

  • @opentelemetry/api, the API every instrumentation calls.
  • @opentelemetry/sdk-trace, the tracer provider and span processors. For years the browser package was @opentelemetry/sdk-trace-web with a WebTracerProvider; it is now deprecated in favour of TracerProvider from @opentelemetry/sdk-trace, which is what the current docs use. Older tutorials show the old names.
  • @opentelemetry/context-zone, a context manager built on zone.js, so the active span survives setTimeout, promise callbacks and event handlers.
  • @opentelemetry/core for the W3C traceparent propagator.
  • @opentelemetry/instrumentation and the instrumentations: @opentelemetry/instrumentation-document-load (a span tree for the page load built from Navigation and Resource Timing), @opentelemetry/instrumentation-fetch and -xml-http-request (a client span per API call, with traceparent injected), -user-interaction (a span per click).
  • @opentelemetry/exporter-trace-otlp-http, which posts OTLP JSON to a Collector’s /v1/traces.

The fetch instrumentation is itself marked deprecated in favour of a new set of instrumentations being developed in the separate opentelemetry-browser repository, whose telemetry differs. The package landscape is moving; pin versions and read the changelog before you upgrade.

Joining the browser to the backend is the same W3C Trace Context you met in tracing 101. When the browser calls fetch('/checkout') inside an active span, the fetch instrumentation starts a CLIENT span and injects traceparent: 00-<trace id>-<client span id>-01. The gateway’s FastAPI instrumentation extracts it and makes its SERVER span a child. In Tempo the trace now starts in the browser.

There is a CORS rule on each hop. For same-origin requests the instrumentation injects the header by default. For a cross-origin API (api.example.com called from www.example.com) it injects only for URLs matching propagateTraceHeaderCorsUrls, because adding a non-safelisted header turns a simple request into one with a preflight, and the API must answer that preflight with Access-Control-Allow-Headers: traceparent (and tracestate if you use it). Forget the server half and the browser blocks your real API call, not only the tracing.

The export is cross-origin too: the page posts spans to the Collector on another port or host, so the Collector’s OTLP HTTP receiver needs cors.allowed_origins. And that endpoint is now public. Anyone can post spans to it. Put it behind a path on your own edge with rate limits and a body size cap, never embed a credential in the page, and treat every attribute that arrives from a browser as untrusted input.

Sampling on the client

The browser is now the root of the trace, so it makes the head sampling decision, and the Predict shows the consequence: whatever ratio the frontend picks, the backend’s parent-based samplers inherit. Three practical rules follow.

  • Agree the ratio across teams, or make the backend ignore the browser’s flag for its own spans, which loses the parent link for unsampled requests.
  • Sample by session, not by request, if you want to replay a user’s journey: decide once per session (hash a session id) and apply it to every trace in that session.
  • Send vitals as aggregates at 100% and traces at a ratio. A web vital is a handful of bytes, and p75 by country and device needs every data point you can get. Traces are large and you need few of them.

Tail sampling in the Collector, which the module project builds, can keep every browser trace with an error, but it only sees what the browser chose to send.

Session replay and its privacy cost

Session replay records the DOM and every mutation to it, plus mouse, scroll and input events, and plays them back as a video-like reconstruction. Libraries like rrweb do it by serialising the page and streaming mutation records. For debugging a confusing UI it is extraordinary. It is also a recording of everything the user saw and typed.

In 2017 researchers at Princeton studied seven replay providers on the top 50,000 sites and found them on 482. Default masking covered password fields and little else: one checkout leaked full card details to the replay vendor as they were typed, pharmacy pages leaked prescriptions next to customers’ names, and some providers served playback over plain HTTP. The site owners had installed a debugging tool and shipped their customers’ data to a third party.

rrweb’s own defaults show the shape of the problem: maskAllInputs is false, and maskInputOptions masks only password inputs. Content is masked or blocked by class (rr-mask, rr-block) that a developer has to remember to add to every sensitive element, forever. The safe configuration inverts it: mask all text and inputs by default, unmask specific non-sensitive regions, block payment iframes entirely, get consent where the law requires it (GDPR does for most of this), and set a short retention. Replay is also heavy: a session can be megabytes, so it is sampled harder than traces, often triggered only on errors.

Mobile: cold starts and offline batching

Native apps have the same questions with different mechanics. The headline metric is app start: cold start (process not running), warm start (process alive, activity recreated) and hot start (brought to foreground). Android vitals treats a cold start of 5 s or more as excessive. Measuring it needs instrumentation that runs before your application code, which is why mobile SDKs (OpenTelemetry Android and Swift, vendor SDKs) hook process start. On the web, Grafana’s Faro SDK and the vendor RUM scripts play the same role.

Mobile telemetry is offline by default. A phone in a tunnel cannot export, so SDKs buffer spans and logs to disk and send them in batches when the network returns, minutes or days later. Your pipeline must accept late data, and your timestamps come from a device clock that may be wrong. Every event needs the app version, because a fix ships to 30% of users in the first week and old versions linger for months; a regression dashboard that does not split by version averages the fixed and the broken.

PII in frontend telemetry

The browser leaks personal data into telemetry in ways the backend does not. url.full on a fetch span includes the query string, which is where email addresses, reset tokens and search terms live. document.title and element text in click spans can contain a name. IP addresses arrive at your Collector with every export. Strip query strings in the SDK where you can (the fetch instrumentation’s applyCustomAttributesOnSpan hook can overwrite attributes), and scrub again in the Collector, which is the next chapter’s project. Never put a user’s email or name in a span attribute; use an opaque id, and hash that in the Collector too.

LAB One click, from the browser to Postgres, in one trace ~50 MIN
YOU NEEDDocker Desktop or Docker Engine with Compose v2the ATLAS repo cloned, working in labs/observabilityNode.js 20 or later with npma Chromium-based browser (Chrome, Edge or Brave) for complete web-vitals support

You will serve an instrumented page from the gateway, click a button that calls /checkout, and see the browser span as the parent of the gateway span in Tempo.

1. Start the stack and allow the page’s origin on the Collector. The page will be served from http://localhost:8080 and export to http://localhost:4318, a different origin. In otel/collector.yaml, give the HTTP receiver a CORS block:

receivers:
  otlp:
    protocols:
      grpc:
        endpoint: 0.0.0.0:4317
      http:
        endpoint: 0.0.0.0:4318
        cors:
          allowed_origins: ["http://localhost:8080"]
          max_age: 7200
cd labs/observability
printf 'OTEL_SDK_DISABLED=false\nLOG_FORMAT=json\nOTEL_SEMCONV_STABILITY_OPT_IN=http/dup\nLOADGEN_RPS=2\n' > .env
docker compose --profile telemetry up -d --build
curl -s -o /dev/null -w '%{http_code} ' -X OPTIONS localhost:4318/v1/traces \
  -H 'Origin: http://localhost:8080' -H 'Access-Control-Request-Method: POST' \
  -H 'Access-Control-Request-Headers: content-type'
curl -s -D - -o /dev/null -X OPTIONS localhost:4318/v1/traces \
  -H 'Origin: http://localhost:8080' -H 'Access-Control-Request-Method: POST' | grep -i access-control-allow-origin
204 (or 200) and a header Access-Control-Allow-Origin: http://localhost:8080. That is the preflight the browser will send before every export. Loadgen is turned down to 2 RPS so your own clicks are easy to find.

2. Write the browser telemetry module. Create services/gateway/web/package.json:

{
  "private": true,
  "type": "module",
  "dependencies": {
    "@opentelemetry/api": "1.9.0",
    "@opentelemetry/context-zone": "2.12.0",
    "@opentelemetry/core": "2.12.0",
    "@opentelemetry/exporter-trace-otlp-http": "0.223.0",
    "@opentelemetry/instrumentation": "0.223.0",
    "@opentelemetry/instrumentation-document-load": "0.68.0",
    "@opentelemetry/instrumentation-fetch": "0.223.0",
    "@opentelemetry/resources": "2.12.0",
    "@opentelemetry/sdk-trace": "2.12.0",
    "web-vitals": "6.2.3"
  },
  "devDependencies": { "esbuild": "0.28.2" }
}

and services/gateway/web/otel.js:

import { context, propagation, trace, SpanStatusCode } from '@opentelemetry/api';
import { TracerProvider, BatchSpanProcessor } from '@opentelemetry/sdk-trace';
import { ZoneContextManager } from '@opentelemetry/context-zone';
import { W3CTraceContextPropagator } from '@opentelemetry/core';
import { resourceFromAttributes } from '@opentelemetry/resources';
import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http';
import { registerInstrumentations } from '@opentelemetry/instrumentation';
import { DocumentLoadInstrumentation } from '@opentelemetry/instrumentation-document-load';
import { FetchInstrumentation } from '@opentelemetry/instrumentation-fetch';
import { onLCP, onINP, onCLS } from 'web-vitals';

const provider = new TracerProvider({
  resource: resourceFromAttributes({ 'service.name': 'checkout-web', 'deployment.environment': 'lab' }),
  spanProcessors: [
    new BatchSpanProcessor({
      exporter: new OTLPTraceExporter({ url: 'http://localhost:4318/v1/traces' }),
      scheduledDelayMillis: 1000,
    }),
  ],
});
trace.setGlobalTracerProvider(provider);
context.setGlobalContextManager(new ZoneContextManager().enable());
propagation.setGlobalPropagator(new W3CTraceContextPropagator());

registerInstrumentations({
  instrumentations: [
    new DocumentLoadInstrumentation(),
    new FetchInstrumentation({ ignoreUrls: [/:4318\//] }),
  ],
});

const tracer = trace.getTracer('checkout-web');

export function checkout(user, items) {
  return tracer.startActiveSpan('checkout click', async (span) => {
    try {
      const res = await fetch(`/checkout?user=${user}&items=${items}`);
      const body = await res.json();
      if (!res.ok) span.setStatus({ code: SpanStatusCode.ERROR, message: `HTTP ${res.status}` });
      return body;
    } finally {
      span.end();
    }
  });
}

function report(m) {
  console.log(`[web-vitals] ${m.name} ${m.value.toFixed(m.name === 'CLS' ? 3 : 0)} ${m.rating}`);
  tracer.startSpan('web-vital', { attributes: {
    'browser.web_vital.name': m.name.toLowerCase(),
    'browser.web_vital.value': m.value,
    'browser.web_vital.rating': m.rating,
    'browser.web_vital.id': m.id,
  } }).end();
}
onLCP(report);
onINP(report, { reportAllChanges: true });
onCLS(report, { reportAllChanges: true });

fetch is called synchronously inside startActiveSpan, before the first await, so the fetch instrumentation sees checkout click as the active span and parents its client span under it. The ignoreUrls entry keeps the exporter’s own requests from being traced. The user id is in the URL, which you would scrub in production; it is here because the gateway needs it.

3. Bundle it.

cd services/gateway/web
npm install
npx esbuild otel.js --bundle --format=esm --target=es2020 --outfile=../static/otel.js
ls -lh ../static/otel.js
cd ../../..
A single services/gateway/static/otel.js of a few hundred kilobytes unminified, including zone.js. Add --minify and it drops to roughly a third. That size is a real cost on a mobile connection, and the reason teams load RUM scripts after the page is interactive.

4. Write the page. Create services/gateway/static/index.html:

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>ATLAS shop</title>
</head>
<body>
  <h1>Checkout</h1>
  <p>User <input id="user" type="number" value="42" min="1" max="1000"> items <input id="items" type="number" value="3" min="1" max="100"></p>
  <button id="buy">Buy</button>
  <pre id="out"></pre>
  <script type="module">
    import { checkout } from './otel.js';
    document.getElementById('buy').addEventListener('click', async () => {
      const body = await checkout(document.getElementById('user').value, document.getElementById('items').value);
      document.getElementById('out').textContent = JSON.stringify(body, null, 2);
    });
  </script>
</body>
</html>

5. Serve it from the gateway. In services/gateway/app.py, after the line app, log = create_app("gateway", lifespan=lifespan), add:

from pathlib import Path
from fastapi.staticfiles import StaticFiles

app.mount("/ui", StaticFiles(directory=Path(__file__).parent / "static", html=True), name="ui")
docker compose --profile telemetry up -d --build gateway
curl -s -o /dev/null -w '%{http_code}\n' localhost:8080/ui/
200. The shared Dockerfile copies the whole gateway/ directory, so static/ ships with the image. The web/ source and its node_modules go too; in a real build you would exclude them with a .dockerignore.

6. Click and follow the trace. Open http://localhost:8080/ui/ with the browser’s developer tools on the Network tab, and click Buy three times.

Each click shows a request to /checkout?user=42&items=3 whose request headers include traceparent: 00-<32 hex>-<16 hex>-01, and about a second later a POST to localhost:4318/v1/traces returning 200, preceded once by an OPTIONS preflight.

Now in Grafana (http://localhost:3000, Explore, Tempo, TraceQL) run:

{ resource.service.name = "checkout-web" && name = "checkout click" } >> { resource.service.name = "gateway" }
Three traces. Open one: the root is checkout click from checkout-web, its child is the fetch instrumentation’s client span (named after the HTTP method), whose child is the gateway’s GET /checkout server span, then orders, Postgres, payments and Redis below. The gap between the fetch span’s start and the gateway span’s start is network time plus anything queued before the server; on localhost it is a millisecond or two, on a phone it is often the largest bar in the trace. A separate trace named documentLoad holds the page load, with documentFetch and one resourceFetch span per script.

7. Read the vitals. Look at the browser console.

An [web-vitals] INP line after each click, with a value in the tens of milliseconds and good. LCP and CLS are reported once the page is hidden: switch to another tab and back, and [web-vitals] LCP appears with a value of a few hundred milliseconds. In Tempo, { name = "web-vital" } finds the spans with the browser.web_vital.* attributes. On this page every number is good; it has one small text block and no images.

Make INP poor on purpose. Paste this into the console, then click Buy:

document.getElementById('buy').addEventListener('click', () => { const t = performance.now(); while (performance.now() - t < 400) {} });
The next INP line reports roughly 400 ms or more and needs-improvement or poor. The trace for that click still shows a fast backend. That is the whole argument for RUM: the user waited and the server was not the reason.
Add sampler: new TraceIdRatioBasedSampler(0) to the TracerProvider options in otel.js (import TraceIdRatioBasedSampler from @opentelemetry/sdk-trace), rebuild the bundle and the gateway, hard-reload the page and click Buy. The request still carries traceparent, now ending in -00. Search Tempo for { resource.service.name = "gateway" && span.user.id = 42 } over the last few minutes: your clicks are gone from the backend too, while loadgen’s requests, which carry no traceparent, are still there. The browser’s sampling decision is the backend’s sampling decision. Then remove cors from the Collector config and restart it: exports fail with a CORS error in the console and nothing reaches Tempo, while the checkout itself keeps working. Put the cors block back (the O2 project keeps it) and remove the sampler from otel.js; the LOADGEN_RPS=2 line in .env can stay until the project replaces the file.
DECIDE

Your shop's mobile web checkout converts worse than desktop and nobody knows why. Backend p99 is fine. You have budget for one quarter of frontend observability work and a Collector already running. Product wants session replay of every checkout 'so we can watch what users do'. Legal has not been asked. What do you build first?

READING
  1. DOC
    Web Vitals

    The definitions, thresholds and the 75th-percentile rule, from the team that defines them. Read the overview and the thresholds section; follow the links to LCP and INP for the details.

  2. DOC
    Interaction to Next Paint (INP)

    How INP is computed, why it replaced FID, and the three phases of an interaction. The section on what causes poor INP is the debugging guide.

  3. DOC
    OpenTelemetry JavaScript: Browser getting started

    The official setup for tracer provider, context manager, propagator and document-load instrumentation, kept current with package renames. Read it before upgrading the lab's pinned versions.

  4. DOC
    W3C Trace Context

    The traceparent format and the meaning of the sampled flag that the browser now sets for your backend. Sections 3.2 and 3.3 are the ones you need.

  5. POST
    No boundaries: Exfiltration of personal data by session-replay scripts Steven Englehardt, Gunes Acar, Arvind Narayanan, 2017

    The study behind the privacy section, with screenshots of what replay vendors captured. Read it before anyone installs a replay script.

  6. CODE
    web-vitals Google Chrome

    The library the lab uses, with the API, the attribution build for diagnosing which element or script caused a poor value, and the caveats on each metric. The attribution section is the part to read.

All companies and people in these examples are fictional. Any resemblance to a real business or person is unintended.

RECALL CARDS Tap to flip. They join your review deck when you mark the lesson complete.
NEXT: Project: a production-grade telemetry pipeline →