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

Workbench / Volume 2 Companion: The Web Frontend

V2·27

Frontend Performance

Companion to Volume 2, chapter 27: how measuring, loading and running connect; new angles (LCP as the main course arriving, INP as how long the waiter takes to acknowledge you, a budget as a kitchen's food-cost percentage); what the chapter simplifies, measured: INP, which reported 40–64 ms for a tap whose result took 42–204 ms to appear; CPU throttling, which isn't a slow device (four times slower made one view 2.1 times slower and turned "no long tasks" into a 170 ms one); and lab noise, where a 43 ms spread means about 70 runs per side to see a 20 ms regression; the theory behind it; how web-vitals estimates INP from the ten longest interactions, and why its live value can stay at 304 ms when the page's real p98 is 200; four debugging drills; interview questions with how to approach each.

6 sections · ~13 min to read
Updated Suggest a correction

Understanding it better

Concept map

Chapter 27 has three strands. Measuring: why performance matters, lab and field data, Core Web Vitals, tools, budgets. Loading: the critical path, JavaScript's cost, code splitting and lazy loading, images and fonts, caching. Running: long tasks and INP, layout shifts, rendering, virtualisation and memory, workers.

measuring loading running why it matters users, money, reach lab and field synthetic vs RUM Core Web Vitals LCP, INP, CLS tools DevTools, Lighthouse, LoAF budgets numbers that gate a change critical path TTFB to LCP JavaScript cost download, parse, run splitting, lazy loading prefetch images, fonts sizes, formats, swap caching, CDN the second visit long tasks, INP input, processing, presentation layout shifts reserve space rendering style, layout, paint virtualisation, memory leaks workers off the main thread measured by summarised as explained by enforced as dominated by reduced by and served via and both in reduced by or goes deeper: ch18 rendering · ch21 UI architecture · ch24 SSR · ch31 deploy and CDN · ch32 RUM exercises: P1–P9 LCP, layout shifts, splitting, tree shaking, virtualisation, workers, LoAF, leak test, RUM
Concept map of chapter 27, frontend performance: measuring it (lab and field data, Core Web Vitals, tools), loading (the critical path, JavaScript cost, splitting and lazy loading, images and fonts) and running (long tasks and INP, layout shifts, rendering, virtualisation, memory and workers), with links such as budgets turning measurements into decisions and the main thread being where loading and running compete.

The links worth remembering:

  • Loading and running share one main thread. A big bundle is evaluated on the thread that handles taps, so loading cost turns into interaction cost on slow devices (stage 22's 100 ms of React start-up, stage 23's Angular bootstrap).
  • Every metric is a model of an experience. LCP models "the main content is here", INP "the page responded", CLS "nothing jumped". Each leaves something out (Gaps 1); budgets on several of them, chosen per screen, are how you cover what matters.
  • A measurement is a sample. Lab numbers vary run to run and depend on the emulation; field numbers vary by user and device. Decisions need repeated measurements and an idea of their noise (Gaps 2–3).

Explain it differently

1. LCP is the main course arriving. Bread on the table (first contentful paint) is nice, but what the diner came for is the main course. LCP times the largest thing on screen, as a stand-in for "the thing you came for".

2. INP is how long the waiter takes to acknowledge you. Raise your hand; INP is the time until the waiter nods. It isn't the time until the food comes (Gaps 1), and it's measured on almost the slowest acknowledgement of your visit, not the average.

3. A long task is a waiter on the phone. Nobody else gets served until the call ends. Breaking work into chunks is hanging up every 50 milliseconds to check the room.

4. Throttling is filming at a slower speed, not hiring a slower cook. Everything the cook does takes longer, but deliveries (the network) and the oven (the GPU) keep their real speed. A slow device is slow in different places (Gaps 2).

5. A budget is a kitchen's food-cost percentage. No single dish is forbidden, but the menu must come in under a number, and every new dish is checked against it before it goes on.

6. Code splitting is a buffet with refills. Put out what most diners eat first; bring the rest when someone asks, and accept the short wait for the rare request.

7. Virtualisation is a restaurant that only lays the tables in view. A hall of 5,000 tables, but only the 30 the guests can see are set; the rest are laid as they come into view.

8. A memory leak is a table never cleared. Each guest leaves something behind; after a long service, there's no room to seat anyone.

Gaps and misconceptions

What the chapter oversimplifies

All outputs are real, from web-vitals 5.1.0, Chromium and the build's stage 27 measurements at 500 open orders (exp/27), unless stated.

1. INP measures the acknowledgement, not the answer. The chapter defines INP as the time from an interaction to the next paint, and treats a good INP as a responsive page. The build measures both, for a tap on "Accept": Event Timing's duration (what INP uses), and the time until the card shows its new status:

Terminal
CPU 4x plain    … | interaction [48, 40, 40, 40, 40] | result on screen [76, 93, 52, 77, 84]
CPU 4x react    … | interaction [64, 88, 112, 48, 48] | result on screen [101, 128, 204, 102, 113]
CPU 4x angular  … | interaction [40, 40, 40, 48, 56] | result on screen [101, 57, 104, 95, 133]

INP sees only the frame after the tap (here the button greying out, aria-disabled). The status change arrives after a network round trip and is painted later, in a frame INP never attributes to the tap. Against a slow or retrying server (stage 19), INP would stay "good" while cooks waited seconds. So the build budgets both: interaction_ms for responsiveness, result_ms for the outcome. A page should acknowledge at once (visible pending state, which INP rewards) and be measured on when the work is really done.

2. A throttled CPU is not a slow device. The chapter recommends CPU throttling to emulate mid-range phones. The same three views at 1×, 4× and 6× slowdown, five runs each:

Terminal
CPU 1x plain    start-up task [0, 0, 0, 0, 0] median 0 sd 0 | all cards [353, 284, 299, 297, 297] median 297
CPU 1x react    start-up task [0, 0, 0, 0, 0] median 0 sd 0 | all cards [316, 311, 336, 374, 331] median 331
CPU 1x angular  start-up task [57, 57, 0, 0, 59] median 57 sd 28 | all cards [320, 313, 309, 301, 326] median 313
CPU 4x plain    start-up task [57, 73, 78, 63, 108] median 73 sd 18 | all cards [642, 634, 532, 701, 575] median 634
CPU 4x react    start-up task [211, 119, 198, 170, 102] median 170 sd 43 | all cards [976, 1039, 876, 758, 887] median 887
CPU 4x angular  start-up task [187, 170, 178, 165, 209] median 178 sd 16 | all cards [751, 790, 865, 801, 905] median 801
CPU 6x plain    start-up task [74, 87, 98, 98, 122] median 98 sd 16 | all cards [953, 943, 937, 919, 819] median 937
CPU 6x react    start-up task [124, 192, 193, 187, 185] median 187 sd 26 | all cards [952, 1249, 1190, 1324, 1184] median 1190
CPU 6x angular  start-up task [272, 257, 257, 231, 208] median 257 sd 23 | all cards [1099, 1061, 1271, 1069, 1015] median 1069

Two things don't scale. Time to all cards went from 297 ms to 634 and 937 (2.1 and 3.2 times, not 4 and 6), because the network, the server and the GPU aren't throttled. And thresholds create cliffs: at full speed React's start-up had no long task at all (all work under 50 ms), and at 4× it had a 170 ms one. A page that looks clean on a developer's laptop can be the opposite on a cheap tablet, and a throttled run is a guess at that, not a measurement of it. Calibrate the throttle against a real target device once (stage 18 chose 4× for the kitchen tablet), measure on the device before decisions that matter, and use field data (chapter 32) as the ground truth.

3. Lab numbers are noisy enough to hide real regressions. The chapter's budgets are single numbers. From the runs above, React's start-up task at 4× has a median of 170 ms and a standard deviation of 43 ms. To detect a 20 ms regression with the usual confidence (5% false alarms, 80% power), a two-sample comparison needs about 2 × (1.96 + 0.84)² × 43² / 20² ≈ 72 runs per side. The build's budgets use the median of three runs, so they catch large regressions (a planted one moved the plain view's start-up task from 73 to 163 ms and failed), not small ones. Options, in increasing cost: budgets with headroom that only catch big steps (the build's choice), many runs on a quiet dedicated machine, measuring work that doesn't vary (bytes, request counts, DOM size, counted operations), or field data with enough users to see small shifts.

Common misconceptions

Misconception What's actually true Where it's shown
"Good INP means a responsive app." INP stopped at 40–64 ms; the result took 42–204 ms. Gaps 1
"4× throttling shows a 4× slower device." One view got 2.1× slower; long tasks appeared from nothing. Gaps 2
"A budget test catches regressions." Only large ones; a 20 ms change needs about 70 runs per side. Gaps 3
"INP is the worst interaction." It's an estimated 98th percentile, from at most ten candidates. Code walkthrough
"No long tasks means no jank." Chunks just under 50 ms still fill frames (stage 23's 44–48 ms passes). Drill D3
"Fallbacks are free." A newly available feature without one cost the whole palette. Drill D4

Theoretical gaps: the ideas behind the chapter

1. Percentiles describe users, means describe servers. Web Vitals use the 75th percentile of page views because a few slow experiences matter more than an average that hides them; INP within a page uses about the 98th percentile of interactions. Tail latency, not mean latency, is what users remember (Volume 3 meets the same idea in services).

2. Amdahl's law for pages. Speeding up one part helps only in proportion to its share: halving the CPU work did less than halving time to all cards, because the network and server share didn't change (Gaps 2). Profile first, then optimise the largest share.

3. Measurement has noise, and comparisons need statistics. A regression test is a hypothesis test; its power depends on effect size, variance and sample size (Gaps 3). Medians resist outliers; bootstrapped confidence intervals say how sure you are.

4. Scheduling theory: latency against throughput. Chunking (yielding every few milliseconds) improves latency for urgent work at a small throughput cost; batching does the opposite. scheduler.yield(), isInputPending (now deprecated) and frameworks' schedulers are policies on that trade.

5. Caching and the second visit. Most performance work targets the first visit; the second is dominated by what's cached (HTTP caching, service workers, bfcache). A budget for the repeat visit is a different number (stage 31).

6. Performance as a feature with a cost model. Every dependency, image and script has a price in bytes, CPU and memory. Budgets make the price visible at review time, the same way a food-cost percentage makes a dish's cost visible before it goes on the menu.

Applying it

Code walkthrough

Chapter Exercises P7 uses the web-vitals library to report INP. The library doesn't take the worst interaction: it keeps a short list and estimates a high percentile. Excerpts from web-vitals 5.1.0, dist/modules/lib/InteractionManager.js and dist/modules/onINP.js, installed from npm.

Keeping the ten longest interactions

JavaScript
const MAX_INTERACTIONS_TO_CONSIDER = 10;
// …
    _estimateP98LongestInteraction() {
        const candidateInteractionIndex = Math.min(this._longestInteractionList.length - 1, Math.floor(getInteractionCountForNavigation() / 50));
        return this._longestInteractionList[candidateInteractionIndex];
    }
    _processEntry(entry) {
        // …
        if (!(entry.interactionId || entry.entryType === 'first-input'))
            return;
        const minLongestInteraction = this._longestInteractionList.at(-1);
        let interaction = this._longestInteractionMap.get(entry.interactionId);
        if (interaction ||
            this._longestInteractionList.length < MAX_INTERACTIONS_TO_CONSIDER ||
            entry.duration > minLongestInteraction._latency) {
            // … update or create the interaction; keep the longest entry's duration as its latency …
            this._longestInteractionList.sort((a, b) => b._latency - a._latency);
            if (this._longestInteractionList.length > MAX_INTERACTIONS_TO_CONSIDER) {
                const removedInteractions = this._longestInteractionList.splice(MAX_INTERACTIONS_TO_CONSIDER);
                // …

One interaction (a tap) produces several event entries (pointerdown, pointerup, click) sharing an interactionId; its latency is the longest of them. The manager keeps only the ten longest interactions. The estimate skips one interaction for every 50 on the page: with fewer than 50, INP is the worst; with 120, it's the third worst. That's the "98th percentile", approximated without storing every interaction.

When it reports

JavaScript
        const handleEntries = (entries) => {
            whenIdleOrHidden(() => {
                for (const entry of entries) {
                    interactionManager._processEntry(entry);
                }
                const inp = interactionManager._estimateP98LongestInteraction();
                if (inp && inp._latency !== metric.value) {
                    metric.value = inp._latency;
                    // …
                    report();
                }
            });
        };
        const po = observe('event', handleEntries, {
            durationThreshold: opts.durationThreshold ?? DEFAULT_DURATION_THRESHOLD,
        });
        // …
            po.observe({ type: 'first-input', buffered: true });
            visibilityWatcher.onHidden(() => {
                handleEntries(po.takeRecords());
                report(true);
            });

The estimate is recomputed only when the observer delivers entries, and it delivers only entries over the duration threshold (40 ms by default), plus the first input whatever its length. The final value is sent when the page is hidden. Fast interactions are counted (in performance.interactionCount) but never enter the list.

Read it yourself

A button whose click handler busy-waits for a set time, and onINP with reportAllChanges. Before running it, predict the values reported for:

  1. 10 clicks, one taking 300 ms and nine 10 ms;
  2. 120 clicks: three slow ones (300, 250, 200 ms) first, then 117 fast ones; and the same with the slow ones last;
  3. 120 clicks, the only slow one (300 ms) last;
  4. 10 clicks of 25 ms each.

Debugging drills

D1. INP is green and cooks say the display is slow

RUM shows the kitchen display's INP at 48 ms, well inside "good". Cooks say that after tapping "Accept" the card "takes ages" to change on the busy evening shift.

D2. The budget test passes on every pull request, and the display got slower

Over three months, the React view's start-up task went from about 100 ms to about 170 ms on the kitchen tablet, though the budget test (median of three runs, limit 200 ms) never failed.

D3. "No long tasks" and the display still stutters while loading

The Angular view's loading profile shows two TimerHandler:setTimeout frames of 44 and 48 ms each, while 500 cards appear. No long tasks are reported, yet scrolling during loading feels uneven.

D4. A browser update later, the kitchen display has no colours

After stage 25 moved colours to light-dark(), a kitchen running an older tablet browser reports a display with transparent backgrounds and black text everywhere.

Career-oriented

Interview prep

Mid level

Q1. What do LCP, INP and CLS each measure, and what does each miss?

How to get there. For each, state the start and end of what it times, then think of an experience that falls outside.

Q2. How would you choose a CPU throttle for lab tests?

How to get there. Calibrate against something real.

Senior level

Q3. Design performance regression testing in CI that teams trust.

How to get there. Trust needs few false alarms and real catches; think about noise.

Q4. Your app uses a feature that's Baseline newly available. Product wants it now. What do you do?

How to get there. Find out who would lose what without it.

Staff level

Q5. Set an organisation-wide performance policy.

How to get there. Cover targets, measurement, enforcement and ownership.

Q6. The business wants to add three third-party scripts (analytics, chat, A/B testing) to the customer pages. How do you decide?

How to get there. Put a price on each and decide how they load.