What you'll learn: By the end of this lesson you will be able to explain what it takes for one user click to be one trace from the browser to the database, say which signal (metric, trace or log) answers which question, make a browser send and a backend accept a
traceparentheader across a CORS boundary, bring server timings back to the page, choose between head and tail sampling, find a broken link in the chain, and keep personal data and metric labels under control.
Think of a parcel with a tracking number. The sender, the depot and the van each scan it, and when the parcel is late you read one history instead of phoning three companies. A web request crosses a browser, an API and a database in the same way; the trace id is its tracking number.
The running example is the checkout page of a grocery marketplace (the front end of the ShopStream marketplace used in this course). Some customers say "Pay" is slow. The question is where the time goes.
The core idea
- One id, every tier. A trace id created in the browser and forwarded on every hop lets you assemble the browser's, the API's and the database's spans into one picture.
- Three signals, three questions. Metrics say that something is wrong and how often. Traces say where in the path. Logs say what exactly happened. You move between them with ids, not by guessing.
- The browser is the weak link. It runs on devices you do not control, behind cross-origin rules and privacy limits, so the chain most often breaks at its first hop.
The three signals and the ids that join them
The terms come from OpenTelemetry. A trace is a set of spans that share one trace id; a span is a unit of work with a start and an end; a child span names its parent by span id, and a root span has none. Span kinds describe the role: CLIENT is a request to a remote service where the caller waits, and SERVER is the handling of that request.
| Signal | Answers | Joined to the others by |
|---|---|---|
| Metrics | Is it wrong, how often, since when? | Exemplars that point to a trace id |
| Traces | Which hop is slow or failing? | Trace id and span id |
| Logs | What did the code say at that moment? | TraceId and SpanId fields on the log record |
The OpenTelemetry log data model defines TraceId and SpanId fields on a log record, and says that if a span id is present a trace id should be too. Prometheus can store exemplars, which its documentation describes as references to data outside the metric set and commonly trace ids, so that you can go from an aggregate sample to one request that produced it. That is the route from "the p95 rose" to "here is one slow checkout".
Figure 1. One click, five tiers
How to read this: solid arrows are the request, carrying the same trace id. Dashed arrows send telemetry to the store, where spans from different tiers are assembled by trace id. If the edge drops the header, the API starts a second trace.
Correlation IDs and Trace Context Across Services teaches the header itself, and Observability with Micrometer, Prometheus and OpenTelemetry teaches the server side. This lesson adds the browser end and the joins.
Starting the trace in the browser
The W3C Trace Context header is traceparent: version-trace-id-parent-id-trace-flags, where the trace id is 32 lowercase hex characters, the parent id 16, and all-zero ids are invalid. OpenTelemetry's default propagator follows this specification, and its documentation says instrumentation libraries usually inject and extract the header for you. The OpenTelemetry page for browser setup states, at the time of writing, that client instrumentation for the browser is experimental and mostly unspecified, and it lists document load, XMLHttpRequest and user interaction instrumentations. A separate lesson in this module covers OpenTelemetry in the browser.
Three browser facts decide whether it works.
- CORS.
traceparentis not a CORS-safelisted request header, so a cross-origin request that sets it is preflighted, and the server must answer withAccess-Control-Allow-Headerslisting it. Otherwise the browser blocks the real request. The Trace Context specification itself warns that cross-origin requests with these headers may fail for exactly this reason. See CORS, Preflight and Credentials Debugging. - Where to send it. Add it only to your own API origins; third-party hosts get an identifier they do not need and may fail the preflight.
- Privacy. The specification says tracing vendors must not put personally identifiable or sensitive data in
traceparentortracestate, and notes that a trace id can let a service correlate requests from one transaction. Keep user ids out of the id; attach them, if policy allows, as attributes on the span.
Bringing the server's view back to the page
Traces flow from the page to a store. The reverse is useful too: the page can read how long the server spent. A response may carry Server-Timing: db;dur=53, app;dur=47.2, and the page can read the entries from the serverTiming array of a PerformanceResourceTiming entry. MDN gives two cautions: for a cross-origin resource the browser withholds requestStart, responseStart and serverTiming unless the response carries Timing-Allow-Origin, and the header may expose sensitive application and infrastructure information, so decide which metrics to send and to whom.
A real-user-monitoring beacon (see Real User Monitoring) can therefore report how much of a click was server time without a trace backend, at the cost of coarse numbers.
Illustration 1: the minimal example
Parsing the header the way a service should, rejecting invalid values. Run in Node (the full script is the one in the next section):
console.log(parseTraceparent("00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01"));
console.log(parseTraceparent("00-00000000000000000000000000000000-00f067aa0ba902b7-01"));
Output, from the full script run in Node 26.13.1:
{
traceId: '4bf92f3577b34da6a3ce929d0e0e4736',
parentId: '00f067aa0ba902b7',
sampled: true
}
null
The first value is the specification's own example. The second has an all-zero trace id, which the specification says is invalid, so the parser returns null and a service would start a new trace.
Reading a trace
A trace is useful because durations nest. The time in a span that its children do not account for is its own work, or time spent waiting for something unrecorded. A gap between a browser CLIENT span and the SERVER span under it is the network, proxies and queueing.
Illustration 2: the realistic example
Six spans, exported by three tiers, with illustrative numbers (they come from no real system). The script assembles them by trace id and parent id and prints each span's total and self time:
const TRACEPARENT = /^00-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$/;
function parseTraceparent(value) {
const m = TRACEPARENT.exec(value ?? "");
if (!m || /^0+$/.test(m[1]) || /^0+$/.test(m[2])) return null;
return { traceId: m[1], parentId: m[2], sampled: (parseInt(m[3], 16) & 1) === 1 };
}
// Spans as three tiers might export them. The numbers are illustrative.
const spans = [
{ tier: "browser", name: "click Pay", id: "a1", parent: null, trace: "t1", start: 0, ms: 940 },
{ tier: "browser", name: "POST /checkout", id: "a2", parent: "a1", trace: "t1", start: 20, ms: 900 },
{ tier: "api", name: "POST /checkout", id: "b1", parent: "a2", trace: "t1", start: 70, ms: 800 },
{ tier: "api", name: "SELECT stock", id: "c1", parent: "b1", trace: "t1", start: 90, ms: 60 },
{ tier: "database", name: "INSERT order", id: "c2", parent: "b1", trace: "t1", start: 170, ms: 620 },
{ tier: "api", name: "POST /checkout", id: "z9", parent: null, trace: "t2", start: 0, ms: 300 },
];
function show(traceId) {
const own = spans.filter((s) => s.trace === traceId);
const walk = (parent, depth) =>
own
.filter((s) => s.parent === parent)
.forEach((s) => {
const children = own.filter((c) => c.parent === s.id);
const self = s.ms - children.reduce((sum, c) => sum + c.ms, 0);
console.log(`${" ".repeat(depth)}${s.tier}: ${s.name} ${s.ms} ms (self ${self} ms)`);
walk(s.id, depth + 1);
});
walk(null, 0);
}
console.log(parseTraceparent("00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01"));
console.log(parseTraceparent("00-00000000000000000000000000000000-00f067aa0ba902b7-01"));
console.log("--- trace t1 (header forwarded)");
show("t1");
console.log("--- trace t2 (a proxy dropped the header: the server started its own trace)");
show("t2");
The t1 part of the output, from Node 26.13.1:
--- trace t1 (header forwarded)
browser: click Pay 940 ms (self 40 ms)
browser: POST /checkout 900 ms (self 100 ms)
api: POST /checkout 800 ms (self 120 ms)
api: SELECT stock 60 ms (self 60 ms)
database: INSERT order 620 ms (self 620 ms)
Reading it: of 940 ms, 800 ms is the API span, and 620 ms of that is the order insert. The 100 ms between the browser's request span and the API's server span is outside both: network, TLS, proxy and queue time, which only a browser-side span can reveal. The metric "checkout p95" could say the page was slow; only the trace says the insert is the cause.
Figure 2. Where did the time go?
present?"} Q -->|"no"| H["Header lost:
check CORS, proxy"] Q -->|"yes"| G{"Large gap between
client and server span?"} G -->|"yes"| N["Network, proxy, queue"] G -->|"no"| S["Child span with most self time"] S --> L["Read its logs by trace id"]
How to read this: a metric starts the search and an exemplar trace narrows it. The decisions use only facts a trace shows: is there a server span, how big is the client-to-server gap, which child is slowest. Logs come last, filtered by the trace id.
Sampling: you cannot keep everything
Browsers produce a trace per interaction for every user, which is more than most teams can store. OpenTelemetry's documentation describes two approaches. Head sampling decides as early as possible, is simple and cheap, but cannot decide from the whole trace, so it cannot guarantee that every trace containing an error is kept. Tail sampling decides after considering all or most spans, so it can keep errors and slow traces, but is harder to implement and to run, needs stateful components, and the page says larger systems almost always need it. The two can be combined.
The traceparent sampled flag is the least significant bit of trace-flags; the specification says that when set it denotes that the caller may have recorded trace data. It is a recommendation from the caller, and a service may decide differently. If the page does not sample, the backend can still sample its own part, but the trace will have no browser root; and a skipped session cannot be searched for errors afterwards, which is one reason to send error reports (see Error Reporting and Source Maps) with the trace id on every error regardless of the trace sampling decision.
Figure 3. Sampling decides what survives
How to read this: the head decision at the page reduces volume early; the tail decision at a collector sees the assembled trace and keeps the interesting ones. This is one possible arrangement, not the only one.
Cardinality and privacy
Two limits keep the data useful and safe. Metric labels must stay low in cardinality: the Prometheus documentation warns that every unique combination of label values is a new time series, and tells you not to use labels for dimensions with many values such as user ids or email addresses. A user id belongs on a trace attribute or a log line, not a metric label. And a trace is personal data waiting to happen: URLs with tokens, form values in span attributes, OpenTelemetry baggage that travels with every request (its documentation says not to put credentials, API keys or personal data in it). Scrub in the browser before export, as in the error-reporting lesson.
Illustration 3: a failure, the chain breaks at the edge
The same script prints trace t2:
--- trace t2 (a proxy dropped the header: the server started its own trace)
api: POST /checkout 300 ms (self 300 ms)
Here a proxy in front of the API stripped traceparent. With no header to continue, the API started a trace of its own, so the server's 300 ms has no browser root and no database child, and the browser's own span has no server span. Both halves look healthy and neither explains the slow click. Three causes are common: the proxy or gateway does not forward the header; the preflight does not list traceparent, so the browser blocks or omits it; or work moves through a queue, where the trace needs a span link (OpenTelemetry says links associate a span with others, implying a causal relationship, and suit asynchronous work that cannot sit in the same parent-child tree).
Trade-offs
| Choice | Gain | Cost |
|---|---|---|
| Trace from the browser | The whole path, including network and the client's own time | CORS setup, more data, privacy review |
| Start traces at the API | Simple, no browser changes | The click, the network gap and client time are invisible |
| Head sampling | Low cost, simple | Cannot keep every error trace |
| Tail sampling | Keeps errors and slow traces | A stateful collector to run |
Build it
This lesson has no lab. The best fit is the existing correlation-id lab in Correlation IDs and Trace Context Across Services. The script above is plain Node, needs no install, and its output is shown unedited; the numbers in it are illustrative. No browser, collector or trace backend was run for this lesson.
In practice: why is "Pay" slow?
This is a realistic scenario, not a case history. It is a composite built from common production patterns. It describes no specific company or product, and every number in it is an illustrative assumption.
The situation
Support reports that the Pay button is slow for some customers. The API dashboard shows a healthy checkout latency, the front end shows a worse number, and each team says the other is at fault.
Starting architecture
Figure 4. Two islands
How to read this: the warning boxes hold data that cannot be joined to anything else, so each team sees only its own half.
Options considered
| Option | What it fixes | What it costs | Risk |
|---|---|---|---|
| Server-Timing on responses | Server share visible on the page | Header on every response | Exposing internals |
| Browser-to-database trace | One view, one id | CORS, sampling, privacy work | Dropped headers, data volume |
The decision
| Field | Decision record |
|---|---|
| Context | Browser and server data cannot be joined, so ownership of slowness is argued, not measured. |
| Decision | Start the trace in the browser for checkout only, send traceparent to the first-party API origin, allow it in the preflight, forward it at the edge, put TraceId on log lines, keep error traces with tail sampling, and expose Server-Timing to same-origin pages only. |
| Consequences, good | One trace per slow click; a metric can link to an example trace. |
| Consequences, bad | A privacy review of span attributes, a collector to run, more telemetry cost. |
| Revisit when | Other flows need tracing, volume grows, or the collector becomes a bottleneck. |
Rollout and verification
- Send one synthetic checkout and confirm the trace has a browser span, an API span and a database span with one trace id.
- Test the failure on purpose: remove the header from the preflight in a test environment and confirm the alert for "API traces with no browser parent".
- Check a trace attribute list for tokens and form values before widening.
The 2 a.m. failure
After an edge configuration change, traces for checkout lose their browser roots and database children: the dashboard shows hundreds of one-span traces. The change stripped unknown request headers and the preflight response no longer lists traceparent.
First three checks: (1) look at a raw request in the edge logs and see whether traceparent arrives; (2) check the preflight response for Access-Control-Allow-Headers; (3) check the browser console for blocked requests. Mitigation: roll back the edge change. Follow-up: a synthetic check that fails when a checkout trace has fewer than three tiers.
Architect's notes
- Treat the header as a contract. Every proxy and gateway on the path must forward it; test that it does.
- Measure the chain. A "traces with a browser parent" ratio finds breaks early.
- Decide what is personal before you collect it. Spans are easier to filter before export than after storage.
Common mistakes
- Starting traces at the API and calling it end to end.
- Forgetting the preflight so cross-origin requests fail or lose the header.
- Sending
traceparentto third-party origins. - User ids as metric labels.
Key takeaways
- One trace id forwarded on every hop turns many islands of data into one trace.
- Metrics say that, traces say where, logs say what; ids and exemplars join them.
traceparentneeds CORS preflight approval cross-origin, and every proxy must forward it.Server-TimingwithTiming-Allow-Originbrings the server's view back to the page.- Head sampling is cheap and blind; tail sampling keeps the interesting traces and costs more to run.
- Keep metric labels low in cardinality and personal data out of ids, attributes and baggage.
Practice exercises
Exercise 1: Starter (30 min). Add a third trace to the script whose database span has the wrong parent id, and explain how the output shows the orphan.
Exercise 2: Intermediate (2 hours). List every hop between your browser and your database for one real action and mark whether each forwards traceparent. Test the one you are least sure of with curl.
Exercise 3: Advanced (half day). Design the sampling policy for a checkout flow: what the page samples, what the collector keeps, and how you would measure that errors are always kept.
The other side of this topic
The back end view of this topic is metrics, logs and traces from the services themselves, with exemplars and an SLO on top. It is covered in Observability with Micrometer, Prometheus and OpenTelemetry and Correlation IDs and Trace Context Across Services.
Related reading
In this course:
- Error Reporting and Source Maps: the error side of the same signals.
- Real User Monitoring: browser field data and what it can and cannot see.
- Micro-Frontend Failure Isolation and Observability: the same question across several teams.
- Same-Origin Policy and CORS: why headers and timings are withheld across origins.
- Backend for Frontend (BFF): a first-party origin that makes propagation simpler.
Planned in this module, named in plain text: logging, tracing and correlation ids for the front end; OpenTelemetry in the browser.
Official documentation
- W3C Trace Context: the
traceparentformat, the sampled flag, privacy. - OpenTelemetry: Context propagation and Sampling: propagators, head and tail sampling.
- OpenTelemetry: Traces: spans, parents and links.
- MDN: Server-Timing and PerformanceResourceTiming: server metrics in the page.
- MDN: CORS: preflights and allowed headers.
- Prometheus: metric and label naming: why labels must stay low in cardinality.
- Prometheus: feature flags (exemplar storage): exemplars that link metrics to traces.