Volume 2 Exercises: The Web FrontendPractice for Volume 2
0 / 0

Workbench / Volume 2 Exercises: The Web Frontend

V2·32

Frontend Observability

Exercises for Volume 2, chapter 32: why the frontend is a blind spot; frontend error tracking and source maps; real-user monitoring and Web Vitals in the field; frontend logs, distributed traces and correlation IDs; session context, release health, and the full picture from browser to database. 9 theory questions, 9 programming exercises, 3 cumulative projects, the concepts the chapter leaves out, and 5 senior-level exercises.

32 exercises · ~15 min to read
Updated Suggest a correction

Start here: how this chapter's exercises work

Same four sets and the same locking. The measured exercises use Chromium 153 through Playwright, two local origins, and Node 22. Three exercises run on simulated data (error reports, LCP distributions, crash rates) generated with a seeded random number generator; those are labelled as simulations and report real computations on synthetic inputs. Four outputs are worth knowing before you start:

  • P1: fingerprinting by raw message split 3 bugs into 632 groups.
  • P3: sending a traceparent header to another origin triggered one CORS preflight per distinct URL, and every request failed until the API allowed the header.
  • P4: a ResizeObserver that resized its own target produced 30 identical "loop completed" errors in half a second.
  • P6: on simulated traffic, a crash-rate regression from 0.4% to 0.8% was detected only 12% of the time with 500 sessions per release.

The chapter's lab showed what global error handlers receive (an unhandled rejection, a useless "Script error." from a cross-origin script, a full stack once CORS was enabled), averages versus percentiles (average LCP 2,050 ms, but p75 2,397 ms and 23.9% of visits over 2.5 s), and one trace from click to query. The exercises build on those.

Coverage map.

Chapter component Exercises
why the frontend is a blind spot T1
frontend error tracking: capture, grouping, noise T2, P1, P4
source maps for errors T3, P2
real-user monitoring; Web Vitals in the field; sampling T4, P5
frontend logs T5, P7
distributed traces; trace context propagation T6, P3
correlation IDs T6, P3
session context and privacy T7, P8
release health T8, P6
the full picture: browser to database T9, P9

Theory

T1. Why the frontend is a blind spot

  1. Server logs show that requests succeeded, while users see blank screens, frozen buttons and wrong prices. List the failure classes that only the browser can observe: JavaScript errors, failed chunk loads (chapter 31), hydration mismatches (chapter 22), slow rendering and interactions (chapter 27), requests that never reached the server (offline, CORS, ad blockers, DNS), broken third parties, layout shifts, and service-worker-served stale content.
  2. What makes frontend telemetry harder than backend telemetry: thousands of device/browser/network combinations, untrusted and noisy data (extensions, bots, old browsers), delivery when the page is closing, privacy rules, and cost at scale?
  3. Define the observability goals for TiffinBox's customer app as questions: "Did the release break anything?", "Which users can't check out?", "Why is the kitchen page slow in Vijayawada?", "Did the API change cause the ₹NaN?". Map each to errors, RUM, traces and logs.

T2. Frontend error tracking

  1. The lab's handlers: a failed request surfaced only as an unhandledrejection; a cross-origin script without CORS produced "Script error." with no details; with crossorigin="anonymous" + CORS headers, the full message and stack came through. List everything an error tracker must capture (window error, unhandledrejection, framework error hooks, failed resource loads, console errors optionally, HTTP failures your code handles) and what context to attach.
  2. P1 grouped 1,000 simulated reports from three real bugs: by raw message, 632 groups (messages contained dish ids, order numbers and status codes); with numbers stripped, 3; by top stack frame, 3. Explain fingerprinting, why trackers group by stack frames (after source mapping), and when to set custom fingerprints.
  3. P4: a ResizeObserver resizing its own target generated 30 "ResizeObserver loop completed with undelivered notifications." errors in 500 ms. List common noise sources (browser extensions, ResizeObserver loops, aborted fetches on navigation, bots, old browsers, third-party scripts) and how to filter them without hiding real bugs.

