Debugging Web Performance / Module 08

Module 8: Memory in Long Sessions

Find what a page keeps alive over a 30-minute session, with counters, heap snapshots and retainers, and clean up listeners, timers and hidden tabs.

On Saturday at 9:31, Leo opened the waiting page for the second night of Midsummer Lights on his phone. He wanted to see the sale as a buyer sees it. By 9:50 the phone felt warm in his hand.

At 9:56 he switched to his messages for a minute. When he came back, the page was loading again from the start.

“It said ‘Finding your place in line’ again,” Leo wrote. “Did I lose my place?”

“No, the server keeps your place,” Maya wrote back. “But your phone threw the page away while you were gone. I want to know what the page was holding.”

Maya, Leo and TinyTickets are invented, and so are the numbers in their story.

This module is about memory in a page that stays open for a long time. Most tools measure a page in its first seconds, but the waiting page lives for 30 minutes, and every few seconds it adds a little. You’ll find what it keeps, why the browser can’t free it, and what that costs a phone. Then you’ll clean it up and measure memory from real buyers.

After this module, you can:

  • watch a page’s memory over a long session with the Performance monitor, and tell a leak from normal garbage collection
  • find what keeps a removed element alive with a heap snapshot, its Detached filter and the Retainers pane
  • remove listeners and stop timers with one AbortController, and say when a bounded cache, a WeakMap or a WeakRef fits
  • stop a page’s work while its tab is hidden, and say what a phone may do to a hidden tab
  • measure a page’s memory in the field with performance.measureUserAgentSpecificMemory(), and name its limits

What buyers saw in the last minutes before 10:00

The second night of Midsummer Lights, June 21, went on sale on Saturday at 10:00. For this sale, Omar had added a table of the stadium’s 120 sections and their prices to the waiting page. Buyers could pick a section before the sale opened. The page asks the server for the buyer’s place every 5 seconds.

On Monday, Leo forwarded 14 messages from buyers. Most said the same two things: the phone got slow or warm, and shortly before 10:00 the page reloaded.

Maya’s endpoint had the waiting page’s lines from phones. Each line carries the navigation type that Module 4 added.

Between 9:30 and 9:45, 1.2% of the page’s loads were reload or restore. Between 9:45 and 10:00, 9.6% were. web-vitals uses restore, a value Module 4 didn’t need, for a page that the browser discarded and loaded again. On desktops it was 0.7% for the whole half hour.

The INP lines didn’t explain it. web-vitals reports when the slowest interaction happened, so Maya split the lines by minutes since the page opened. Taps in the first 10 minutes had an INP of 110 ms at the 75th percentile, over 980 lines. Taps after the 20th minute had 130 ms, over 1,460 lines. So whatever ended the tabs didn’t make taps much slower.

Nothing in the first minute of the page looked wrong. CrUX and Lighthouse look at a page load, so neither could show a page that gets worse with time.

Pause and predict. The page replaces one card every 5 seconds. Suppose each old card stays in memory. In the Performance monitor, which line grows fastest over 30 minutes: the JavaScript heap, the number of DOM nodes, or the number of event listeners? Write down a guess.

Reproduce a 30-minute session in the lab

The lab app is Module 7’s, with a waiting page added as Omar shipped it. The finished code for this module is in the course repository, folder module-08/.

The waiting page as it was on sale day

The production server knows each buyer’s place. But the lab server fakes it: this buyer is always number 1,204, a few more buyers join before every answer, and every section of the stadium is on sale. In server.js, add above const app:

