Diagnosing and Optimizing Full-Stack Web Request Latency

Hard · System Design · Software Engineer · Technical Screen

Prompt

Design a systematic methodology to diagnose, attribute, and reduce the full-stack latency of an interactive web request. Assume the request originates in a user's browser and traverses a CDN edge tier, load balancer and API gateway, multiple backend microservices, in-memory caches, relational or document datastores, and external third-party APIs before the UI finishes rendering.

Walk through a concrete numerical before-and-after scenario to ground your design, and make sure your approach addresses: - Critical-path latency modeling: Break total user-perceived wait time into client/browser, network transport, and server-side stages, distinguishing strictly sequential dependencies from work that executes concurrently. - Full-stack telemetry: Specify what to capture in browser Real User Monitoring (such as DNS/TCP/TLS handshakes, network RTT, Time to First Byte, and main-thread blocking time) alongside server-side telemetry (queue delays, per-service compute, cache hit ratios, datastore query durations, and external API calls). - Cross-tier trace correlation: Show how to join browser measurements with distributed backend traces (using standards like W3C Trace Context and HTTP Server-Timing) and reconcile browser-recorded totals against network, backend, and client-compute segments without clock-skew errors. - Tail-latency outlier diagnosis: Explain how to investigate p50, p95, and p99 gaps by segmenting across region, network type, device tier, endpoint, and software release, and identify typical root causes of tail spikes. - Multi-layer remediation and safe rollout: Propose high-leverage optimizations across browser, CDN/network, service tier, datastore, and third-party integrations, backed by clear SLIs/SLOs, dashboards, alerts, and controlled experiments that protect error rates and throughput.

Scope & Expectations

  • End-to-end model and numeric waterfall: Present an explicit mathematical model separating sequential chains from max(...) parallel branches, illustrated with realistic baseline and post-optimization millisecond budgets.
  • Low-overhead, correlated observability: Detail how RUM beacons, Server-Timing headers, latency histograms, and tail-sampled distributed traces fit together asynchronously without slowing down live user traffic.
  • Tail root-cause isolation and production guardrails: Show how to pinpoint p95/p99 bottlenecks scientifically and ship layered fixes behind canary/A/B experiments and burn-rate SLO alerts without hurting reliability or capacity.