T3. Source maps for error tracking

  1. Chapter 30's P5 set up hidden source maps uploaded per release. Explain how a tracker symbolicates a stack (matching bundle URL or debug ID to the uploaded map, mapping line/column to source, recovering function names), and why errors from a release whose maps weren't uploaded stay unreadable forever.
  2. P2 asks you to compare a raw minified stack (at e (index-Cs1vsncV.js:1:34)) with a symbolicated one (at priceWithGst (src/price.ts:2:29)). What goes wrong in practice (maps for the wrong build, CDN-rewritten URLs, missing sourcesContent, inline/eval'd code, third-party bundles, minifier settings that drop names)?
  3. How do you handle source maps for server-rendered code (Node stack traces with --enable-source-maps), for workers and service workers, and for errors thrown in code generated at runtime?

T4. Real-user monitoring and Web Vitals in the field

  1. The lab: over 1,000 visits, the average LCP was 2,050 ms (under the 2.5 s line), but the p75 was 2,397 ms and 23.9% of visits exceeded 2.5 s (p95 5,573 ms). Explain why percentiles and "share over threshold" are the right summaries, and which segments to split by (route template, device memory, connection, country/city, browser, logged-in, release, A/B variant).
  2. P5 simulated 200,000 visits (true p75 LCP 2,258 ms) and estimated p75 from random samples 20 times each: a 0.1% sample (~200 visits) gave estimates between 2,102 and 2,357 ms (±5.6%); 1% (~2,000) between 2,194 and 2,369 ms (±3.9%); 10% (~20,000) between 2,237 and 2,273 ms (±0.8%). How do you choose a sampling rate, and why does segmenting (per route × device × city) require more samples than the global number suggests?
  3. What does field data show that lab data can't (chapter 27's T1), and how do you combine RUM with CrUX (public data for your origin), Lighthouse CI (lab regressions) and synthetic monitoring (scripted checks from fixed locations)?