// A fake queue for the waiting page. This buyer is always number 1,204 in line, a few more
// buyers join before every answer, and the stadium's 120 sections of 500 seats are all on sale.
let waiting = 41000;
const sections = Array.from({ length: 120 }, (_, i) => ({
  name: `${['North', 'East', 'South', 'West'][i % 4]} ${Math.floor(i / 4) + 1}`,
  price: i < 40 ? 95 : 60,
  seats: 500,
}));
function queueStatus(res) {
  waiting += 3 + (waiting % 7);
  res.writeHead(200, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' });
  res.end(JSON.stringify({ place: 1204, waiting, sections }));
}

In the first createServer call, above return serveFile(req, res, app);:

  if (req.url === '/api/queue') return queueStatus(res);

Create public/waiting.html:

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Waiting room - TinyTickets</title>
  <link rel="stylesheet" href="/styles.css">
  <script type="module" src="/assets/waiting.js"></script>
</head>
<body>
  <header>TinyTickets</header>
  <main>
    <h1>Midsummer Lights, June 21</h1>
    <div id="queue">Finding your place in line...</div>
    <p><a id="seats" href="/seats.html" hidden>Pick your seats</a></p>
  </main>
</body>
</html>

Add 'waiting' to the pages list in build.js, so the bundler writes the page’s script and its modulepreload link. Add two lines for the table at the end of public/styles.css:

table { border-collapse: collapse; }
td, th { padding: 2px 12px 2px 0; text-align: left; }

Then create src/waiting.js, the script as Omar wrote it:

import './vitals.js';
import './load-analytics.js';

// The lab's sale opens 30 minutes after the page loads, as for a buyer who arrives at 9:30.
// ?speed=10 runs the clock and every timer ten times faster: 30 minutes in 3.
const speed = Number(new URLSearchParams(location.search).get('speed')) || 1;
const opensAt = performance.now() + (30 * 60 * 1000) / speed;
const box = document.getElementById('queue');
const seatsLink = document.getElementById('seats');

// Minutes and seconds until the sale opens, such as 29:58.
function timeLeft() {
  const s = Math.max(0, Math.ceil(((opensAt - performance.now()) * speed) / 1000));
  if (s === 0) seatsLink.hidden = false;
  return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`;
}

// Cards already drawn, by answer: the same answer twice draws nothing new.
const cards = new Map();

function renderCard(queue) {
  const key = JSON.stringify(queue);
  let card = cards.get(key);
  if (!card) {
    card = document.createElement('section');
    card.innerHTML = `
      <h2>The sale opens in <span class="left">${timeLeft()}</span></h2>
      <p>You are number ${queue.place.toLocaleString('en-US')} in line.
        ${queue.waiting.toLocaleString('en-US')} buyers are waiting.</p>
      <table>
        <tr><th>Section</th><th>Price</th><th>Seats</th></tr>
        ${queue.sections.map((s) => `<tr><td>${s.name}</td><td>$${s.price}</td><td>${s.seats}</td></tr>`).join('')}
      </table>`;
    cards.set(key, card);
  }
  // The countdown ticks every second, and catches up when the buyer comes back to the tab.
  const left = card.querySelector('.left');
  setInterval(() => (left.textContent = timeLeft()), 1000 / speed);
  document.addEventListener('visibilitychange', () => {
    if (!document.hidden) left.textContent = timeLeft();
  });
  box.replaceChildren(card);
}

async function pollQueue() {
  const queue = await (await fetch('/api/queue')).json();
  renderCard(queue);
}

pollQueue();
setInterval(pollQueue, 5000 / speed);

Run npm start and open http://localhost:8080/waiting.html. The card shows the countdown, the buyer’s place and the table of sections. Every 5 seconds a new card replaces it, and nothing on the screen looks wrong.

A session takes 30 minutes, so the lab speeds it up

The laptop never showed the problem, for two reasons. Nobody keeps a page open on a laptop for 30 minutes to test it. And a laptop with 16 GB of memory doesn’t end a tab for a few dozen megabytes. The phone profile slows the CPU and the network, but nothing in it limits memory.

So the lab has to run the session itself. The runs behind this module used headless Chrome 157 on the 2019 laptop (Intel Core i7-9750H), driven through the DevTools Protocol, as in Modules 1 to 7. The phone profile is Module 1’s: 412 × 823, device pixel ratio 1, touch, Slow 4G and 6x CPU, with the cache disabled. Your numbers will differ.

Two kinds of runs were made:

  • Compressed. ?speed=10 makes every timer of the page fire ten times as often, so 30 minutes of the session take 3. The page then makes the same 360 polls and draws the same cards, so counts of nodes, listeners and bytes match a real session. But CPU time per second doesn’t: ten times as many timers fire in each second.
  • Real time. One 30-minute run of the sale-day page and one of the fixed page, side by side, with speed=1. The CPU numbers in this module come only from these runs.

Every 5 minutes, the script forced a garbage collection, as the Collect garbage button does, and read the same counters as the Performance monitor. Figure 1 shows one compressed run of the sale-day page.

Minute Polls DOM nodes JS event listeners JS heap after GC
0 7 4,347 17 0.90 MB
5 58 49,172 69 1.16 MB
10 118 100,891 129 1.47 MB
15 178 152,612 189 1.77 MB
20 238 204,332 249 2.07 MB
25 298 256,051 309 2.37 MB
30 356 305,185 362 2.66 MB

Figure 1: every poll adds about 860 DOM nodes and one listener, and the JavaScript heap hardly moves.

The real-time run of the same page agreed: at minute 30 it had made 358 polls and held 308,634 nodes, 366 listeners and 2.70 MB of JavaScript heap.

Answer to the prediction

The DOM nodes, by far: from 4,347 to 305,185, about 860 for each card. The listeners grew by one per poll. The JavaScript heap grew from 0.90 MB to 2.66 MB, which looks harmless on a graph.

The cards’ elements live outside the JavaScript heap, so the JS heap line almost misses them. Measured with the method at the end of this module, the same page used about 26 MB for the DOM at minute 30.

What the browser keeps, and why

Module 7 followed a script from bytes to a task. This section follows an object from the moment the page stops using it to the moment the memory is free again, and finds where the waiting page breaks that path.

Reachable objects stay

JavaScript has no free(), so a garbage collector decides which objects to keep. An object is reachable when a chain of references leads to it from a root: the global object, the current call stack, and a few lists the browser itself holds. The collector keeps every reachable object and frees the rest (MDN, memory management).

Every modern engine marks reachable objects and sweeps the others, so a cycle of objects that nothing reaches is freed. So a leak in a page is always a chain from a root that you didn’t mean to keep.

DOM nodes take part in the same rule. A DOM node is a C++ object in Blink, Chrome’s rendering engine, with a small JavaScript object that wraps it. Since Chrome 57 (2017), V8 traces references from JavaScript into the DOM and back. Blink’s C++ collector, Oilpan, now lives inside V8, which marks both graphs as one heap (V8 blog, tracing from JS to the DOM and back, V8 blog, Oilpan library, 2021).

A detached element is an element that is no longer in the document while JavaScript still references it (Chrome DevTools, fix memory problems). It can’t be seen, and it can’t be freed. Every node keeps its parent and its children, so one reference to any node in a removed subtree keeps the whole subtree (heap snapshots).

Three roots a long session fills

box.replaceChildren(card) takes the old card out of the document. Nothing on the screen shows it any more, but three chains still lead to it. A retainer is an object that holds a reference to another object, and so keeps it alive; DevTools lists them in the Retainers pane.

  1. A module variable. cards lives as long as the page, and its Map holds every card by its answer. Every answer differs, because more buyers join each time, so every card is new and stays.
  2. The timer list. The browser keeps each running interval’s callback until clearInterval(). The countdown’s arrow function uses left, so its closure keeps the <span>. The span keeps its parent, the <h2>, which keeps the card.
  3. The document’s listener list. document lives as long as the page, and it keeps each listener’s function. The visibilitychange listener uses the same left.

Figure 2 draws the three chains to one card.

[roots]                     [what holds]              [the card]
module scope    ---------> Map `cards` ------------+
                                                   |
timer list      ---------> interval callback --+   +--> <section> (one card:
                           (closure: left)     |   |     <h2>, <p>, <table>,
                                               +---+     about 860 nodes)
document's      ---------> visibilitychange ---+   |
listener list              listener                |
                           (closure: left) --------+

Figure 2: a removed card stays while any one of three chains reaches it.

The first chain is easy to see in the code. But the other two aren’t, because neither line mentions the card. A closure keeps what it uses, and left is a node inside the card.

Rule: Removing an element from the page frees nothing; dropping the last reference to it does.

Two kinds of collection, and where they run

The heap is split by age, because most objects die young. V8 allocates new objects in a small young generation and moves the ones that survive two collections to the old generation (V8 blog, trash talk, 2019).

A minor GC collects only the young generation: it copies the few survivors and drops the rest, so its cost grows with what survives, not with what was allocated. A major GC collects the whole heap: it marks every reachable object, then sweeps and, where pages are fragmented, compacts. Most of the marking runs on helper threads while JavaScript runs, since Chrome 64 (2018), and sweeping runs there too (V8 blog, concurrent marking).

But the main thread still pays. Each minor GC pauses it, and so does the last step of each major GC. A trace shows these pauses as Minor GC and Major GC events in the Main track, colored as scripting (Performance panel reference).

A leak makes each major GC mark more. Every card the waiting page keeps is about 860 nodes that the collector must visit on every full collection, for the rest of the session. The 5-second traces of the real-time runs caught no collection of the sale-day page at minute 29, so these runs don’t show how much longer its collections became.

What a phone does when memory runs short

A phone has a few gigabytes of memory for every app on it, and the browser is one app. So each platform ends pages it can’t afford:

  • Android runs apps in processes ranked by importance. A process the user can’t see may be killed at any time when the system needs memory (Android, processes and app lifecycle). Chrome runs pages in renderer processes, and a page behind another app is in a process the user can’t see.
  • Chrome itself discards hidden tabs when memory runs low, first as an experiment in Chrome 46 on desktop. Since Chrome 108 (2022), Memory Saver also discards tabs unused in the background for some time (tab discarding, Memory Saver).
  • iOS runs every browser on WebKit. When a page’s content process crosses a memory limit, the system kills it, and Safari loads the page again. The limit depends on the device, and Apple publishes no number (WebKit bug 279637).

Tab discarding is the browser throwing away a hidden page and loading it again when the user returns. The page gets no event at that moment, so it can’t send a beacon or save its state. After the reload, Chrome sets document.wasDiscarded to true (Page Lifecycle API), and web-vitals then reports the navigation type restore. If the system ends the process instead, the next load may look like a plain reload.

That’s what happened to Leo at 9:56. His messages app came to the front, the waiting page’s tab became hidden, and the phone ended it. Which phones do this, and at what size, is the platform’s decision. So the lab can measure only how much the page holds and how fast it grows.

Find what the page keeps

These steps use the DevTools UI. The numbers in them come from the same runs through the protocol, which reads the same counters and takes the same snapshots, not from the panel itself.

  1. Watch the counters. Open waiting.html?speed=10 with the phone profile. In the Command Menu, run Show Performance monitor. It draws CPU usage, JS heap size, DOM Nodes, JS event listeners and other counters in real time (Performance monitor).

Watch for a minute. DOM Nodes climbs in steps, one step per poll, and never comes down. JS event listeners climbs one at a time. The JS heap size draws a saw: it rises with every poll and falls at every collection, a little higher each time.

  1. Rule out garbage that is still waiting. A rising line can be garbage the collector hasn’t reached yet. Open the Memory panel and click Collect garbage (the trash can icon), then read the counters again.

In the compressed run, a forced collection at minute 30 left 305,185 nodes and 362 listeners. Only reachable objects survive a forced collection, so these are kept on purpose by something.

Pause and predict. You take a heap snapshot at minute 30 and filter for detached objects. Which kind of detached object will be most common: <section>, <tr> or Text?

  1. Take a heap snapshot. A heap snapshot is a copy of every reachable object in the page’s heap, with the references between them. In the Memory panel, choose Heap snapshot and Take snapshot. DevTools collects garbage first, so the snapshot holds only reachable objects (heap snapshots).

In the Summary view, type Detached in the Class filter. DevTools names an object Detached <tr> when it belongs to a subtree that isn’t in the document. Figure 3 is the top of that list in the compressed run at minute 30.

Class filter: Detached Count Shallow size
Detached <td> 127,440 10,952 KB
Detached Text 131,688 10,288 KB
Detached <tr> 42,834 3,681 KB
Detached <section> 354 36 KB
Detached <table>, <tbody>, <h2>, <p>, <span class="left"> 354 each 30–36 KB each

Figure 3: 354 old cards are still in memory, about 70 KB each, and most of it is table cells and their text.

Answer

Text: 131,688 detached text nodes, against 127,440 cells, 42,834 rows and 354 sections. Each card has one <section> but 121 rows of three cells, and every cell holds a text node. The whitespace in the template between tags adds more text nodes. The count of sections tells you how many cards; the count of text nodes tells you where the bytes are.

Two sizes describe each object. Shallow size is the memory an object holds itself. Retained size is the memory that would be freed if the object were deleted, with every object that only it keeps alive (memory terminology).

A detached <section> has a shallow size of about 100 bytes. Its retained size can be small as well. That’s because an object retains only what nothing else reaches, and the timer reaches the card through the <span>.

memlab, a tool described below that reads the same file, gave one card’s <table> a retained size of 72.1 KB.

The 24.7 MB of detached shallow size in this snapshot is about 85% of the snapshot’s 29.1 MB. The counts come from these runs; the sizes are what Chrome 157 reported, and other versions count differently.

  1. Compare two snapshots. Take a second snapshot 30 seconds later, and choose Comparison in the view menu. The # New column lists what appeared between the two.

In two snapshots taken 30 seconds apart at speed=10, Detached <td> grew from 6,480 to 28,800. The 22,320 new cells are 62 cards of 360 cells: one action repeated, not one large object.

  1. Read the Retainers. Select one Detached <section>. The Retainers pane below lists what holds it, and the shortest path back to a root (heap snapshots). Right-click a retainer and choose Ignore this retainer, added in Chrome 125 (2024), to see the next path.

The lab’s build minifies the code, so a context variable shows as r instead of left. So to read names, set minify: false in build.js and build again while you debug. Figure 4 is the path search on such a build, at pretend minute 12, after ignoring one retainer at a time.

Retainers of one Detached <section>, shortest path first

1. <section> <- [3] in <h2> <- [6] in <span class="left">
     <- left in system / Context <- context in (closure)
     <- V8Function <- ScheduledAction <- DOMTimer        the interval
   Ignore every DOMTimer:
2. <section> <- [3] in <h2> <- [6] in <span class="left">
     <- left in system / Context <- context in (closure)
     <- V8EventListener <- EventListener                 the listener
   Ignore every event listener:
3. <section> <- 132 in (array) <- table in Map
     <- cards in system / Context <- context in pollQueue  the Map
   Ignore the Map:
   no path left

Figure 4: the same card has three retainers, one for each chain in Figure 2.

system / Context is a closure’s scope: the variables an inner function uses from the function around it. The first two paths go through the same scope, the one that holds left, because both closures use it. DOMTimer and ScheduledAction are Blink’s objects for a timer and its callback. The path search came from a script that reads the snapshot file the way the Retainers pane does; it isn’t a screenshot of the panel.

  1. Count the detached roots. Since Chrome 130 (2024), the Memory panel has a Detached elements profile. It lists the detached elements that JavaScript keeps, grouped by the root of each detached subtree (fix memory problems).

These runs read the same list through the protocol’s DOM.getDetachedDomNodes method: 355 roots, each a SECTION with three children. That’s one more than the snapshot’s 354, because a poll ran between the two calls.

The profile counts cards; the snapshot counts every node in them. Both describe the same leak.

Rule: Confirm growth with counters after a forced GC, find the class with a snapshot, and find the cause in the Retainers.

Two more profiles, and what they do not show

The Memory panel has two more ways to look, and they answer a different question: who allocated it, not who keeps it.

  • The allocation timeline (“Allocations on timeline”) takes a snapshot about every 50 ms while you use the page. It shows, for each moment, how much of what was allocated then is still alive at the end (allocation timeline).
  • Allocation sampling records a sample of allocations with the JavaScript function that made them, and shows memory by function (fix memory problems).

Both see the JavaScript heap. On the unminified waiting page, 60 seconds of allocation sampling at speed=10 kept 568 KB alive at the end. Of that, 545 KB came from renderCard, through the Map‘s get: the cache keys, the JSON text of each answer, about 5 KB each. The allocation timeline for the next 30 seconds found 60 such strings, 300 KB, plus 300 small objects from renderCard.

Neither profile showed the cards’ elements. That’s because, in these runs, no DOM object carried a JavaScript allocation stack. Figure 5 sums up which tool answers which question.

Tool Question it answers Showed the cards’ elements here
Performance monitor Does something grow, and which counter? as a count of DOM nodes
Heap snapshot, Summary and Comparison What is kept, how many, how large? yes, every node
Retainers pane Why is this object kept? yes
Detached elements profile Which removed elements does JavaScript keep? yes, one root per card
Allocation timeline When was what is still alive allocated? no
Allocation sampling Which function allocates what stays? no

Figure 5: a DOM leak is found with snapshots and retainers; the allocation tools find JavaScript objects.

The Performance panel can also record memory: check Memory before recording, and the counters appear under the tracks, with JS heap, documents, nodes and listeners (fix memory problems). It’s useful for a few seconds around one action, but for 30 minutes the Performance monitor is lighter.

Module 7’s candidates

Module 7 handed over three suspects. The same tools cleared two of them:

  • The analytics script’s pointerdown listener. After the fixes below, the waiting page held 10 to 14 listeners for the whole session, the analytics listener among them. A listener added once isn’t a leak, whatever it captures.
  • The seat map’s 9 MB markup string. A heap snapshot of the seat map 8 seconds after load had 4.2 MB of JavaScript heap and no string over 100 KB. The string is garbage once the parser has read it. So it costs a peak during the load, not memory for the session.

The payment script no longer loads outside checkout (Module 7). That leaves the waiting page’s own code.

The fixes, one change at a time

Each fix below ran as a compressed session at speed=10, with a forced GC before each reading and a snapshot at the end. The numbers in Figure 7 are from those runs, one each.

Fix 1: drop the cache

The Map saves nothing. Every answer differs, so it never finds a card to reuse. So delete cards, and create the card every time. In src/waiting.js, replace the top of renderCard() down to the countdown comment:

function renderCard(queue) {
  const card = document.createElement('section');
  card.innerHTML = `
    <h2>The sale opens in <span class="left">${timeLeft()}</span></h2>
    <p>You are number ${queue.place.toLocaleString('en-US')} in line.
      ${queue.waiting.toLocaleString('en-US')} buyers are waiting.</p>
    <table>
      <tr><th>Section</th><th>Price</th><th>Seats</th></tr>
      ${queue.sections.map((s) => `<tr><td>${s.name}</td><td>$${s.price}</td><td>${s.seats}</td></tr>`).join('')}
    </table>`;

Pause and predict. With the Map gone, what happens to the DOM nodes at minute 30?

Answer

Nothing. The compressed run ended at 305,185 nodes and 362 listeners, the same as before. The JavaScript heap fell from 2.66 MB to 0.93 MB, because the 5 KB keys are gone. Every card still has two other retainers, the interval and the listener (Figure 4), so not one card was freed.

Fix 1 costs nothing here, because the cache never found a card to reuse. But if answers did repeat, each repeat would now build its 120-row table again.

A cache that never hits is a leak with a reason. If you need a cache, give it a limit: keep the last answer, or the last few, and delete the oldest when you add one. A WeakMap is a map whose keys must be objects, and whose entries go away when nothing else references the key (MDN, memory management). But it can’t replace this Map, because the keys here are strings.

A WeakMap fits when the key is an object with its own life, such as data about an element: when the element is freed, its entry goes too.

A WeakRef holds an object without keeping it alive, and deref() returns it or undefined. MDN says to avoid it where possible: when an object is freed is up to the engine, and it may never be (MDN, WeakRef). So a cache of WeakRefs may hold cards for minutes or lose them at once. And no weak structure helps here, because the timer and the listener are strong references.

Fix 2: one AbortController for the card’s listener and timer

Each card adds a listener and a timer, and nothing removes them. removeEventListener() needs the same function that was added, and the arrow function in renderCard() is a new one every time. The signal option avoids keeping it: a listener added with { signal } is removed when that signal’s AbortController aborts (MDN, addEventListener()).

First change only the listener. Above renderCard(), add:

// Removes the listener of the card on screen when the next card replaces it.
let cleanup = new AbortController();

At the start of renderCard(), add:

  cleanup.abort();
  cleanup = new AbortController();
  const { signal } = cleanup;

And pass the signal to the listener:

  document.addEventListener('visibilitychange', () => {
    if (!document.hidden) left.textContent = timeLeft();
  }, { signal });

In the compressed run, the listeners stayed between 9 and 13 for the whole session. But the nodes still reached 305,185 at minute 30: the interval still holds every card.

A timer has no signal option, but a signal can tell you when it aborts. Replace the setInterval line:

  const timer = setInterval(() => (left.textContent = timeLeft()), 1000 / speed);
  signal.addEventListener('abort', () => clearInterval(timer));

Now one abort() removes the old card’s listener and stops its timer. With nothing left that reaches it, the old card is garbage.

The compressed run held 899 or 900 nodes from minute 0 to minute 30, and 14 listeners. The snapshot at minute 30 had no detached objects and 2.4 MB in all, against 29.1 MB.

The signal option works in Chrome 90, Firefox 86 and Safari 15. Its costs:

  • One more thing to pass. Every listener and timer that belongs to the card must be tied to the signal. A new timer added later without it leaks again, and nothing warns you.
  • Order matters. abort() must run before the new card’s listeners are added with a new controller. Aborting the new one by mistake removes the listeners you meant to keep.

{ once: true } is the other built-in way, and it fits a listener that should run once. But these listeners must run many times, so it doesn’t fit.

When to update in place instead

The cleanest fix creates no new card at all. Suppose you draw the card once, then change the two lines of text that differ on each poll. Then one interval and one listener live for the whole page. That removes the cleanup code, and the table of 120 sections isn’t rebuilt every 5 seconds.

The choice flips with how much of the card changes. Here only two numbers change, so updating in place is less code.

TinyTickets keeps the new card on each poll for now. That’s because from the next sale, Leo can change prices and sections during the wait, and then the whole card must be rebuilt anyway. The AbortController pattern is the one that still works when a component is replaced as a whole.

Fix 3: stop working while the tab is hidden

When a buyer switches to another app, the page keeps polling and keeps its timers running. Chrome slows hidden pages’ timers to once per second, and after 5 hidden minutes to once per minute for chained timers (timer throttling in Chrome 88, 2021). But it doesn’t stop them, and every poll still draws a card that nobody sees.

The runs behind this module launched Chrome through Puppeteer, whose default flags turn that throttling off, so they show what the page itself does. In the compressed run of Fix 2, the page made 24 polls while its tab was hidden for 2 pretend minutes.

The Page Visibility API tells a page whether the user can see it: document.hidden, and a visibilitychange event when it changes (MDN, Page Visibility API). So stop the poll and the card’s timer when the page is hidden, and poll at once when it comes back. Replace the last two lines of src/waiting.js:

// Polls only while the buyer can see the page. Coming back asks for a fresh answer at once.
let poller;
function startPolling() {
  pollQueue();
  poller = setInterval(pollQueue, 5000 / speed);
}

document.addEventListener('visibilitychange', () => {
  clearInterval(poller);
  cleanup.abort();
  if (!document.hidden) startPolling();
});

startPolling();

The card’s own visibilitychange listener is no longer needed: coming back draws a fresh card with the right time. So delete it from renderCard(). The finished file is in the course repository.

In the compressed run, the hidden tab made no polls, against 24. Nodes stayed at 899 and listeners at 10 to 14.

The costs of Fix 3:

  • A stale countdown for one round trip. When the buyer comes back, the old card shows the old time until the answer arrives, about 0.6 s on Slow 4G.
  • No news while hidden. If your page must warn the buyer while it’s hidden, such as with a notification, it can’t stop its work.

Fix 3 doesn’t stop a phone from discarding a hidden tab. It stops the page’s work while nobody looks, and it makes the page come back right.

If Chrome discards the tab, the reload shows a fresh card, and the server still has the buyer’s place. If your page has state that only the browser knows, such as a half-filled form, you’ll want to save it when the page becomes hidden. Page Lifecycle’s freeze event, Chrome 68 (2018), is another moment to save state, in Chromium only.

Before and after

The node counts are one cost. The other is work: each leaked interval still fires every second. Figure 6 is the main thread in the real-time runs, drawn in the format of Module 2 at 20 ms per character. Each row is one second with no poll and no tap in it.

time (ms)     0         200       400       600       800       1000
              |         |         |         |         |         |
sale day,                                  .            #=...  . 19 ms
minute 1
sale day,     ...                                          ### . 75 ms
minute 29
fixed,          .                           =..          .        9 ms
minute 29

#  10 ms or more of tasks in 20 ms   =  1 to 10 ms   .  under 1 ms
right column: busy time in that second; no task reached 50 ms

Figure 6: at minute 29, the sale-day page runs 349 timers in one burst of about 60 ms every second.

In the sale-day run at minute 29, each second held about 710 tasks and 349 timer callbacks, against 42 tasks at minute 1. But none was long: the largest in a quiet second was 4.5 ms. The intervals fire together because each one started right after a poll, and the polls are a whole number of seconds apart.

The one test tap in each trace landed outside the burst, and its click took 24 ms at minute 29, as at minute 1. So the lab shows a page that does four times the work of minute 1 in every quiet second, not a page whose taps got slow. That matches the field: the INP lines barely moved.

Figure 7 puts the compressed runs side by side, at pretend minute 30.

Waiting page DOM nodes JS event listeners JS heap after GC Snapshot Detached objects Polls while hidden
Sale day 305,185 362 2.66 MB 29.1 MB 308,477 24
Fix 1: no Map 305,185 362 0.93 MB 27.3 MB 308,477 24
Fix 2, listener only 305,185 9 0.92 MB 27.3 MB 308,477 24
Fix 2: listener and timer 899 10 0.90 MB 2.4 MB 0 24
Fix 3: nothing while hidden 899 10 0.91 MB 2.4 MB 0 0

Figure 7: no single retainer fix freed a card; the last one freed them all.

In the fixed versions, the listener count fell by a few after the runs hid the page at minute 26. But these runs didn’t check which listeners went.

Confirming it in the field

The lab showed the leak with counters that buyers’ phones don’t send. So Maya wanted the page’s memory from real phones, by minutes since the page opened.

performance.measureUserAgentSpecificMemory() estimates the memory a page uses: its JavaScript and DOM, and those of its iframes, workers and related windows in its process (web.dev, monitor total page memory). It works only in Chromium browsers, from Chrome 89 (2021), and only on a page that is cross-origin isolated.

Cross-origin isolation is a page state that the browser grants when the page is served with two headers: Cross-Origin-Opener-Policy: same-origin and Cross-Origin-Embedder-Policy: require-corp. The page then can’t load a resource from another site unless that resource agrees to it (MDN, COEP). If it worked, crossOriginIsolated is true.

In server.js, in serveFile(), above the checkout cookie line:

    // The waiting page is cross-origin isolated, so that it may measure its own memory.
    if (url.pathname === '/waiting.html') {
      Object.assign(headers, { 'Cross-Origin-Opener-Policy': 'same-origin', 'Cross-Origin-Embedder-Policy': 'require-corp' });
    }

Pause and predict. The analytics script comes from 127.0.0.1:8081, another site, and the lab’s third-party server sends no Cross-Origin-Resource-Policy header. What happens to it on the isolated waiting page?

Answer

Chrome blocks it. The request failed with net::ERR_BLOCKED_BY_RESPONSE.NotSameOriginAfterDefaultedToSameOriginByCoep, and the page ran without analytics. The script was requested in no-cors mode, as a plain <script> is, and under require-corp such a response from another site loads only with a Cross-Origin-Resource-Policy header that allows it.

A CORS request avoids the block, if the provider answers CORS. The lab’s third-party server sends Access-Control-Allow-Origin: * since Module 7. In src/load-analytics.js, below the src line:

  // A CORS request: an isolated page (the waiting page) blocks a cross-origin script without one.
  script.crossOrigin = 'anonymous';

Then create src/memory.js, and import it at the top of src/waiting.js with import './memory.js';:

// Measures the page's memory at random times, on average every 5 minutes, and sends it with the
// minutes since the page opened. Only Chromium has the API, and only on a cross-origin isolated page.
const device = matchMedia('(pointer: coarse)').matches ? 'phone' : 'desktop';

function measureLater() {
  if (!window.crossOriginIsolated || !performance.measureUserAgentSpecificMemory) return;
  // Random waits with an average of 5 minutes, so the samples do not all fall on the same moments.
  const wait = -Math.log(1 - Math.random()) * 5 * 60 * 1000;
  setTimeout(async () => {
    const result = await performance.measureUserAgentSpecificMemory();
    const minutes = Math.round(performance.now() / 60000);
    navigator.sendBeacon('/vitals', JSON.stringify([
      { page: location.pathname, device, name: 'memory', value: result.bytes, minutes },
    ]));
    measureLater();
  }, wait);
}

measureLater();

The random waits follow web.dev’s advice. They give an unbiased sample over the session, instead of one measurement at the same moment on every phone. In p75.js, print memory lines in megabytes:

  const shown = group.endsWith('CLS') ? p75.toFixed(3)
    : group.endsWith('memory') ? `${(p75 / 1048576).toFixed(1)} MB` : `${Math.round(p75)} ms`;

Figure 8 has one call in each version, isolated, at pretend minute 30 of a compressed run.

measureUserAgentSpecificMemory() Total DOM JavaScript Shared performance.memory used
Sale day 29.8 MB 26.2 MB 2.1 MB 1.4 MB 3.8 MB
After Fixes 1 to 3 1.8 MB 0.1 MB 0.3 MB 1.4 MB 1.9 MB

Figure 8: the page’s total fell from 29.8 MB to 1.8 MB; the JavaScript heap alone would have shown 3.8 MB against 1.9 MB.

The bytes in the table are what the method returned (29,789,254 and 1,791,309); the table shows them in MB of 1,048,576 bytes. performance.memory is older, Chromium-only and deprecated, and it reports only the JavaScript heap (MDN, performance.memory). That’s why it missed nine tenths of this leak.

The method has limits:

  • It waits for a garbage collection. Chrome measures during a collection, and forces one after about 20 seconds. The first call in each run took 16.1 s; a later call took 0.9 to 1.5 s.
  • It exists only on an isolated page. In Chrome 157, a page without the two headers has no such method at all, so 'measureUserAgentSpecificMemory' in performance is false. Test for it before calling.
  • Numbers aren’t comparable across browsers or versions. They’re estimates whose method may change. So compare the same page over time, not your page with another site.
  • Isolation costs. Every resource from another site must answer CORS or send Cross-Origin-Resource-Policy. If a provider does neither, it breaks the page. Cross-Origin-Embedder-Policy: credentialless loads such resources without cookies instead, a weaker demand. A popup the page opens on another site also loses its link to the page under same-origin.

TinyTickets isolates only the waiting page, which has no payment widget, iframes or popups. The seat map and checkout stay as they are.

Maya shipped the three fixes and the measurement before the next Saturday sale, an arena show at 10:00 with the same waiting page. On phones, 1.4% of the page’s loads between 9:45 and 10:00 were reload or restore, against 9.6% the week before. INP after the 20th minute was 110 ms at the 75th percentile, over 1,390 lines, the same as in the first 10 minutes. The memory lines from phones had a 75th percentile of 2.1 MB in the first 10 minutes and 2.2 MB after the 20th, over 2,860 samples.

Some phones still ended the tab: the 1.4% are those buyers. Their page came back with a fresh card, and the server still had their place.

“I left the page for five minutes this time,” Leo wrote. “It was still there when I came back.”

In Firefox and Safari

  • measureUserAgentSpecificMemory() and performance.memory are Chromium-only. So field memory covers only Chromium users.
  • document.wasDiscarded, freeze and resume work in Chrome 68 and aren’t in Firefox or Safari. Chrome’s Page Lifecycle guide says Android support is still tracked in an open issue, so don’t count on restore from phones.
  • The signal option of addEventListener() works in Chrome 90, Firefox 86 and Safari 15. WeakRef works in Chrome 84, Firefox 79 and Safari 14.1.
  • Firefox’s Memory tool takes heap snapshots and compares them, with a Dominators view that shows what keeps an object alive (Firefox Memory).
  • Safari’s Web Inspector has a Memory timeline with JavaScript, images, layers and page memory, and a JavaScript Allocations timeline with heap snapshots (WebKit blog, 2016).
  • Cross-origin isolation with COOP and COEP works in all three; credentialless isn’t in every browser, so check before you use it.

The support versions come from MDN’s browser compatibility data.

What changed recently

  • 2018, Chrome 64: concurrent marking moved most of a major GC’s marking off the main thread (V8 blog).
  • 2018, Chrome 68: the Page Lifecycle events freeze and resume, and document.wasDiscarded (Page Lifecycle API).
  • 2021-01, Chrome 88: intensive throttling of timers in pages hidden for more than 5 minutes (Chrome blog).
  • 2021, Chrome 89: performance.measureUserAgentSpecificMemory() (web.dev).
  • 2022, Chrome 108: Memory Saver discards background tabs before memory runs low (Chrome blog).
  • 2024, Chrome 125, 126 and 130: Ignore this retainer, new heap snapshot filters, and the Detached elements profile (What’s new in DevTools 126, 130).
  • 2026, Chrome 150 to 154: heap snapshot tooltips with exact bytes (150), a filter for objects kept only through closure contexts (151), object counts in the Summary view (152), and edge filters by retained size (153 and 154) (DevTools 150, 151, 152, October 2026).

Online tools for this step

No online tool fits this step. That’s because a leak shows over minutes in one buyer’s own tab, and it depends on what the buyer does there. Public testing services load a page from their own servers for a few seconds and report load metrics, so they never see minute 30. Field memory needs code in your own page, such as src/memory.js above, which needs cross-origin isolation.

Two local tools do the work:

The Memory panel in Chrome DevTools. It takes heap snapshots, compares them, shows retainers and records the Detached elements, allocation timeline and allocation sampling profiles. These runs read the same data through the DevTools Protocol, not through the panel.

  • Data: lab only, one page in your own browser.
  • Limit: a snapshot of a large page takes seconds and forces a garbage collection, so it changes what it measures. Objects logged to the Console stay alive, so clear the Console before a snapshot.
  • Compared with memlab: it shows every view of one snapshot by hand, but each check needs a person to repeat it.

memlab. An open-source tool from Meta, MIT licensed, run with Node.js. It can drive a page with Puppeteer through a scenario file, or analyze three snapshots you took yourself. It reports objects that were allocated between the first two snapshots and are still alive in the third, grouped by retainer path. Version 2.0.6 was published on 2026-10-29.

These runs used only its analysis, memlab find-leaks with --baseline, --target and --final set to the three snapshot files, on three snapshots of the unminified sale-day page taken 30 seconds apart. It reported one leak cluster. Its retainer trace ran from a DOMTimer through the interval’s closure and the context variable left to Detached <span class="left">, then to the card’s table.

  • Data: lab only, from snapshots of one page.
  • Limit: it finds what you made happen. If a leak needs a hidden tab or a 30-minute wait, you’ll need a scenario that does those things. memlab’s own browser runs need a Chromium build.
  • Compared with DevTools: it repeats the same check without a person, which suits a check on every change, as Module 9 sets up for other metrics. But for one leak you can reproduce by hand, it adds a Node.js setup and shows less than the panel.

Check yourself

Debugging scenario

A month later, Omar replaces the countdown text with a ring that fills as 10:00 nears. It redraws on every animation frame. Each frame, his code builds an array of 360 points for the ring’s path, then a string from them for an SVG <path>.

After 20 minutes on the waiting page, buyers say scrolling the table stutters.

In the Performance monitor, JS heap size draws a fast saw between about 1 and 4 MB. DOM Nodes stays at 900, and JS event listeners at 12. A trace of 5 seconds at minute 20 shows a Minor GC event about every half second, each 3 to 6 ms, and no Major GC. After Collect garbage, the JS heap is 0.9 MB, as it was at minute 1.

Is this a leak? What is the cause, and what would you change?

Hint 1

What does a leak do to the heap after a forced garbage collection, and what did this page’s heap do?

Hint 2

What triggers a minor GC, and what does its cost depend on?

Answer

It isn’t a leak. The heap returns to 0.9 MB after a forced collection, and the nodes and listeners stay flat, so nothing is kept. The saw and the minor GCs come from allocation: every frame creates a new array of 360 points and a new string, and they die at once. The young generation fills about twice a second, and each minor GC pauses the main thread for 3 to 6 ms, which can push a scroll frame past its time.

So allocate less per frame. Keep one array and overwrite its points, so each frame creates no new objects. Better still, redraw only when the ring visibly changes, about once a second, which removes most of the work as well as the garbage.

Review questions

  1. In the sale-day run, the JavaScript heap grew from 0.90 MB to 2.66 MB while the page used about 26 MB more for the DOM. Why does the JS heap line miss most of it, and which counter shows it?
  2. After Fix 1 removed the Map, the DOM nodes still grew by the same amount. Why?
  3. Why can’t removeEventListener() remove the listener in Omar’s renderCard(), how does the signal option avoid that, and why would a WeakMap of cards not have helped?
  4. With Fix 3, what does the waiting page stop when its tab is hidden, and what can’t it prevent?
  5. What two conditions must hold before performance.measureUserAgentSpecificMemory() exists on a page, and why did the first call take 16 seconds?
Answers
  1. DOM nodes are C++ objects in Blink, outside V8’s JavaScript heap; the heap holds only their small wrappers and the closures. The DOM Nodes counter shows them: from 4,347 to 305,185.
  2. A removed card stays while any chain reaches it. The interval’s closure and the listener’s closure both use left, a node inside the card, so each card still had two retainers.
  3. removeEventListener() must get the same function that was added, and each call to renderCard() creates a new arrow function that nothing keeps. With { signal }, calling abort() removes every listener added with that signal, with no reference to the function. A WeakMap needs object keys, and the cache keys were strings; and the timer and the listener would still have held every card.
  4. It stops the poll and the card’s countdown interval, and polls at once when the tab is visible again. It can’t stop the phone or Chrome from ending a hidden tab; it only keeps the page from working and growing while nobody looks, and the reload then shows a fresh card.
  5. The page must be in a Chromium browser, and cross-origin isolated with Cross-Origin-Opener-Policy: same-origin and Cross-Origin-Embedder-Policy: require-corp. Chrome measures during a garbage collection and forces one after about 20 seconds, so the first call waited for that.

Lab: find the card that will not go away

Time: about 15 minutes. You need the lab app from Module 7 with the changes from “Reproduce a 30-minute session in the lab”, Chrome and Node.js. The finished code is in the course repository, folder module-08/.

  1. Run npm start. Open http://localhost:8080/waiting.html?speed=10 in Chrome, open DevTools, and set the phone profile: 412 × 823 with touch, CPU “6x slowdown”, Network “Slow 4G”, Disable cache checked.
  2. Open the Performance monitor from the Command Menu. Predict before you look: after one minute, about how many DOM nodes will the page have? Watch for 60 seconds, then click Collect garbage in the Memory panel and read the counters again.
  3. Take a heap snapshot. Type Detached in the Class filter, and write down the counts of Detached <section> and Detached <td>.
  4. Select one Detached <section> and read its Retainers. Ignore the first retainer and read the next path, until no path is left. How many retainers does one card have?
  5. Apply Fix 1, run npm run build, reload, and repeat step 2. Did the node count change?
  6. Apply Fix 2, build and reload. Watch the counters for 60 seconds again.
  7. Apply Fix 3, build and reload. Open the Network panel, switch to another tab for 30 seconds, and come back. How many /api/queue requests did the hidden page make?
Results from one run

These come from headless Chrome 157 on a 2019 laptop (Intel Core i7-9750H), through the DevTools Protocol, not the DevTools UI. Your numbers will differ.

  • Step 2: at pretend minute 10, one real minute, 100,891 nodes and 129 listeners after a forced GC.
  • Step 3: at pretend minute 30, 354 detached sections and 127,440 detached cells.
  • Step 4: three retainers: the interval, the visibilitychange listener and the Map.
  • Step 5: the same 305,185 nodes at minute 30; the JS heap fell from 2.66 MB to 0.93 MB.
  • Step 6: 899 or 900 nodes for the whole run.
  • Step 7: none; before Fix 3, 24 in 2 pretend minutes (12 real seconds). In a normal Chrome window, Chrome also slows the timers of a hidden tab.

Stretch: after Fix 3, call await performance.measureUserAgentSpecificMemory() in the Console of the isolated waiting page, and time it. Then check out the sale-day waiting.js and do it again at pretend minute 30. Compare the DOM entries of the two breakdowns.

What to look for

In one run each, the sale-day page returned 29,789,254 bytes, of which 26,226,664 were DOM, and the fixed page 1,791,309, of which 101,576 were DOM. The first call on a page took about 16 seconds, because Chrome waited for a garbage collection. Objects logged to the Console stay alive, so log the bytes, not the result object.

Cheat sheet

Memory in long sessions
  1. Reachable from a root stays; removing an element frees nothing
  2. Watch DOM Nodes and JS listeners, not only the JS heap
  3. Collect garbage first; what survives is kept on purpose
  4. Snapshot, filter Detached, read Retainers, ignore one at a time
  5. Closures keep what they use: a timer or listener can hold a card
  6. One AbortController per component: { signal } and clearInterval
  7. Caches need a limit; WeakMap only for object keys
  8. Hidden tab: stop polling and timers; a phone may end it anyway
  9. Field: measureUserAgentSpecificMemory needs COOP + COEP, Chromium

Figure 9 is the whole module in one picture: what a long session keeps, how you find it, and what releases it.

[what keeps a card]     [how you see it]              [what releases it]
module variable    ---> Retainers: Map in a      ---> no cache, or one
(a Map of cards)        Context                       with a limit
interval callback  ---> Retainers: DOMTimer,     ---> clearInterval on
                        closure, left                 abort()
document listener  ---> Retainers:               ---> { signal } and
                        EventListener, closure        abort()
hidden tab         ---> polls while nobody       ---> visibilitychange:
                        looks                         stop, then poll
all of it          ---> DOM Nodes counter;       ---> measure again,
                        field memory samples          same setup

Figure 9: a page in a long session must release what it no longer shows; every retainer must go before the memory does.

Next, in Module 9, a new organizer’s page is slow and nobody knows why, and Maya has a week before its sale to use everything from Modules 1 to 8.

Sources