Skip to content

    Frontend System Design

    OpenTelemetry in the Browser

    Trace a page with OpenTelemetry: context, head sampling, batching and page-hide flushing, CORS and CSP, plus what its docs say about browser stability.

    By Published 13 min read

    Share

    Standard lessonadvancedTypeScript labFrontend System Design

    Before this: Logging, Tracing and Correlation IDs

    What you'll learn: By the end of this lesson you will be able to state, with the date you read it, what the OpenTelemetry documentation says about browser support, describe the four decisions behind browser tracing (which span is the parent, who samples, how spans leave the page, which requests carry the header), explain why spans from a page that is closing are the easiest to lose, list what a browser exporter needs (HTTP, CORS, CSP, a proxy), and design a tracing set-up that does not depend on an unstable package.

    A dashcam records while you drive and uploads in batches. If the car is scrapped before the next upload, that footage is gone, and the crashes that end a journey are the footage you wanted. A browser tracer is a dashcam in the visitor's pocket: it records spans, holds them, sends them in batches, and a visitor who closes the tab ends the journey.

    The running example is the checkout page from Logging, Tracing and Correlation IDs, which put one trace id on every log line and request. This lesson asks what a full tracing SDK adds in the page, what it costs, and how much of it you can rely on today.

    The core idea

    1. OpenTelemetry names the pieces; you still decide four things in the page: which span is the parent, who samples, how finished spans leave, and which requests carry the header.
    2. The browser part is the least settled part of the project. Stability is stated per signal and per package, and for the browser the documentation read for this lesson says experimental. Treat that as a design input: isolate it, pin it, and keep your correlation ids independent of it.
    3. A browser is a hostile place to export from. The page can close at any moment, the collector is on another origin, and the page's security policy may refuse the request.

    Three illustrations run through the lesson: a minimal example (a context manager and a child span), a realistic example (the checkout page exporting in batches) and a failure example (the page closes with spans queued).

    What the documentation says about stability, read on 2026-12-01

    Never write "stable" from memory. These statements were read on 2026-12-01 from the pages named, quoted or closely paraphrased. They may have changed since.

    Page What it said
    OpenTelemetry JavaScript (docs) Status table: Traces Stable, Metrics Stable, Logs Development. "Client instrumentation for the browser is experimental and mostly unspecified." No official supported list of browsers.
    Browser getting started (docs) The same warning. Its example exports to the console; real analysis needs an exporter to a tracing backend.
    Web, under client apps (docs) "The Browser SDK and instrumentations are experimental. Releases can include breaking changes." It supports logs and traces, with no metrics SDK at present.
    opentelemetry-js README Stable for tracing, metrics and logs (API and SDK), with the same experimental wording for browser client instrumentation.
    opentelemetry-browser README Its three packages (browser-api, browser-instrumentation, browser-sdk) are marked experimental; the classic fetch and XMLHttpRequest instrumentations in other repositories are deprecated or will be.
    Specification: versioning and stability "Development" (once called "Experimental"): breaking changes may occur and long-term dependencies should not be taken. "Stable": they may.

    Two things follow. The pages disagree on the status of logs (Development on one, Stable on another), so read the page for the version you install. And "traces are stable" and "browser instrumentation is experimental" describe different things: the trace API and SDK, and the code that watches a page. No version policy was read, so the lesson says nothing about when anything will change.

    For the design: put the tracer behind a small interface of your own, pin versions, read the changelog before each upgrade, and keep the previous lesson's correlation ids working without it.

    Which span is the parent

    Something must say which span is current. The OpenTelemetry JavaScript context documentation says the context API depends on a context manager; without one, context.active() always returns the root context, so nothing gets a parent. It names async_hooks or AsyncLocalStorage for Node and zone.js on the web, and says context.with(ctx, callback) makes a context active for a callback that is called synchronously. It does not describe how browser asynchronous calls behave, so this lesson makes no claim about any real manager.

    The lab models the idea with three managers: none, a synchronous stack, and one that remembers the active context when a callback is scheduled. A click handler starts click-checkout, starts validate-cart inside it, and queues render-confirmation for later.

    Figure 1. The parent of a span depends on when it runs and what remembers the context

    flowchart TD accTitle: Choosing a parent for a new span accDescr: When code starts a span, the tracer asks the context manager for the active context. With no manager the answer is always the root, so the span starts a new trace. With a synchronous manager the answer is the current span only while the handler is still running; a callback that runs later gets the root. With a manager that captures the context when a callback is scheduled, the later callback also gets the original span. S["Code starts a span"] --> M{"Which context
    manager?"} M -->|"none"| R1["Active context is root:
    new trace"] M -->|"synchronous only"| T{"Still inside the
    handler call?"} T -->|"yes"| C1["Child of the
    active span"] T -->|"no, a later task"| R2["Root: new trace"] M -->|"captures when
    scheduled"| C2["Child of the span that
    was active at scheduling"]

    How to read this: an unlinked span is a quiet loss: the trace splits into pieces nothing joins, the same symptom as the lost header in the previous lesson.

    Who decides to keep a trace

    Head sampling decides when a trace starts. The OpenTelemetry sampling page defines it as deciding as early as possible, without looking at the whole trace; its common example derives the decision from the trace id and a target percentage. It cannot guarantee, say, that every trace containing an error is kept. Tail sampling decides after considering all or most spans of a trace: more flexible, but it needs stateful components and more to operate. They are often combined. A page sees only its own spans, so it is a head-sampling place.

    The trace SDK specification gives the lab's vocabulary. The default sampler is ParentBased(root=AlwaysOn): it asks its root sampler only for a span without a parent; otherwise, by default, a sampled remote parent leads to sampling and an unsampled one to dropping. A dropped span has IsRecording false and its attributes and events are discarded. TraceIdRatioBased is described as deprecated in favour of a probability sampler, and its exact algorithm "was never specified" and is not defined to agree between SDKs, so the lab's ratio hash is its own.

    The decision travels in the last field of traceparent. A page that samples one trace in ten and says nothing makes the server sample on its own, and the halves of a trace no longer match; a ParentBased server follows the page. Lab scenario 2 shows a server with a root rate of zero recording only when the page said "sampled".

    How spans leave the page

    The specification describes two built-in span processors. The simple one passes each span to the exporter as soon as it finishes. The batching one queues spans and exports batches, with defaults of queue size 2048 (spans are dropped when it is full), scheduled delay 5000 ms and a maximum batch of 512; it exports when the delay passes, when the queue holds a full batch, or when ForceFlush is called, and never calls the exporter concurrently. The browser getting-started page uses the simple processor with a console exporter and only suggests the batching one.

    For export from a browser, the JavaScript exporters page says gRPC is not supported, so use the HTTP/JSON or HTTP/protobuf exporters (port 4318); the collector must send CORS headers; the site's Content Security Policy may block the request unless it allows the collector's origin; and the collector should not be exposed directly, so put a reverse proxy in front. The Web page adds that headers configured in browser code are visible to users, so no credential belongs in a bundle.

    Figure 2. The pipeline from a span to a backend

    A span passes the sampler, waits in a batch queue and is exported over HTTP through a proxy to a collectorPage code to Sampler (start span); Sampler to Batch queue (recorded spans); Batch queue to Exporter (batch); Exporter to Reverse proxy (HTTP, CORS, CSP); Reverse proxy to CollectorVISITOR'S BROWSEROUR SYSTEMSPage code: starts and ends spansPage codestarts and endsspansSampler: head decisionSamplerhead decisionBatch queue: size, delay, forceFlushBatch queuesize, delay,forceFlushExporter: OTLP over HTTPExporterOTLP over HTTPReverse proxy: CORS, TLSReverse proxyCORS, TLSCollector: port 4318Collectorport 4318start spanrecorded spansbatchHTTP, CORS, CSP

    How to read this: in the left zone spans live only in memory. Each step can lose them: the sampler drops, a full queue drops, the network can refuse.

    When the page goes away

    The batching delay is the dashcam problem. With a 5000 ms delay and a visitor who leaves after two seconds, the spans are still queued when the page ends. MDN's navigator.sendBeacon() page says the most reliable moment to send final data is visibilitychange when the document becomes hidden, that unload, beforeunload and pagehide are unreliable, that queued data is limited to 64 KiB, and that the call returns whether the browser queued it. So the page flushes when the document is hidden, through a transport that survives page hide.

    Figure 3. A visitor leaves with spans still queued

    sequenceDiagram accTitle: Flushing spans when the page is hidden accDescr: A visitor completes a checkout, so three spans end and wait in the batch queue for the scheduled delay. The visitor switches away. The document becomes hidden and the page asks the processor to flush. The exporter hands the batch to a send mechanism that survives the page going away. If the batch is larger than that mechanism allows, the send is refused and the spans are lost. participant V as Visitor participant P as Page participant Q as Batch queue participant T as Send mechanism V->>P: complete checkout (3 spans end) P->>Q: spans wait for the scheduled delay V->>P: switch tab or close P->>Q: visibilitychange to hidden: flush Q->>T: one batch alt batch within the transport's limit T-->>Q: queued for sending else batch too large T-->>Q: refused, spans lost end

    How to read this: flushing on hide is necessary, not sufficient: the batch must also fit what the send mechanism allows.

    Which requests carry the header

    Context leaves the page in a traceparent header (format in the previous lesson). The Web page says propagation is configured separately from exporter CORS, with propagateTraceHeaderCorsUrls on the fetch instrumentation, so the decision is yours per destination. For the first page load, the getting-started page shows a traceparent meta tag in its sample HTML whose fixed value "should be dynamically generated server side", so that the load joins the server's trace.

    Sessions are separate. The Web page says quickStartBrowserSdk alone does not configure sessions, that session timeouts have no defaults, and that "a session identifier is for correlation, not authentication". For consent, it describes starting the SDK with enabled false so no instrumentations run, while spans you create yourself are still exported: a consent gate must cover your own code too.

    Build it: a model of the four decisions

    Goal. Run a model through five situations: the parent of a span under three context managers, head sampling and a server that follows the page's flag, the batching rules, a page hidden with spans queued, and which URLs get the header.

    Setup. The lab is in the course's example workspace (Node 26.13.1). It is pure logic and uses no OpenTelemetry package.

    cd examples/frontend
    pnpm install
    cd labs/otel-browser-model
    pnpm test           # 32 tests
    node src/demo.ts

    Steps.

    1. Run the tests, then the demo, and compare the output below.
    2. In section 1, the middle row breaks only on the deferred callback: the case a synchronous stack cannot handle.
    3. In section 4, no flush loses all three spans, a flush with room sends them, and a flush through a small-cap transport loses them anyway.

    Expected output, captured from a real run (Node 26.13.1, 2026-12-01; scenarios 1 and 2):

    === 1. Which parent does a span get? It depends on the context manager and on an asynchronous hop
    no context manager       validate-cart: new trace         render-confirmation: new trace
    synchronous only         validate-cart: child of 4b884b   render-confirmation: new trace
    captures at scheduling   validate-cart: child of 4b884b   render-confirmation: child of 4b884b
    
    === 2. Head sampling: the root decides, everyone downstream follows the flag
    TraceIdRatio(0.5) over 10 trace ids: 6 kept, 4 dropped
    same ids, second sampler instance:  identical decisions
    server ParentBased(root=ratio 0), parent sampled:     recorded
    server ParentBased(root=ratio 0), parent not sampled: dropped
    server ParentBased(root=ratio 0), no header:          dropped

    Expected output, captured from a real run (the same run; scenarios 3 and 4):

    === 3. The batch processor: size, timer, a full queue, a failed export
    specification defaults: queue 2048, delay 5000 ms, batch 512
    3 spans, batch size 3:           exported 3, queued 0
    2 more, after 4999 ms:           exported 3, queued 2
    after 5000 ms:                   exported 5, queued 0
    8 spans, slow export (queue 4):  exported 0, queued 4, dropped 2
    after the exports answer:        exported 6, queued 0, dropped 2
    first export fails, no retry:    exported 2, failed 2 (this model drops a failed batch)
    
    === 4. The page is hidden with 3 spans still queued
    no flush on hide:                          sent 0, failed 0, lost in the queue 3
    flush on hide, transport limit 100000:     sent 3, failed 0, lost in the queue 0
    flush on hide, transport limit 300:        sent 0, failed 3, lost in the queue 0

    Expected output, captured from a real run (the same run; scenario 5):

    === 5. Which requests get the trace header
    span context: sampled=true
    https://shop.example/api/cart      00-28a04cb29573d13d810f8312913829f4-b117200a8e71c0c6-01
    https://api.example/orders         00-28a04cb29573d13d810f8312913829f4-b117200a8e71c0c6-01
    https://cdn.example/app.js         no traceparent
    https://api.example.evil.test/x    no traceparent

    What the lab does not show. It is not OpenTelemetry: it uses none of its packages and says nothing about their behaviour or stability. The context managers are teaching models; what a real manager does across browser asynchronous calls was not verified. The ratio hash is the lab's own. A failed batch is dropped without retry because the model chose so; whether a real exporter retries was not verified. The small sizes in scenarios 3 and 4 and the transport limit of 300 are made up (MDN's limit for queued sendBeacon data is 64 KiB).

    Break it. In test/otel.test.ts, the test "a page that goes away without a flush loses what is queued" calls clock.destroy() before advancing time. Remove that line and it fails, because the timer fires and exports the span. Put it back.

    Trade-offs

    Choice Gain Cost
    Full tracing SDK in the page Standard span model, many exporters Bundle size, an experimental browser layer, upgrades
    Own thin tracer plus correlation ids Small, under your control You maintain the span model and export
    Sample in the page Cuts volume and cost at the source Lost traces cannot be recovered
    Flush on hide Fewer lost final spans Batches must fit the transport; more small sends

    Figure 4. Should this page use a full tracing SDK?

    flowchart TD accTitle: Choosing browser tracing accDescr: If the team only needs to join page logs with server logs, correlation ids and a traceparent header are enough. If it needs spans for page work and requests, it can add a tracing SDK, but must pin versions and isolate it because browser support is described as experimental. If it needs to decide on whole traces, such as keeping every trace with an error, that needs tail sampling in a collector, not in the page. Q{"What do you need?"} -->|"join page and server logs"| A["Correlation ids and a
    traceparent header"] Q -->|"spans for page work
    and requests"| B["Tracing SDK behind your
    own interface, versions pinned"] Q -->|"keep every trace
    that has an error"| C["Tail sampling in a
    collector, not in the page"]

    How to read this: the lightest option that answers the question wins; the more you ask of the page, the more of the experimental layer you depend on.

    In practice: traces that only show visitors who stayed

    NOTE

    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

    A shop adds browser tracing to its checkout page. The dashboards look healthy: checkout spans are fast and rarely fail. But support still hears about visitors who "paid and got an error page", and none of those visits appear in the traces.

    Starting architecture

    Figure 5. Starting point: batching with a long delay and no flush on hide

    Starting architecture: spans wait in a batch queue for the scheduled delay and are lost if the page is closed firstCheckout page to Reverse proxy (batch per delay); Reverse proxy to CollectorCheckout page: tracer, batch queueCheckout pagetracer, batchqueueReverse proxy: CORSReverse proxyCORSCollector: OTLP over HTTPCollectorOTLP over HTTPbatch per delay

    How to read this: spans only leave on the timer. A visitor who leaves before the next batch takes the spans with them.

    Options considered

    Option What it fixes What it costs Risk
    Shorten the scheduled delay More spans leave before the page closes More requests Still loses a fast exit
    Flush when the document is hidden The last spans usually leave Batches must fit the transport's limit A refused send still loses them, so count refusals
    Simple processor, one request per span No queue to lose Much more traffic Rate limits

    The decision

    Field Decision record
    Context Traces favour visits that last long enough for the timer, so the failures that end a visit are missing.
    Decision Flush the batch queue when the document becomes hidden, keep batches small, and count refused or failed batches as a metric.
    Consequences, good Fast exits and error pages appear in traces; the bias is measurable.
    Consequences, bad More small sends, and a transport limit to respect.
    Revisit when The tracing packages change their flush behaviour, or payloads grow.

    Rollout and verification

    1. Count first: spans ended per page view against spans received; the gap is the loss.
    2. Ship the flush to a small share of visitors and compare the counts.
    3. Verify: end a span, hide the document, check the collector received it; repeat with a batch over the transport's limit and check the failure is counted.

    The 2 a.m. failure

    A week later an alert fires: collector requests from browsers have jumped (illustrative) and the proxy's error rate rises with them. The flush runs on every visibilitychange, including every tab switch, and each switch sends a small batch until the proxy rate-limits the source.

    First three checks: (1) batches per page view before and after the release; (2) which event triggers the flush; (3) the proxy's rate-limit rule. Mitigation: flush only a non-empty queue, at most once per few seconds. Follow-up: cap flushes per page view and alert on sends per page view.

    Architect's notes

    • Date your stability claims and re-read them at each upgrade.
    • Isolate the experimental layer: one module imports the tracing packages; the app calls your interface.
    • Count your losses: dropped spans, refused batches and failed exports are metrics.
    • Never put a credential in the bundle; headers set in browser code are visible to users.

    Common mistakes

    • Saying "stable" about the browser from memory, or from the status of the trace API.
    • No context manager, so every span starts a new trace.
    • Relying on the batch timer for the last spans of a visit.
    • Forgetting the site's CSP or the collector's CORS headers.
    • Exposing the collector directly to the internet.

    Key takeaways

    • The documentation read on 2026-12-01 calls browser client instrumentation experimental and mostly unspecified, and Browser SDK releases may include breaking changes. Re-read before you decide.
    • Four decisions shape browser tracing: the parent, the sampler, the export path and the header.
    • Without a context manager, context.active() is always the root and no span has a parent.
    • Head sampling cannot keep "every trace with an error"; that needs tail sampling elsewhere.
    • Batching defaults are 2048, 5000 ms and 512; spans are dropped when the queue is full.
    • Flush on visibilitychange, keep batches within the transport's limit, and count losses.
    • A browser exporter uses HTTP, needs CORS and CSP allowances, and sits behind a proxy.

    Practice exercises

    Exercise 1 — Starter (45 min): Open the OpenTelemetry pages in the table. Write down, with today's date, what each says about browser support, and mark where they differ from this lesson.

    Exercise 2 — Intermediate (2 hours): In the lab, make a flush run at most once every 2000 ms. Write the test that shows two hides within 2000 ms produce one send, and say what that costs the last spans.

    Exercise 3 — Advanced (half day): Sketch a thin tracing interface (start, set attribute, end, flush) for your app, name the package behind it, and list what you would check in its changelog before each upgrade.

    In this course:

    Official documentation

    Ask about this article

    Get answers grounded in this post. AI-generated — based on this article, and may be imperfect.

    Scaled AI Weekly

    Enjoyed this? Get more like it every Monday.

    Real architecture decisions, LLMOps patterns that survive production, and engineering leadership advice — from 12+ years of building at enterprise scale. Free. No spam. Unsubscribe anytime.

    Get new articles by email

    Free. We email a confirmation link first, and you can unsubscribe from any email.

    Join engineers building production AI systems

    Comments