T5. Frontend logs

  1. What should a frontend log (state transitions that matter, API failures with status and request id, feature flag evaluations, chunk-load errors, service worker updates, offline/online transitions) and what shouldn't it (every click, personal data, tokens, full API responses)?
  2. Design the logging pipeline: structured events with levels, batching in memory, sending with sendBeacon/fetch(keepalive) on visibilitychange (chapter 27's P9), size limits, sampling by level, backpressure when the endpoint is down, and an ingestion endpoint that validates and rate-limits.
  3. How do breadcrumbs differ from logs, and why are they the most useful part of an error report?

T6. Distributed traces and correlation IDs

  1. The lab's trace: the browser created traceparent: 00-{trace id}-{span id}-01; the BFF and orders service created child spans, ending with a 42 ms SQL query, all sharing one trace id. Explain W3C Trace Context (traceparent, tracestate), spans, parents and sampling flags, and what the browser's span represents (a click, a fetch, a page load).
  2. P3: sending traceparent to an API on another origin triggered a preflight (OPTIONS with Access-Control-Request-Headers: traceparent); when the API didn't allow the header, all requests failed (Failed to fetch); when it allowed it with Max-Age: 600, requests to three different URLs still caused 3 preflights, while three requests to the same URL caused 1. What are the costs and risks of propagating trace headers from browsers, and how do OpenTelemetry's propagateTraceHeaderCorsUrls and same-origin APIs help?
  3. Correlation IDs without full tracing: a request id generated by the edge or server, returned in a response header (X-Request-Id, exposed via CORS: chapter 19's T7), shown in error UIs ("Reference: 7f3a…") and attached to frontend error reports. How do they connect a user's support ticket to server logs?

T7. Session context and privacy

  1. What session context helps debugging (pseudonymous session and user ids, route, device and network, feature flags, A/B variants, release, kitchen id) and what is personal data under India's DPDP Act and GDPR (IP addresses, precise location, phone numbers, typed text, addresses)?
  2. Session replay tools record DOM changes and interactions to replay a user's session. What are the privacy risks (recording typed phone numbers, addresses, payment fields, OTPs), and how do you configure masking (mask all inputs and text by default, block specific elements, exclude checkout and account pages, honour consent)?
  3. How do you design telemetry under a consent framework: what can run without consent (strictly necessary error monitoring, possibly), what needs consent (analytics, replay), data minimisation, retention limits, and user rights (deletion by user id)?

T8. Release health

  1. Define release health metrics: crash-free sessions (sessions without an unhandled error), crash-free users, error rate per 1,000 sessions, new error groups introduced, adoption (share of sessions on the release), and Web Vitals and conversion by release. Why compare releases at the same adoption stage and time of day?
  2. P6 simulated releases with true crash rates of 0.4% and 0.8% and tested for a difference (pooled two-proportion test, z > 1.96) over 200 simulations: detected 12% of the time with 500 sessions per release, 37% with 2,000, 70% with 5,000 and 100% with 20,000. An earlier single simulation with 500 sessions showed the old release at 100.00% crash-free and called the difference "significant", an artefact of zero counts. What does this mean for canary analysis (chapter 31's P6) and automated rollbacks?
  3. Design automated release gates: what metrics, what thresholds, what minimum sample sizes, how long to wait, and what happens on failure (halt the rollout, page on-call, roll back automatically for severe regressions).

T9. The full picture: browser to database

  1. Walk through one slow checkout using all signals: RUM shows INP 900 ms on "Place order" for Android users on Jio; the error tracker shows no errors; the trace for a sample session shows the browser span 1.2 s, the BFF span 1.1 s, the payments service span 900 ms waiting on a database lock; logs with the trace id show retries. Explain how each signal narrows the search, and what instrumentation made it possible.
  2. What are OpenTelemetry's roles on the frontend (web SDK, instrumentations for document load, fetch, user interactions; exporters via OTLP/HTTP to a collector), and what do vendor SDKs (Sentry, Datadog RUM, New Relic, Grafana Faro) add on top?
  3. How do you keep observability costs and noise under control as the app grows (sampling at the edge of collection, tail-based sampling for traces, aggregating metrics client-side, retention tiers, dropping unused attributes)?

Programming exercises

P1. Group errors so the real bugs stand out

Generate 1,000 error reports from three bugs (simulated: messages containing dish ids, order numbers and status codes; stacks with stable top frames) and compare the number of groups when fingerprinting by raw message, by normalised message and by top in-app stack frame. Then configure your error tracker's fingerprinting rules (or beforeSend) for chunk-load errors, HTTP errors by endpoint and status, and errors from a shared API helper.

P2. Symbolicate a production error

Build an app with hidden source maps, deploy the bundle to a local "CDN" path, throw an error in production code, capture the raw stack via window.onerror, and symbolicate it yourself with the source-map library (SourceMapConsumer.originalPositionFor). Then break symbolication three ways (rebuild after deploy, upload maps under the wrong URL prefix, minify without names) and observe the results.

P3. Trace context across origins

From a page on one origin, call an API on another origin with a traceparent header. Record preflights and failures when the API doesn't allow the header, then when it allows it with Access-Control-Max-Age: 600, for three distinct URLs and for one URL three times. Then configure OpenTelemetry web with propagateTraceHeaderCorsUrls limited to your API, and compare with routing the API through the same origin.

P4. Filter error noise without hiding bugs

Trigger common noise in a test page: a ResizeObserver that resizes its own target, an aborted fetch during navigation, an error from a script loaded without CORS, and an error thrown from a fake extension URL. Record what the global handlers receive and how often. Write filters (allow-listed script origins, known benign messages with owners, sampling for high-volume benign groups) and a weekly report of filtered volumes.

P5. RUM sampling and segments

Using simulated LCP data for 200,000 visits (log-normal), estimate p75 from 0.1%, 1% and 10% samples, 20 times each, and report the spread. Then compute the samples you'd have per day for a segment that's 0.5% of traffic at each rate, given 1 million daily visits, and choose a sampling policy for TiffinBox (with higher rates for checkout).

P6. Release health with enough data

Simulate two releases with crash rates of 0.4% and 0.8% and check how often a two-proportion test detects the difference with 500, 2,000, 5,000 and 20,000 sessions per release (200 simulations each). Then design the canary gate: minimum sessions, minimum expected events, test choice, and automatic actions. Show why a single small run can mislead.

P7. A frontend logger with breadcrumbs

Build a small logger: levels, structured JSON events with release, route template, session id and trace id; an in-memory breadcrumb ring buffer (last 50) attached to error reports; batching and flushing with sendBeacon on visibilitychange; size caps and backoff; PII scrubbing (phone numbers, emails, tokens); and an ingestion endpoint that validates the schema and rate-limits. Test delivery when the user navigates away and closes the tab.

P8. Session replay with privacy

Add a session replay SDK (Sentry Replay, PostHog, or rrweb directly) to the customer app with masking of all text and inputs by default, blocked elements for addresses and order notes, excluded routes (checkout, account, partner payouts), sampling (1% of sessions, 100% of sessions with errors), consent gating and 30-day retention. Record a session where you type a phone number and an address, and verify none of it is visible in the replay or in the network payloads.

P9. One trace from click to database

Instrument the customer app (OpenTelemetry web SDK with fetch and user-interaction instrumentation), the BFF (Node OTel SDK with HTTP and database instrumentation) and one backend service, exporting to a local collector and Jaeger (or Grafana Tempo). Click "My orders", find the trace, and check that the browser span, BFF span, service span and SQL span share a trace id, that logs carry the trace id, and that sampling decisions are consistent.

Cumulative projects (chapters so far: Volume 1, and Volume 2's 00, 12–32)

C1. An observability platform for TiffinBox's frontends

Implement observability for the customer app and partner portal: error tracking with source maps per release (chapter 30's P5), fingerprinting and noise filters (P1, P4), RUM with Web Vitals attribution and segmentation (chapter 27's P9, P5), logs with breadcrumbs (P7), distributed tracing through a same-origin BFF (P3, P9), session replay with privacy (P8), release health dashboards and canary gates (P6, chapter 31's P6), synthetic checks for key journeys, alerting with runbooks, consent handling, and a cost budget. Define SLOs for the customer experience.

Combines: performance metrics (ch 27), security and privacy (ch 28), service workers and offline (ch 29), build and source maps (ch 30), deployment and canaries (ch 31), Volume 1's SLOs and incident response (ch 10) and this chapter.

C2. Observe the kitchen tablets

Kitchen tablets run the partner portal all day, offline at times (chapter 29's C1). Build observability for them: device health (app version, storage usage and persistence, battery, memory), outbox depth and sync latency, SSE connection state durations, push delivery and acknowledgement latency, error tracking that buffers offline and uploads later, and a fleet dashboard showing kitchens with stale versions, growing outboxes or missed alerts. Alert support staff before a kitchen notices a problem.

Combines: PWAs, workers and offline storage (ch 29), real-time transports (ch 19), state machines (ch 25), memory leaks (ch 27), deployment and versions (ch 31) and this chapter.

C3. Investigate "checkout fails for some users" end to end

Support reports that some users can't place orders since yesterday: they tap Pay and nothing happens. Use (or simulate) all signals: RUM (INP and interaction attribution), errors (none? or a group), logs and breadcrumbs, traces, release health, synthetic checks, CDN and server logs. Find the cause (candidates: a CSP change blocking the payment SDK, a chunk not loading on old tabs, a CORS change for traceparent, a third-party script blocked by an ad blocker, a service worker serving an old SDK), fix it, and write the post-incident review with detection gaps.

Combines: CSP and third-party scripts (ch 28), service workers (ch 29), deployment and chunks (ch 31), CORS and trace headers (P3), and this chapter's tools.

What the chapter leaves out

Product analytics versus observability

Product analytics (funnels, retention, feature adoption: Amplitude, Mixpanel, PostHog, GA4) answers "what do users do?", while observability answers "is it working, and why not?". They share collection infrastructure and privacy concerns, and good funnels (P9, C3) are observability's best early-warning signal for broken flows. Keep event naming, consent and PII rules consistent across both, and avoid duplicating SDKs that each add weight to the page.

Mobile apps and WebViews

Native apps and WebViews need their own crash reporting (Crashlytics, Sentry native SDKs), ANR detection, startup time metrics, and symbolication (dSYMs, ProGuard/R8 mappings), and WebView content inside apps needs the web SDK plus bridging context (app version, device) into web events. Release health for mobile is slower (store rollouts, users not updating), making staged rollouts and feature flags even more important. The mobile volume covers it.

Alerting design and on-call for frontends

Frontend alerts are often noisy (third parties, bots, browser updates). Good practice: alert on symptoms tied to SLOs (checkout success, error budgets burning) rather than on every error group; use burn-rate alerts over multiple windows; route by ownership (team tags from code owners); include runbook links and dashboards in alerts; and review alert quality monthly (pages that weren't actionable get fixed or deleted). Volume 1 covers SLOs and on-call in depth.

Security monitoring in the browser

Observability doubles as security monitoring: CSP and Trusted Types violation reports (chapter 28), unexpected third-party domains contacted (a compromised dependency exfiltrating data shows up as new connect-src violations or unknown request hosts), spikes in failed logins or OTP requests from the client side, and integrity checks on payment pages (PCI DSS 4.0's script monitoring requirements). Feed these into the security team's tooling, not just the performance dashboards.

Building your own pipeline versus buying

Teams choose between vendors (Sentry, Datadog, New Relic, Dynatrace), open-source stacks (OpenTelemetry Collector + Grafana Faro/Tempo/Loki/Mimir, SigNoz, Jaeger) and hybrids. Trade-offs: features (symbolication, replay, release health) and ease versus cost at scale, data residency (keeping telemetry in India), and lock-in. OTel-based instrumentation keeps the option to switch backends; SDK-specific features (replay, grouping) are harder to move.

Senior exercises

S1. Design TiffinBox's frontend observability strategy

Write the strategy: goals and SLOs, signals and tools (errors, RUM, logs, traces, replay, synthetic), sampling and cost budget, privacy and consent, ownership (who owns which dashboards and alerts), release integration, and a roadmap for the next two quarters. Justify build vs buy.

S2. Review an observability pull request

A PR adds monitoring: it logs every click with the element's innerText; sends RUM with fetch on unload; fingerprints errors by error.message; attaches localStorage contents and the full URL (with ?phone=…) to every error; adds traceparent to all fetch calls including the payment provider and analytics; samples nothing; and loads the vendor SDK synchronously in <head>. Write the review.

S3. Decide what to alert on

The team has 140 alert rules on frontend errors and gets paged nightly; people ignore alerts. Redesign alerting: classify existing alerts, move to SLO-based burn-rate alerts, define a small set of paging alerts and a larger set of tickets, route by ownership, and measure alert quality.

S4. Make an observability vendor migration safe

The company is moving from one frontend monitoring vendor to another (or to OpenTelemetry + open-source backends). Plan the migration: dual-running, parity checks (event counts, error groups, Web Vitals values), source map pipelines, dashboards and alerts, data retention and history, SDK weight and performance, privacy review, and cut-over.

S5. Teach observability with one incident replayed

Prepare a 20-minute session that replays one incident ("users tap Pay and nothing happens", C3) through each signal in order: RUM funnel, errors (and why they were silent), CSP reports, traces (the request that never left), logs and breadcrumbs. Use this chapter's real outputs where they fit (P1's grouping, P3's preflights, the lab's percentiles and "Script error.") and end with five rules.