Debugging Browser Memory Leaks in a Long-Running Web Console

Medium · Software Engineering Fundamentals · Frontend Engineer · Onsite

Prompt

On-call engineers keep a browser-based real-time monitoring console open throughout 10+-hour shifts. Each time an engineer switches between live data channels, the UI tears down the active channel widget and mounts a new one. Over several hours of normal channel switching, tab memory climbs past 2 GB, interactions lag noticeably, and the browser tab eventually crashes with an out-of-memory error.

Profiling points to LiveFeedWidget, shown below in simplified form:

class LiveFeedWidget {
  constructor(channelId, hostElement) {
    this.channelId = channelId;
    this.hostEl = hostElement;
    this.history = [];

    this.panelEl = document.createElement('div');
    this.panelEl.className = 'feed-status-card';
    this.hostEl.appendChild(this.panelEl);

    window.addEventListener('feed-packet', (evt) => {
      if (evt.detail.channelId === this.channelId) {
        this.updateView(evt.detail.payload);
      }
    });

    this.pollId = setInterval(() => {
      this.history.push({ recordedAt: Date.now(), state: 'online' });
    }, 1000);
  }

  updateView(payload) {
    this.panelEl.textContent = `Channel ${this.channelId}: ${JSON.stringify(payload)}`;
  }

  destroy() {
    this.hostEl.removeChild(this.panelEl);
  }
}

Walk through how you would diagnose, fix, and verify this issue end to end:

  1. Root-cause analysis: Identify every distinct reason LiveFeedWidget instances, DOM subtrees, and in-memory data fail to stay bounded or be reclaimed by garbage collection across channel switches and multi-hour shifts.
  2. Refactored implementation: Rewrite LiveFeedWidget so all subscriptions, timers, DOM references, and internal buffers have clean, bounded lifecycles upon destroy().
  3. Browser profiling workflow: Explain step by step how you would use Chrome DevTools (or equivalent browser memory tools) to confirm the leak via heap snapshots, inspect detached DOM nodes and retaining paths, and prove steady-state memory stability after your fix.

Scope & Expectations

  • Trace concrete garbage-collection root paths and distinguish object-retention leaks from unbounded growth inside live instances.
  • Produce an idiomatic, idempotent JavaScript refactor that releases every external subscription, timer, and DOM reference cleanly.
  • Detail a repeatable multi-snapshot and soak-testing workflow in browser DevTools rather than relying on single ad-hoc memory readings.