Step-by-step walkthrough

  1. Clarify scope, clocks, and latency targets

    "Make the web request faster" cannot be engineered until we pin down which user journey, measured between which two points, for which users, and at which percentile (a percentile like p99 = 300 ms means 99 out of 100 requests finish in 300 ms or less, while the slowest 1% take longer).

    • Concrete request and architecture. Consider loading the logged-in home screen of a collaborative document web app (www.example.com/home):
      1. The browser loads a cached HTML shell from a CDN (Content Delivery Network: geographically distributed edge servers close to users).
      2. The HTML loads app.js, which boots the frontend and calls GET /api/v1/home.
      3. That dynamic request flows: CDN edge -> load balancer -> API gateway -> BFF (Backend-for-Frontend: a thin server service that aggregates data specifically for one UI screen) -> four microservices (profile, documents, recommendations, entitlements) -> Redis cache, Postgres database, and an external third-party licensing API.
    • Two clocks, both essential:
      • Page journey clock: navigation start -> LCP (Largest Contentful Paint: the moment the main visible content finishes painting on screen).
      • API request clock: fetch() called in JavaScript -> response parsed and handed to the UI callback. Measuring only the backend misses network round trips and browser main-thread stalls, which often dominate what the user actually feels.
    • User mix and topology. Global users with a single origin region in us-east (so European and Asian users pay a cross-ocean edge-to-origin network hop) and 60% mobile traffic.
    • Guardrails. Protect 5xx error budgets and peak request capacity, gate every change behind a feature flag, and cap telemetry CPU overhead below 1% with zero synchronous blocking on user traffic.

    Concrete targets

    • User journey: p75 LCP <= 2.5 s and p75 INP <= 200 ms in every major region (INP, Interaction to Next Paint, measures how long the page takes to visually update after a click or tap; p75 is the standard Core Web Vitals percentile).
    • API request at the load balancer: p99 < 300 ms and p99.9 < 600 ms for GET /api/v1/home, with HTTP 5xx server error rate < 0.1%.
  2. Build the latency model and map the critical path

    End-to-end latency only accumulates along the critical path — the dependency chain of steps where each step cannot start until the step before it finishes.

    Sequential steps (A -> B):     total latency = time(A) + time(B)
    Parallel branches (A || B):    total latency = max(time(A), time(B))
                                   (note: the parallel group inherits the slowest branch's tail!)
    End-to-end journey:            sum across sequential stages of max(parallel branches in each stage)
    

    Every contributor belongs to one of three buckets:

    • Client: redirects, service-worker boot, HTML parsing, JavaScript compilation and execution, main-thread blocking, DOM rendering, and screen paint.
    • Network: DNS lookup, TCP handshake, TLS encryption handshake, RTT (Round-Trip Time: the time for a tiny packet to travel from sender to receiver and back) between user <-> CDN edge and CDN edge <-> origin, bandwidth transfer time, and packet-loss retransmissions.
    • Server: load-balancer and worker-thread queueing, gateway auth/rate-limiting, service business logic, cache lookups, database queries, external API calls, and JSON serialization.

    Baseline waterfall for a p75 mobile user in Frankfurt (user <-> Frankfurt CDN edge RTT = 50 ms, Frankfurt edge <-> us-east origin RTT = 90 ms, downlink bandwidth = 8 Mbps = 1 KB/ms):

     #  Step                                              Bucket    On critical path?   Time (ms)
     1  DNS lookup for www.example.com                    network   yes                        40
     2  TCP 3-way handshake to CDN edge (1 RTT)           network   yes                        50
     3  TLS 1.2 handshake (2 RTTs)                        network   yes                       100
     4  HTML shell (CDN edge hit): wait for first bytes   network   yes                        50
     5  Parse <head>, discover <script src="app.js">      client    yes                        20
     6  Fetch app.js (450 KB compressed = 3,600 kb):      network   yes                       500
        1 RTT (50 ms) + 450 ms transfer at 8 Mbps
     7  Parse, compile, and execute app.js on mobile CPU  client    yes                       700
     8  Connect to api.example.com (DNS 40 + TCP 50       network   yes                       190
        + TLS 1.2 100 on a separate hostname)
     9  API wire round trips: user<->edge (50)            network   yes                       140
        + edge<->us-east origin (90)
    10  Origin server processing (gateway + BFF + 4 svcs) server    yes                       420
    11  Download 12 KB compressed JSON response           network   yes                        20
    12  JS callback wait (10 ms) + render DOM & paint LCP client    yes                       160
        -----------------------------------------------------------------------------------------
        TOTAL JOURNEY (navigation start -> LCP)                                             2,390
        CSS, fonts, icons, analytics beacons              parallel  no (finish during steps 6-7)
    

    Two networking details explain steps 4, 8, and 11:

    • TCP slow start and preload scanning (step 4). A brand-new TCP connection starts with an initial congestion window (initcwnd) of 10 network segments (~14.6 KB, RFC 6928) before waiting for an acknowledgment. Although the full HTML shell is 30 KB, the browser's preload scanner (a fast background tokenizer that scans the first packet of HTML) spots <script src="app.js"> inside the first 14.6 KB and requests app.js immediately, taking the second HTML packet off the critical path. In step 11, the 12 KB compressed JSON fits inside a single 14.6 KB window.
    • Split hostname penalty (step 8). Hosting the API at api.example.com instead of www.example.com/api forces the browser to pay DNS + TCP + TLS a second time (190 ms).

    Inside step 10 (the 420 ms server span on a p75 trace):

    Load balancer + API gateway queueing                  5 ms
    API gateway -> remote auth service token check       25 ms  (sequential)
    BFF -> profile service (Redis cache hit)              5 ms  (sequential)
    BFF -> documents service (1 list SQL + 20 per-doc)  140 ms  (sequential <- N+1 query bug!)
    BFF -> recommendations service                      110 ms  (sequential)
    BFF -> entitlements service (third-party HTTP API)  120 ms  (sequential)
    BFF: merge payloads + serialize JSON                 15 ms
                                                        ------
    Total origin server processing                      420 ms
    

    Three immediate lessons jump out before touching a single line of code:

    1. Sequential chains dominate. The browser waits to finish downloading and running 450 KB of app.js before even starting GET /api/v1/home, and the BFF calls four independent backend services one after another instead of concurrently.
    2. The backend is only 18% of the p75 user wait. Network (1,090 ms, 46%) + client compute (880 ms, 37%) account for 82% of the 2,390 ms load.
    3. Percentiles do not add. The p75 of A + B is not p75(A) + p75(B). The waterfall table is an illustrative model; true attribution requires recording all segments of each individual request and aggregating per-request totals.
  3. Size the telemetry pipeline (back-of-the-envelope)

    Before designing instrumentation, calculate data volume so observability does not cost more than the application itself:

    Traffic          20M page views/day -> ~230/s average, ~700/s at 3x peak
                     ~10 API calls/page view -> 200M API calls/day (~2,300/s avg, ~7,000/s peak)
    
    Client RUM       1 compressed beacon/page view x ~3 KB = 60 GB/day
                     -> Cheap enough to keep 100% (never drop rare devices or small countries).
    
    Server traces    200M API calls x ~15 spans/trace x ~500 B/span = 1.5 TB/day raw.
                     Use tail sampling: keep 100% of errors (~0.5%) + 100% of traces slower
                     than the route's p99 threshold (~1%) + 1% random baseline = ~2.5% kept
                     -> ~38 GB/day stored.
                     In-memory collector wait buffer (30 s window at 7,000 req/s peak):
                     7,000 x 30 s x 15 spans x 500 B ~ 1.6 GB RAM total across collector pods.
    
    Metrics          Histogram buckets per (service, route, status_class, region, deploy_version):
                     30 x 20 x 3 x 4 x 2 = 14,400 label sets x 30 buckets ~ 432,000 time series.
                     NEVER put user_id, trace_id, or raw URL in metric labels (unbounded cardinality,
                     meaning millions of unique label values that crash time-series databases).
    
    Sample floor     At p99, only 1 in 100 requests sits in the tail, so a slice needs >= 1,000
                     requests (~10 tail events) before a dashboard displays p99.
    

    Why tail sampling beats head sampling: head sampling flips a 1% coin when a request arrives, throwing away 99% of slow outliers and rare errors. Tail sampling buffers spans for a few seconds until the request finishes, keeping every single slow or broken trace while discarding 99% of routine fast ones.

  4. Instrument both the browser (RUM) and the backend

    1. Client instrumentation with RUM (Real User Monitoring: an asynchronous < 10 KB browser script that reads standard W3C performance APIs on real user sessions):

    Metric                      Browser source / formula
    Redirects                   redirectEnd - redirectStart                 (Navigation Timing)
    Service worker startup      fetchStart - workerStart                    (Navigation / Resource Timing)
    DNS lookup                  domainLookupEnd - domainLookupStart
    TCP handshake (~1 RTT)      secureConnectionStart - connectStart        (on fresh TCP connections)
    TLS handshake               connectEnd - secureConnectionStart
    Document TTFB               responseStart - activationStart             (Time to First Byte of HTML)
    API wait to first byte      responseStart - requestStart                (Resource Timing)
    Response download           responseEnd - responseStart
    LCP, INP, CLS               PerformanceObserver ('largest-contentful-paint', 'event', 'layout-shift';
                                CLS = Cumulative Layout Shift, visual jumping during load)
    Main-thread blocking        PerformanceObserver ('longtask'): sum of max(0, task_duration - 50 ms)
                                before LCP (field equivalent of lab Total Blocking Time, TBT)
    Callback delay              custom fetch() wrapper: handler_run_ts - entry.responseEnd
    Server breakdowns           entry.serverTiming (requires Timing-Allow-Origin header if cross-origin)
    Protocol & browser cache    nextHopProtocol ('h2', 'h3'), transferSize (0 = served from disk cache)
    
    • Why track callback_delay? When the browser finishes downloading JSON (responseEnd) while the main thread is busy running heavy JavaScript, the promise .then() callback waits in the task queue. Without callback_delay, neither network logs nor server traces explain the gap.
    • Preventing survivorship bias. Users on slow connections often close the tab before LCP fires. Sending the beacon via navigator.sendBeacon() on the visibilitychange event records partial/abandoned loads (abandoned: true) instead of silently dropping your worst experiences.

    2. Server instrumentation (OpenTelemetry + Server-Timing + Histograms):

    • Distributed traces (OpenTelemetry). Propagate the W3C traceparent header across HTTP, gRPC, and async queues so every hop records a timed span (one unit of work with start time, duration, and parent span ID). Tag spans with http.route template, cache hit=true|false, DB connection-pool wait time, SQL statement fingerprint, row count, external peer.service, retry attempt, and business cardinality hints like app.doc_count.
    • Queueing time. Have the load balancer stamp an arrival header (X-Request-Start), so the gateway records handler_start - lb_arrival (clamped at 0; both hosts sit in one NTP-synced data center), plus thread-pool / event-loop queue wait inside each service.
    • Histograms with exemplars. Emit latency histograms alongside saturation metrics (CPU throttling, garbage-collection pause duration, DB pool wait, in-flight requests). Attach exemplars — sample trace_id links pinned to histogram buckets — so clicking a p99 spike jumps straight to an actual slow trace.
    • Coarse Server-Timing response header (exposes aggregate durations to RUM without leaking internal microservice names in public browser DevTools):
    Server-Timing: edge;dur=3, cache;desc="MISS", edge_origin;dur=505
    Server-Timing: origin;dur=420, db;dur=140, ext;dur=120,
                   traceparent;desc="00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01"
    

    At ingest, a stream processor flattens each sampled trace into a single row in a columnar analytics table request_facts(day, trace_id, route, release, region, total_us, queue_us, critical_path, slowest_span, retries, cache_misses, doc_count) so slicing millions of traces takes seconds instead of recursive graph joins.

  5. High-level architecture: request path vs. telemetry path

                           SYNCHRONOUS REQUEST PATH                         ASYNC TELEMETRY PATH
     Browser + RUM SDK ---------------------------------------------------> CDN RUM Beacon Endpoint
       |  GET /api/v1/home (carries traceparent if same-origin)  sendBeacon          |
       v                                                                             |
     CDN Edge (records edge & edge_origin in Server-Timing)                          |
       |  warm keep-alive pool                                                       |
       v                                                                             |
     Load Balancer (stamps arrival timestamp)                                        |
       v                                                                             |
     API Gateway ---> Auth Service                                                   |
       v                                                                             |
     BFF ---+---> Profile Svc ----------> Redis                                      |
            +---> Documents Svc --------> Postgres (primary + read replicas)         |
            +---> Recommendations Svc --> Redis                                      |
            +---> Entitlements Svc -----> Third-Party Licensing API                  |
       (every service: non-blocking OTel SDK -> local node agent)                    |
                          |                                                          |
                          v                                                          v
            OTel Collector Fleet (hash-routed by trace_id)            Kafka -> Columnar Store
              +--> Tail Sampler --> Trace Store                                (rum_pageviews,
              +--> Histograms + Exemplars --> Time-Series DB                    request_facts)
                                \                                                  /
                                 +-----> Unified Dashboards & SLO Alerts <--------+
    

    Two isolation rules keep instrumentation safe:

    1. Telemetry never blocks user traffic. Service SDKs write to bounded in-memory ring buffers; if collectors back up, SDKs drop spans and increment a dropped_spans counter rather than stalling requests.
    2. Hash routing for tail sampling. Node agents route spans by hash(trace_id) so all 15 spans of a single request land on the same collector instance, letting it judge total trace duration and error status before storing.
  6. Deep dive 1: correlate RUM with backend traces and reconcile durations

    Linking browser and backend with trace_id without adding latency:

    • Same-origin calls (www.example.com/api/*): The RUM fetch wrapper generates a W3C traceparent header and sends it with the request.
    • Cross-origin calls (api.example.com): traceparent is not a CORS-safelisted header, so sending it cross-origin forces the browser to send a CORS preflight (an extra OPTIONS network round trip asking the server for permission before sending the real request). Instrumentation would literally slow down the app! For cross-origin endpoints, let the backend generate trace_id and return it inside Server-Timing (made readable to JS via the Timing-Allow-Origin response header), adding zero extra round trips.

    Reconciling client vs. server time using same-clock durations:

    Never subtract a server timestamp from a browser timestamp — phone clocks regularly drift by seconds. Instead, every term below is a duration measured on one machine's monotonic clock, so subtracting nested durations is immune to clock skew:

    App fetch wrapper total                  = 780 ms  (measured in JS from fetch() -> callback run)
    Resource Timing duration                 = 770 ms  (DNS 40 + connect 150 + req_to_first_byte 560 + download 20)
    Callback delay                           =  10 ms  (handler waited 10 ms on main thread)
    Server-Timing headers                    = edge: 3 ms, edge_origin: 505 ms, origin: 420 ms
    
    1. Client residual    = 780 - (770 + 10) =   0 ms  (if large: check CORS preflights or JS retry wrappers)
    2. User<->edge net    = 560 - 505 - 3    =  52 ms  (cross-check vs TCP handshake 50 ms: +2 ms match!)
    3. Edge<->origin net  = 505 - 420        =  85 ms  (cross-check vs CDN logged origin RTT 90 ms: -5 ms noise)
    4. Origin server      = 420 ms                     (matches root span in OpenTelemetry trace)
    

    Notice step 2: if you merely define network = total - server, the math always adds up by tautology even when something is broken. Cross-checking the derived 52 ms against the independently measured 50 ms TCP handshake on that connection proves no hidden queueing or packet-retransmit stall went unaccounted for.

  7. Deep dive 2: investigate p50, p95, and p99 tail outliers

    While /api/v1/home takes 420 ms at p75, suppose its server p99 is 2,600 ms. Hunt tail outliers systematically:

    1. Inspect the full latency histogram, not single percentile lines.

    • Bimodal (two humps): You are mixing two distinct populations (e.g., cache hits at 15 ms vs. cache misses at 300 ms, or small accounts vs. enterprise accounts).
    • Sharp vertical spikes at round constants: A fixed timeout or OS retransmission timer is firing:
      • ~200 ms: Linux minimum TCP retransmission timeout (RTO_MIN).
      • ~1,000 ms and ~3,000 ms: lost TCP SYN packet retransmissions (1 s initial timeout, doubling on backoff).
      • ~5,000 ms: default Linux DNS resolver timeout (resolv.conf).
      • Exact spike at 1,000 ms on an external span: your own HTTP client timeout + retry firing.

    2. Slice dimensions and rank by lift. Define a "slow" request as exceeding our 600 ms p99.9 cap, and compute lift = (share of all slow requests in slice) / (share of all traffic in slice):

    Slice on GET /api/v1/home              Traffic share   Share of slow (>600 ms)    Lift
    app.doc_count > 200                             3.0%                     41.0%    13.7x  <- huge culprit
    entitlements_retried = true                     1.0%                     22.0%    22.0x  <- huge culprit
    recommendations cache = MISS                   15.0%                     25.0%     1.7x
    deploy web-2026.11.3 vs .2                     50.0%                     51.0%     1.0x  (not a deploy bug)
    

    Run the same lift ranking on client RUM across (country, ASN/carrier, effective_connection_type, device_memory, browser, deploy_version) — client p99 tails usually cluster on low-RAM budget phones (JS execution + GC) and high-loss cellular networks.

    3. Diff slow (p99) vs. fast (p50) traces span by span.

    • Culprit 1 — N+1 database queries on large accounts: documents runs 1 query to list IDs and 1 query per document for metadata (N+1 query problem). A power user with 500 documents triggers 501 sequential 5 ms queries = 2,505 ms!
    • Culprit 2 — Unbounded third-party wait: entitlements uses a 1,000 ms timeout plus 1 synchronous retry, turning vendor hiccups into 1,000–2,000 ms stalls.

    4. Check structural tail-latency amplifiers:

    Tail bottleneck               Diagnostic signature in metrics & traces
    Queueing near saturation      Latency curves steeply upward above ~75% utilization; in an M/M/1 queue,
                                  mean wait = S / (1 - rho), jumping from 2x service time at 50% busy
                                  to 5x at 80% busy and 10x at 90% busy.
    DB connection-pool starvation Pool-wait child span balloons while actual SQL execution stays 3 ms.
    GC pauses / CPU CFS throttle  All spans on one pod stall simultaneously during a container throttle window.
    Fan-out tail amplification    Waiting on N parallel calls that each have a 1% p99 spike produces a slow
                                  parent 1 - 0.99^N of the time (3.9% for N=4; 63.4% for N=100).
    Cache stampede                Synchronized TTL expiry sends 500 identical cold queries to Postgres at once.
    
  8. Optimize every layer and recalculate the waterfall

    Target the critical path and the two p99 culprits across every tier:

    • Browser & UI runtime
      • Break the JS -> API waterfall: Put a tiny <script> inline in <head> that fires window.__homePromise = fetch('/api/v1/home') immediately, before app.js even downloads. Now app.js and the API call run in parallel (max(JS, API) instead of JS + API).
      • Route-based code splitting & tree shaking: Trim /home JS bundle from 450 KB -> 200 KB compressed (200 ms transfer + 50 ms RTT = 250 ms; mobile parse/exec drops 700 -> 300 ms).
      • Yield long tasks: Break startup work into < 50 ms chunks so callback_delay drops from 10 -> 2 ms and INP stays < 200 ms.
    • Network / CDN
      • Unify onto one hostname (www.example.com/api/*): Route /api/* at the CDN so the browser reuses the already-open HTTP/2 or HTTP/3 connection, eliminating the second DNS + TCP + TLS (-190 ms).
      • Enable TLS 1.3 and HTTP/3 (QUIC): TLS 1.3 cuts the handshake from 2 RTTs to 1 RTT (100 -> 50 ms), and HTTP/3 eliminates TCP head-of-line blocking on lossy mobile links.
      • Keep <head> discovery inside the first 14 KB (initcwnd): Ensures both app.js and the early fetch start after the very first HTML round trip, while keeping warm edge-to-origin keep-alive pools.
    • Application / microservices
      • Local JWT verification at the API gateway: Verify token signatures in-memory using cached public keys (JWKS) instead of calling the auth service on every request (25 -> 1 ms).
      • Parallel fan-out in the BFF with deadlines: Dispatch profile, documents, recommendations, and entitlements concurrently (sum -> max), propagate remaining request deadlines, and treat recommendations as optional (render home without it if it misses a 100 ms budget).
    • Datastore
      • Eliminate N+1 and paginate: Fetch only the first 20 documents using a composite B-tree index on (owner_id, updated_at DESC) LIMIT 20, followed by one batched WHERE doc_id IN (...) query (140 -> 30 ms, and latency stays flat whether a user owns 20 or 50,000 documents!).
      • Precompute recommendations in Redis: Serve precomputed lists in 8 ms (85% hit rate); on cache miss, return "recently opened" immediately and trigger async background refresh.
    • Third-party service
      • Per-user Redis cache (5-min TTL) with stale-while-revalidate: Serve cached entitlements in 2 ms while refreshing expiring entries asynchronously in the background. On a cold cache miss, enforce a 200 ms timeout with no synchronous retry (falling back to last-known/basic tier for UI badges, while enforcing paid actions authoritatively when executed). Keeping this cap at 200 ms ensures even a cold third-party timeout fits inside our 300 ms server p99 budget.

    Recalculated p75 waterfall after optimizations:

     1  DNS lookup (www.example.com)                                            40 ms
     2  TCP handshake (1 RTT)                                                   50 ms
     3  TLS 1.3 handshake (1 RTT, down from 100 ms)                             50 ms
     4  HTML shell first bytes (1 RTT, CDN edge hit)                            50 ms
     5  Parse <head>; kick off BOTH app.js and fetch('/api/v1/home')            20 ms
        Parallel stage (reusing the same connection):
          Branch A (JS):  1 RTT (50) + 200 KB transfer (200) + execute (300) = 550 ms
          Branch B (API): user<->edge (50) + edge<->origin (90)
                          + origin 51 ms [5 queue + 1 JWT + max(5, 30, 8, 2) + 15 JSON]
                          + 12 KB JSON download (20)                         = 211 ms
        Parallel stage critical path = max(550, 211) + ~15 ms shared link     ~565 ms
    12  Callback wait (2 ms) + render DOM & paint LCP (150 ms)                 152 ms
        -----------------------------------------------------------------------------
        OPTIMIZED JOURNEY p75                                                 ~927 ms
        (Down from 2,390 ms -> 61% faster! Origin server p99: 2,600 ms -> ~240 ms)
    

    Notice a crucial non-linear insight: once parallelization drops Branch B (211 ms) well below Branch A (550 ms), shaving another 20 ms off Postgres saves 0 ms on p75 LCP because JS is now the bottleneck! Backend fixes still dramatically improve server p99 (2,600 -> ~240 ms) and server capacity.

  9. SLIs, SLOs, alerts, safe rollout, and measurement traps

    1. SLIs, SLOs, and multi-window burn-rate alerts

    An SLI (Service Level Indicator) is the exact good-event ratio we measure; an SLO (Service Level Objective) is the target threshold over a rolling window; the remaining gap (e.g., 1% for a 99% SLO) is the error budget.

    SLI definition                                       28-day SLO     Measured at
    GET /api/v1/home latency < 300 ms                    99.0%          Load balancer
    GET /api/v1/home latency < 600 ms                    99.9%          Load balancer
    GET /api/v1/home status != 5xx                       99.9%          Load balancer
    Journey LCP per region & device tier                 p75 <= 2.5 s   RUM (daily gate)
    Journey INP per region & device tier                 p75 <= 200 ms  RUM (daily gate)
    

    Alert on burn rate (how fast the error budget is being consumed compared to a steady 1x pace over 28 days) using paired long + short windows so blips don't page and resolved incidents clear quickly:

    • Page on-call: burn rate > 14.4x over both 1 hour and 5 minutes (consumes 2% of the monthly budget in 1 hour).
    • Page on-call: burn rate > 6x over both 6 hours and 30 minutes (consumes 5% in 6 hours).
    • Create ticket: burn rate > 1x over 3 days.

    2. Dashboards and safe experimentation

    • Five core dashboards: (1) Stacked RUM waterfall by region/device/release, (2) Per-service RED metrics (Rate, Errors, Duration heatmaps) + CPU/GC/pool saturation, (3) Critical-path span share from request_facts, (4) Canary vs. baseline histogram diff, (5) Cache hit rates, DB replica lag, and third-party latency.
    • Controlled rollout with guardrails: Ship backend changes via staged canary (1% -> 5% -> 25% -> 100%) and frontend changes via randomized user A/B tests (using bootstrap confidence intervals on p75 LCP). Auto-rollback if 5xx rises by > 0.05 percentage points, CPU/request rises > 5%, or a 1% shadow comparison between cached and live entitlements shows > 0.01% mismatch.
    • Throughput & resilience protections:
      • Replay 2x peak traffic using an open-loop load generator (sends requests at a fixed arrival schedule regardless of server slowdowns; closed-loop generators wait before sending the next request, hiding tail spikes via coordinated omission). Size DB connection pools for the burstier concurrency of parallel BFF fan-out.
      • Enforce nested timeouts (callee timeout < caller's remaining deadline), retry budgets (cap retries at <= 10% extra traffic to prevent retry storms), circuit breakers on third-party APIs, and hedged requests only on idempotent reads (send a backup read if the first exceeds p95, duplicating <= 5% of calls).
      • Never average percentiles across hosts (always merge histograms), and filter prerendered/back-forward-cached loads into separate RUM cohorts so clean averages don't mask real regressions.

Intuition & how it works

Think of loading a web page like ordering breakfast at a drive-thru where a relay team prepares your meal. Your total wait is not the sum of every worker's effort in the kitchen — it is only the chain of tasks waiting one behind another, called the critical path (the longest sequence of dependent steps from start to finish). If you spend 4 minutes waiting in the car line outside just to reach the speaker, and another 3 minutes waiting because the cashier won't start brewing coffee until the toast pops up, shaving 10 seconds off the egg grill inside barely changes when you eat.

The naive approach to latency optimization fails in three predictable ways: teams measure only their own backend server (missing the 70–85% of time spent in DNS, TLS handshakes, and browser JavaScript), average p99 numbers across servers (p99 is the latency threshold that 99% of requests beat, and averaging percentiles mathematically distorts spikes), or micro-optimize steps that run in parallel with something slower. Worse, looking only at median latency hides distinct tail populations — such as the 1% of enterprise users with 500 documents triggering 500 sequential database queries.

Walk through a concrete mobile load of /home from Frankfurt (50 ms round trip to the local CDN edge server, 90 ms from the edge to the us-east origin server, 8 Mbps link):

  1. Baseline (2,390 ms total): Opening the connection and fetching HTML takes 240 ms. Downloading and executing 450 KB of app.js takes 1,220 ms. Only after app.js finishes does it connect to api.example.com (190 ms), wait on four sequential backend calls (140 ms network + 420 ms server + 20 ms download = 580 ms), and render (160 ms).
  2. Correlated measurement: A shared trace_id (via W3C traceparent and the Server-Timing HTTP response header) joins the browser's RUM beacon (Real User Monitoring: timings captured inside real user browsers) with the backend OpenTelemetry trace (a tree of timed service hops), verifying 1,090 ms network + 880 ms client compute + 420 ms server with zero clock-skew guesswork.
  3. Layered fix (~927 ms p75, 2,600 ms -> ~240 ms server p99): Moving the API onto www.example.com/api, upgrading to TLS 1.3, firing fetch('/api/v1/home') from an inline <head> script in parallel with a trimmed 200 KB app.js, fanning out the four backend calls concurrently, and replacing a 500-query N+1 database loop with a single indexed LIMIT 20 query cuts the user's wait by 61% and crushes the 2.6-second server tail.

Key trade-offs

  • Server load-balancer metrics vs. browser RUM for SLOs. Load-balancer metrics are complete, noise-free, and available within seconds, making them ideal for automated paging SLOs (Service Level Objectives: formal reliability targets like 99% of requests under 300 ms), yet they miss the 82% of time spent on client networks and CPUs. Browser RUM sees the user's true wait, but arrives late (on tab hide), includes noisy cellular dropouts, and lacks uniform browser API support; use server SLIs to page on-call engineers and RUM to gate releases and guide roadmap priorities.
  • Head sampling vs. tail sampling of distributed traces. Head sampling (deciding whether to record a trace at a 1% random rate when the request arrives) is stateless and cheap, but discards 99% of slow outliers and rare failures right when you need to debug a p99 regression in one country. Tail sampling (buffering spans in collector memory for ~30 seconds until the trace completes) keeps 100% of errors and >p99 slow traces (~38 GB/day instead of 1.5 TB/day), trading ~1.6 GB of stateful collector RAM and trace-ID hash routing for complete tail visibility.
  • Client traceparent header vs. Server-Timing trace correlation. Generating traceparent in the browser works seamlessly on same-origin requests, but on cross-origin requests it triggers a CORS preflight (an extra OPTIONS permission round trip before the real call) that actively slows down users. Returning trace_id inside the Server-Timing response header avoids preflights completely, at the minor cost that requests failing before reaching the CDN/origin have no server trace ID.
  • Coarse vs. granular Server-Timing headers. Putting every internal microservice name and SQL timing into Server-Timing simplifies client-side debugging, but leaks internal architecture and timing side channels to anyone opening browser DevTools. Publishing only coarse buckets (edge, edge_origin, origin, db, ext) plus trace_id enables exact per-request network/server reconciliation while keeping internal service details safely inside the backend trace store.
  • Parallel backend fan-out vs. burst concurrency. Switching four sequential backend calls to run concurrently turns sum(latencies) into max(latencies), slashing server latency from 420 ms to 51 ms. In exchange, the BFF fires the same four downstream calls in a 4x tighter burst, requiring larger connection pools, per-branch deadlines, and graceful degradation when non-critical branches like recommendations time out.
  • Stale-while-revalidate caching vs. strict data freshness. Serving cached third-party entitlements in 2 ms (while refreshing asynchronously in the background) removes a 120 ms external dependency and shields users from vendor outages, at the cost of up to 5 minutes of stale UI badge state — acceptable only because the backend re-verifies entitlements authoritatively when a user actually executes a paid action.
  • Early-fetch SPA vs. Server-Side Rendering (SSR). Triggering fetch('/api/v1/home') from <head> eliminates the JS-then-API waterfall while keeping HTML cacheable at the CDN edge. Full SSR lets low-end phones paint pixels before running JavaScript, but makes HTML personalized and uncacheable at the edge, adding origin round-trip and server compute time back into TTFB (Time to First Byte).

Common mistakes

  • Measuring only backend latency and spending months shaving 50 ms off a microservice when 80%+ of user wait time sits in JS bundles, split-domain handshakes, and sequential browser waterfalls.
  • Summing segment percentiles or averaging host p99s. Percentiles are non-additive (p99(A) + p99(B) != p99(A + B)), and averaging p99 across 20 pods hides a single broken pod; always sum durations per individual request and merge raw latency histograms (bucketed request counts).
  • Subtracting browser and server wall-clock timestamps to compute network transit time; user device clocks regularly drift by hundreds of milliseconds or seconds, producing negative or bogus network numbers instead of subtracting single-clock durations.
  • Treating network = total - server as self-proving reconciliation without cross-checking that remainder against an independent RTT signal like the TCP handshake (secureConnectionStart - connectStart).
  • Ignoring survivorship bias in RUM by sending beacons only after onload, silently dropping the slowest mobile users who abandon the tab mid-load instead of flushing partial beacons on visibilitychange.
  • Staring at smooth percentile trend lines instead of histograms, missing bimodal humps (cache hit vs. miss) or sharp timer spikes at 200 ms (TCP retransmit), 1 s (SYN retry / client timeout), or 5 s (DNS timeout).
  • Continuing to optimize a branch after it leaves the critical path — once API (211 ms) finishes well inside app.js (550 ms), faster SQL saves zero milliseconds on p75 page paint until app.js shrinks.
  • Load-testing with closed-loop virtual users that wait for each slow response before sending the next request (coordinated omission), making tail latency look artificially healthy under load.

Follow-up questions

  • Suppose p99 latency jumps right after a deploy, but only in one geographic region. How would you isolate the root cause within 15 minutes? First, check the release-comparison dashboard filtered to that region: if both the old and new release pods spiked together, suspect shared regional infrastructure (a degraded database replica, network link, or third-party regional endpoint); if only the new release shifted, suspect code or region-specific config. Next, click an exemplar (a sample trace_id attached to the slow p99 histogram bucket) and diff its span tree against a fast p50 trace to spot which exact span grew — common culprits are cold per-pod caches after restart, a misconfigured regional connection-pool size, or a new cross-region call accidentally pointing back to us-east. If the multi-window burn-rate alert is paging, roll back the regional deploy immediately via feature flag or canary revert first, then debug safely offline.
  • When would you choose Server-Side Rendering (SSR) or streaming HTML over the early-fetch Single-Page App (SPA) optimization? Compare both on the exact critical-path waterfall for your dominant user devices. With SSR, the browser can render visible HTML before downloading and executing app.js (removing the 550 ms JS branch from LCP), which is a major win on budget Android phones where CPU execution takes 700+ ms. However, personalized SSR HTML can no longer be served instantaneously from the CDN edge cache, adding the 90 ms edge-to-origin round trip and 51 ms server compute directly onto HTML TTFB (unless you use HTTP streaming to flush the static <head> shell immediately while awaiting data). Validate the choice with a randomized A/B test measuring p75 LCP and INP alongside origin CPU cost.
  • How do you prevent end-to-end latency from quietly regressing over the next 12 months as dozens of engineers ship features? Automate the latency model into CI/CD gates rather than relying on manual vigilance. Enforce a build-time bundle-size budget per route (blocking PRs that push /home JS past 200 KB compressed) and a static/integration check ensuring zero new sequential round trips are added before LCP. Gate production rollouts with automated canary histogram comparisons that halt promotion if p75 or p99 shifts beyond historical variance, and require every new backend service call in design reviews to declare its timeout, fallback behavior, and whether it sits on the critical path.

Follow-up questions

Similar questions

More Adobe interview questions

All 29 Adobe questions →