Step-by-step walkthrough

  1. How JavaScript garbage collection works—and why memory leaks happen

    A garbage collector (GC) reclaims heap memory only when an object becomes unreachable, meaning zero reference chains connect it to any GC root (an anchor the browser runtime always keeps alive, such as the global window object, the active call stack, registered event listeners, and active setInterval/setTimeout timers).

    In managed runtimes like V8, browser memory leaks fall into two distinct categories: 1. Retention leaks: An object you intended to tear down stays tethered to at least one GC root through a lingering reference. 2. Unbounded live growth: A long-lived array, map, or queue appends entries indefinitely without a capacity cap or eviction policy.

    LiveFeedWidget exhibits both failure modes simultaneously. Even after destroy() removes panelEl from the visible page, two independent GC roots still point straight at this:

    GC Root 1: window
       └── 'feed-packet' listener list
              └── arrow closure (evt) => ... ──┐
                                               ├──> LiveFeedWidget (this)
    GC Root 2: Browser active timer table      │       ├── this.panelEl  (detached <div>)
       └── 1000ms setInterval entry            │       ├── this.hostEl   (parent DOM element)
              └── arrow closure () => ...    ──┘       └── this.history  (appending every 1s!)
    

    Because either root chain suffices to keep this reachable, everything hanging off this (panelEl, hostEl, and history) remains pinned in memory forever.

  2. Leak 1: Unremoved anonymous `window` event listener

    Examine the global event subscription inside constructor:

    window.addEventListener('feed-packet', (evt) => {
      if (evt.detail.channelId === this.channelId) {
        this.updateView(evt.detail.payload);
      }
    });
    

    Here (evt) => { ... } forms a closure (a function paired with references to variables from its enclosing lexical scope—specifically this). That single block creates three problems:

    • Permanent root retention: Because window lives for the entire 10+-hour session, its listener table holds the arrow closure, which holds this.
    • No handle for removal: window.removeEventListener requires the exact same function reference originally passed to addEventListener. Passing an inline arrow function without saving a reference or attaching an AbortSignal leaves destroy() unable to unsubscribe.
    • Hidden CPU work on unmounted DOM: After N channel switches, N + 1 global listeners sit on window. Whenever a packet arrives for a previously visited channelId, every stale widget for that channel still runs JSON.stringify(payload) and mutates its invisible div.
  3. Leak 2: Uncleared `setInterval` timer and unbounded `history` buffer

    Next, look at the 1-second heartbeat loop:

    this.pollId = setInterval(() => {
      this.history.push({ recordedAt: Date.now(), state: 'online' });
    }, 1000);
    
    • Second independent GC root: Until clearInterval(this.pollId) runs, the browser's active timer table retains the callback closure, which also captures this. Fixing Leak 1 without clearing this.pollId frees zero instances!
    • Continuous background allocation: Every "destroyed" widget's interval continues firing once per second, allocating fresh objects inside its retained this.history array even when the console sits untouched.
    • Unbounded buffer on a single channel: Even if an engineer never switches channels once, this.history.push(...) appends 1 record per second without limit (10 * 3,600 = 36,000 objects over a 10-hour shift).

    Back-of-the-envelope numbers explain both the 2+ GB crash and UI sluggishness. Suppose an engineer switches channels once every 30 seconds over a 10-hour (36,000-second) shift, creating 36,000 / 30 = 1,200 instances (i = 0, 1, ..., 1199), where instance i starts at 30 * i seconds and ticks until 36,000 seconds:

    Total history entries = sum for i = 0..1199 of (36,000 - 30 * i)
                          = (1,200 * 36,000) - 30 * (1,199 * 1,200 / 2)
                          = 43,200,000 - 21,582,000
                          = 21,618,000 entries (~21.6 million objects!)
    

    With each { recordedAt, state } object plus boxed Date.now() heap numbers and array backing slots occupying roughly 50–80 bytes (plus retained DOM subtrees and closures), memory climbs well past 1.5–2+ GB while 1,200 interval callbacks fire every second on the main thread!

  4. Leak 3: Detached DOM nodes and retained parent subtrees

    Currently, destroy() executes only:

    this.hostEl.removeChild(this.panelEl);
    

    Detaching an element from the document tree does not release its memory while JavaScript still holds a reference to it. Instead, this.panelEl becomes a detached DOM tree (DOM nodes unlinked from document yet kept alive in C++/Blink and JS heaps by an active JS reference):

    Live document:   <body> ──> (workspace pane later replaced by router!)
                                      ▲
    Leaked JS `this`:  ├── panelEl  ─┴─> <div class="feed-status-card">  (detached node)
                       └── hostEl   ───> <section class="channel-pane">  (pins entire parent subtree!)
    

    Even worse, this.hostEl references a container element owned by the outer page. If a layout change unmounts that entire <section>, one leaked LiveFeedWidget pins the entire detached parent DOM subtree in memory. Also verify the parent controller outside LiveFeedWidget: if caller code appends instances into a registry (activeWidgets.push(new LiveFeedWidget(...))) without removing destroyed ones, that outer array forms a third retention root.

  5. Refactor `LiveFeedWidget` for symmetric, bounded lifecycle management

    Pair every resource acquired in constructor with deterministic cleanup in destroy():

    1. Global listener: Attach { signal: this.abortController.signal } using an AbortController (a standard browser primitive whose abort() call unregisters every associated listener in one step without manually tracking bound function references).
    2. Heartbeat timer: Call clearInterval(this.pollId) and reset this.pollId = null.
    3. Bounded history: Cap retained samples (for instance, MAX_HISTORY_SIZE = 300 for 5 minutes of 1 Hz heartbeats) using a ring buffer (a fixed-capacity circular array overwriting its oldest slot at (writeIdx + 1) % capacity in O(1) time, avoiding Array.shift()'s O(K) element shift).
    4. Idempotent DOM teardown: Guard destroy() with if (this.destroyed) return; so repeated teardown calls are idempotent (safe to invoke multiple times with no error or duplicate work), call this.panelEl.remove(), and null out panelEl, hostEl, and history.
    const MAX_HISTORY_SIZE = 300; // Retain at most 5 minutes of 1 Hz status samples
    
    class LiveFeedWidget {
      constructor(channelId, hostElement) {
        this.channelId = channelId;
        this.hostEl = hostElement;
        this.destroyed = false;
    
        // Fixed-capacity ring buffer keeps memory O(1) across 10+ hour shifts
        this.history = new Array(MAX_HISTORY_SIZE);
        this.writeIdx = 0;
        this.sampleCount = 0;
    
        // Create and mount status card
        this.panelEl = document.createElement('div');
        this.panelEl.className = 'feed-status-card';
        this.hostEl.appendChild(this.panelEl);
    
        // Bind global subscription to an AbortSignal for atomic teardown
        this.abortController = new AbortController();
        window.addEventListener(
          'feed-packet',
          (evt) => {
            if (evt.detail.channelId === this.channelId) {
              this.updateView(evt.detail.payload);
            }
          },
          { signal: this.abortController.signal }
        );
    
        // Save interval ID so destroy() can cancel it cleanly
        this.pollId = setInterval(() => {
          this.appendHistory({ recordedAt: Date.now(), state: 'online' });
        }, 1000);
      }
    
      appendHistory(sample) {
        this.history[this.writeIdx] = sample;
        this.writeIdx = (this.writeIdx + 1) % MAX_HISTORY_SIZE;
        if (this.sampleCount < MAX_HISTORY_SIZE) {
          this.sampleCount += 1;
        }
      }
    
      updateView(payload) {
        if (this.destroyed || !this.panelEl) return;
        this.panelEl.textContent = `Channel ${this.channelId}: ${JSON.stringify(payload)}`;
      }
    
      destroy() {
        if (this.destroyed) return;
        this.destroyed = true;
    
        // 1. Sever both GC root chains (window listener + active interval)
        this.abortController.abort();
        clearInterval(this.pollId);
        this.pollId = null;
    
        // 2. Unmount DOM element and release external/internal references
        this.panelEl.remove();
        this.panelEl = null;
        this.hostEl = null;
        this.history = null;
      }
    }
    
  6. Confirm the leak and inspect retaining paths in Chrome DevTools

    Use the three-snapshot comparison workflow in Chrome DevTools so one-time initialization caches do not masquerade as leaks:

    1. Warm up and open live counters: Open DevTools -> More tools -> Performance monitor to observe JS heap size, DOM Nodes, and JS event listeners in real time. Switch channels 1–2 times upfront so lazy imports and V8 inline caches warm up.
    2. Capture 3 heap snapshots (Memory panel -> Heap snapshot):
      • Click the trash-can icon (Collect garbage), then record Snapshot 1 (clean baseline).
      • Perform 20 channel switches (new LiveFeedWidget(...) -> destroy()), then record Snapshot 2 (recording a snapshot automatically runs a full GC pass first).
      • Perform 20 additional channel switches, then record Snapshot 3.
    3. Diff snapshots to isolate leaked instances:
      • Select Snapshot 2, switch the view mode from Summary to Comparison (against Snapshot 1), and enter LiveFeedWidget in the Class filter. Before the fix, you will observe # New = 20, # Deleted = 0, # Delta = +20.
      • Alternatively, view Snapshot 3 in Summary mode and set the allocation filter to Objects allocated between Snapshot 1 and Snapshot 2—any widget created during batch 1 that survives batch 2 is a confirmed leak.
    4. Inspect detached DOM nodes and retainers:
      • Filter Summary by Detached (or run the Memory panel's Detached elements profile) to spot 20 detached HTMLDivElement (div.feed-status-card) instances per batch.
      • Select a leaked div or LiveFeedWidget to inspect the Retainers tree at the bottom. Trace the retaining path (bottom-up reference chain to each GC root): HTMLDivElement <- panelEl on LiveFeedWidget <- closure context <- window 'feed-packet' listener and setInterval callback.
      • Compare Shallow Size (bytes of the object header/fields alone) against Retained Size (total memory freed if that object were collected): each leaked widget's Retained Size climbs every second as this.history grows.
  7. Verify steady-state memory stability after the refactor

    Validate the fix with both deterministic counts and extended load:

    1. Re-run the 3-snapshot diff: Across 20 switches between Snapshot 1 and Snapshot 2, filtering Comparison by LiveFeedWidget must report # New = 20, # Deleted = 20, # Delta = 0 (only the single currently mounted channel remains alive). Filtering by Detached must show 0 detached .feed-status-card nodes, and evaluating getEventListeners(window)['feed-packet'].length in the Console must stay pinned at 1 instead of climbing to 41.
    2. Run a soak test: A soak test drives sustained workload over time—such as automating 1,000 channel switches followed by 15 minutes of 1 Hz heartbeats—while watching Performance monitor across forced GC sweeps:
    Before fix (climbing floor):   /\/\/\/\/\/\/\/  --> rises past 2 GB -> tab crash
    After fix  (flat sawtooth):    /\/\/\/\/\/\/\/  --> returns to same MB baseline after every GC
    

    Once post-GC heap usage, DOM node count, and JS listener count all return to a flat horizontal floor, the leak is conclusively resolved.

Intuition & how it works

Picture JavaScript's garbage collector (GC) (the engine's automatic memory cleaner) as an overnight cleanup crew inspecting an office: any equipment still tethered by a cord to a permanent wall outlet (GC root, such as the global window object or the browser's active timer registry) cannot be thrown away. Calling removeChild() takes a status card off the visible wall, yet leaves two power cords plugged into LiveFeedWidget—so every "closed" channel widget piles up in the back room forever.

LiveFeedWidget.destroy() leaks because detaching this.panelEl visually leaves two independent root paths alive. First, window.addEventListener('feed-packet', (evt) => ...) registers an anonymous closure (a function retaining variables like this from its outer scope) on window permanently. Second, setInterval(() => ..., 1000) keeps a callback closure in the browser's active timer table that pins this and appends a fresh object to this.history every second without limit—and even a single unswitched channel grows this.history endlessly across a 10+-hour shift.

Severing both root chains in destroy() and bounding this.history resolves every issue together. Trace 3 channel switches (C1 -> C2 -> C3): 1. Before the fix, switching C1 -> C2 -> C3 leaves 3 'feed-packet' listeners on window, 3 running 1-second intervals appending to 3 separate history arrays, and 2 detached DOM nodes (elements unlinked from document yet still referenced from JS). 2. After the fix, calling C1.destroy() aborts its AbortController (removing the window listener), calls clearInterval(this.pollId) (clearing the timer root), unmounts panelEl, and nulls out fields. 3. With zero paths left from any GC root to C1 or C2, the next GC cycle reclaims both completely—leaving 1 active listener, 1 active timer, 0 detached div elements, and a fixed 300-slot ring buffer on C3.

Key points

  • Trace every GC root chain explicitly: Name both independent retainers—window -> 'feed-packet' listener -> closure -> this and active timer table -> interval callback -> closure -> this. Eliminating only one of two roots reclaims zero instances.
  • Distinguish retention leaks from unbounded buffers: Retained LiveFeedWidget instances leak across channel switches, whereas this.history.push(...) without a maximum length leaks even if the engineer stays on a single channel for 10 hours (36,000 samples per widget).
  • Quantify why the tab hits 2+ GB and lags: Switching channels every 30 seconds over 10 hours leaks 1,200 widgets whose concurrent timers allocate ~21.6 million history entries while firing 1,200 callbacks every second on the main thread.
  • removeChild unmounts DOM without freeing memory: Detached elements stay allocated as long as this.panelEl (or this.hostEl pointing into an unmounted parent layout pane) remains reachable from JS.
  • Symmetric, idempotent destroy(): Every subscription, timer, and DOM reference created in constructor is torn down in destroy(), protected by a this.destroyed guard so duplicate teardown calls are safe no-ops.
  • Prove root cause and resolution with 3-snapshot diffs: Warm up first, capture 3 heap snapshots across repeated 20-switch batches, verify # Delta == +20 and Retainer paths before the fix, and verify # Delta == 0 plus a flat post-GC soak-test baseline afterward.

Common mistakes

  • Removing the listener while forgetting clearInterval (or vice versa): Because both closures independently capture this, leaving either one registered retains the entire LiveFeedWidget, its detached div, and its history array.
  • Calling window.removeEventListener('feed-packet', (evt) => ...) with a new arrow function: Function removal checks strict reference equality (===), so passing a newly created inline arrow function silently removes nothing (mismatched { capture: true } flags also fail to match).
  • Setting this.panelEl = null without stopping the listener and timer: Not only do this and this.history keep leaking, the next matching 'feed-packet' event throws TypeError inside updateView() when accessing this.panelEl.textContent.
  • Inferring a leak from a single cold snapshot: First-time JIT compilation, module loading, and browser caches always raise memory on initial interaction; always warm up before taking Snapshot 1.
  • Leaving this.history unbounded on the live widget: Long-lived consoles require a fixed-capacity ring buffer (circular array overwriting its oldest slot in O(1) time) or time-windowed eviction.
  • Ignoring caller-side collections: Even a leak-free destroy() cannot free an instance if the parent view controller keeps old LiveFeedWidget references inside an unpruned array or Map.

Follow-up questions

  • Why is AbortController less error-prone for tearing down DOM and global event subscriptions than storing bound listener functions manually? Manual removal forces you to store every bound reference (this.onPacket = this.onPacket.bind(this)) and mirror the exact target, event type, handler reference, and capture flag inside destroy(). Passing { signal: this.abortController.signal } lets you attach inline handlers across window, document, DOM elements, and even in-flight fetch() calls, then tear down every subscription atomically with one this.abortController.abort() call—eliminating mismatched option flags and forgotten bound properties.

  • In what situations do WeakMap or WeakRef work well for associating state with DOM nodes, and why can they not replace .destroy() for active subscriptions? A WeakMap (a map whose object keys are held weakly, allowing entries to be collected automatically once no strong reference to the key remains) excels at attaching passive metadata or derived UI state to DOM elements owned by outside code (nodeStateWeakMap.set(domEl, meta)). A WeakRef (a non-owning wrapper that yields undefined once its target has been collected) fits optional caches of expensive, recomputable data. Neither can substitute for .destroy() on active window listeners, setInterval timers, or WebSocket streams because the browser runtime itself holds strong root references to active callbacks—and FinalizationRegistry offers no deterministic timing guarantee (or even guarantee of execution) for resource cleanup.

  • How would you catch regressions in DOM node counts, listener counts, and heap retention automatically inside a CI pipeline? Drive a headless Chromium test via Playwright or Puppeteer attached to the Chrome DevTools Protocol (CDP) (Chromium's low-level automation and profiling API): load the console, perform 2 warm-up channel switches, force HeapProfiler.collectGarbage, and read baseline counters from Performance.getMetrics (JSEventListeners, Nodes, JSHeapUsedSize) or Runtime.queryObjects against LiveFeedWidget.prototype. Next, run 50 mount/destroy cycles, force GC again, and assert that JSEventListeners, live LiveFeedWidget instances, and Nodes match the baseline exactly (deterministic object/listener counts avoid byte-level CI flakiness), optionally pairing with Meta's MemLab to print automated 3-snapshot retainer traces on PR failures and fast unit spies asserting clearInterval and abort() run in destroy().

Follow-up questions

Similar questions

More Anduril interview questions

All 7 Anduril questions →