Ömer Faruk YILDIRIM
tutorials

Node.js Production Failure Lab · part 2

Why Does the Service Die Every Four Minutes? Memory Leaks and Unbounded Caches in Node.js

The API restarts every few minutes, and the logs contain a single FATAL line. We trace, step by step from heap graphs to heap snapshots, how a marketing campaign turned a cache into a memory leak.

26 min read60 min hands-oncode(opens in a new tab)

Node.js Production Failure Lab · Part 2 · Difficulty ★☆☆ · Reading time ~20 min · Lab ~30–60 min

In January 2023, Kent C. Dodds wrote about a problem on his personal site that he’d been chasing for months: after every deploy, memory crept up slowly, at some point spiked along with CPU, the site struggled to serve requests, and every so often the process died from running out of memory. None of the logs, timing headers, or load tests revealed the trigger. What finally worked was taking a heap snapshot of the running process and looking at what was piling up in Chrome DevTools (Fixing a Memory Leak in a Production Node.js App).

This picture may feel familiar: “random” restarts, a process that dies without logging an error, a problem nobody can reproduce. In this article we’ll live through the same picture in a production incident. The summer sale campaign has just started, the API restarts every few minutes, and customers occasionally see “Bad Gateway.” The culprit is an innocent-looking cache added for performance two days ago. The trigger is a Facebook ad.

In Part 1 we hunted for CPU work that was eating Node.js’s single thread. This time what runs out isn’t time; it’s memory.

What you’ll learn

  • How V8 manages memory: the heap, the garbage collector, and objects that are “reachable but useless”
  • How to line up “random” restarts against the memory graph, and how to read the last line before the process died
  • The metric that separates a busy-but-healthy service from a leak: live heap after GC
  • How to read a cache’s hit ratio to tell how much it’s actually helping
  • How to compare two heap snapshots to find the object that’s piling up and who is holding on to it
  • The three questions every cache must answer: what’s the key, what bounds its size, and what evicts entries?

Prerequisites

You can read this article without running the lab. These will help:

TopicWhyResource
V8’s heap and --max-old-space-sizeTo understand where the heap limit comes fromUnderstanding and Tuning Memory (official guide)
Garbage collectionTo answer “why wasn’t this cleaned up?”Trash talk: the Orinoco garbage collector (V8 blog)
Heap snapshotsThe main tool in this articleUsing Heap Snapshot (official guide)
Caching and LRUTo understand the fixIt’s enough to know that Map preserves insertion order

1. The concept: the garbage collector only collects garbage

In JavaScript you don’t free memory yourself; V8’s garbage collector (GC) does. The GC’s rule is simple: it starts from the roots (the global object, module scopes, the variables of running functions) and follows references. Every object it can reach is alive; anything it can’t reach is garbage and gets collected.

That’s why a “memory leak” in JavaScript really means: objects nobody needs anymore that are still reachable. From the GC’s point of view there is no leak; someone holds a reference to these objects, so they’re alive. And the most common retainers are structures that hold on to objects on purpose: a module-level Map, an array, a cache.

root ──► module scope ──► const entries = new Map()
                            ├─ "/api/products?page=1&fbclid=IwAR8x…"  ──► 48 product cards (~25 KB)
                            ├─ "/api/products?page=1&fbclid=IwARq2…"  ──► 48 product cards (same content)
                            ├─ "/api/products?page=1&fbclid=IwARz7…"  ──► ...
                            └─ ... one more for every click, none of them ever read again

The heap also has a ceiling. As it fills up, the GC runs more often and for longer, but it can’t release objects that are still being held. Eventually an allocation request can’t be satisfied and V8 shuts the process down: FATAL ERROR: … JavaScript heap out of memory. This isn’t an exception: try/catch won’t catch it, and not even process.on('exit') runs.

See it for yourself: a 30-line experiment

// leak.mjs: a cache keyed by URL that never deletes anything
// Run: node --expose-gc leak.mjs [unbounded|normalized]
const mode = process.argv[2] ?? 'unbounded';
const cache = new Map();

function handle(url) {
  const u = new URL(url, 'http://shop');
  const key = mode === 'unbounded'
    ? u.pathname + u.search                                          // full URL: fbclid included
    : u.pathname + '?page=' + (u.searchParams.get('page') ?? '1');  // only the parameter that changes the response
  const hit = cache.get(key);
  if (hit && hit.expiresAt > Date.now()) return hit.body;
  const body = { items: Array.from({ length: 48 }, (_, i) => ({ id: i, description: 'x'.repeat(500) + Math.random() })) };
  cache.set(key, { body, expiresAt: Date.now() + 60_000 });
  return body;
}

const mb = (b) => (b / 1024 / 1024).toFixed(1);
for (let round = 1; round <= 5; round++) {
  for (let i = 0; i < 2_000; i++) {
    const page = 1 + (i % 5);                              // only 5 distinct pages
    const fbclid = Math.random().toString(36).slice(2);   // unique to every click
    handle(`/api/products?page=${page}&utm_source=facebook&fbclid=${fbclid}`);
  }
  globalThis.gc();                                         // full GC: only live objects remain
  console.log(`${round * 2000} requests  entries: ${cache.size}  heap after GC: ${mb(process.memoryUsage().heapUsed)} MB`);
}

On my machine (Node.js 22), the result:

$ node --expose-gc leak.mjs unbounded
2000 requests  entries: 2000  heap after GC: 48.6 MB
4000 requests  entries: 4000  heap after GC: 94.2 MB
6000 requests  entries: 6000  heap after GC: 139.6 MB
8000 requests  entries: 8000  heap after GC: 184.9 MB
10000 requests  entries: 10000  heap after GC: 230.4 MB

$ node --expose-gc leak.mjs normalized
2000 requests  entries: 5  heap after GC: 3.4 MB
...
10000 requests  entries: 5  heap after GC: 3.6 MB

Same 5 pages, same content. The only difference is the key. With the full URL, every request adds a new entry, and even after a full GC the heap grows by ~45 MB every 2,000 requests. Narrow the key down to the parameter that actually changes the response, and the cache holds 5 entries while the heap stays flat at 3.6 MB.

To see what happens when the heap hits its ceiling, shrink the heap on purpose:

// oom.mjs
import v8 from 'node:v8';
console.log(`heap limit: ${(v8.getHeapStatistics().heap_size_limit / 1024 / 1024).toFixed(0)} MB`);
const cache = new Map();
let i = 0;
setInterval(() => {
  for (let n = 0; n < 200; n++) cache.set(`/api/products?fbclid=${i++}`, { body: 'x'.repeat(20_000) + i });
}, 1);
process.on('exit', (code) => console.log('exit', code)); // on OOM, not even this runs
$ node --max-old-space-size=64 oom.mjs
heap limit: 112 MB

<--- Last few GCs --->
[…] 671 ms: Mark-Compact (reduce) 67.0 (95.9) -> 65.5 (69.1) MB, …

FATAL ERROR: Reached heap limit Allocation failed - JavaScript heap out of memory

The process died in 0.7 seconds, and the exit line was never printed. Two observations:

  1. --max-old-space-size=64 limits the “old space”; the total heap limit (including the young generation) is reported as 112 MB. You can see the limit in your own environment with v8.getHeapStatistics().heap_size_limit.
  2. The last GC lines are the symptom itself: a full Mark-Compact ran and could only reclaim 1.5 MB. The heap is almost entirely full of live objects.

2. The incident: the first morning of the summer sale

🔥 [FIRING] ApiRestarting: shopflow-api restarted 3 times in the last 15 minutes

Three weeks after the report incident, ShopFlow is running its Summer Sale. Marketing’s Facebook campaign launched this morning, traffic is up 50%, and most of it comes from the ads. The support team forwards messages like this:

“The site showed ‘Bad Gateway’ twice while I was browsing the sale. It was fine after a refresh.”

Here’s what you know:

  • Traffic is ~55 requests/s, mostly campaign visitors landing on product listings.
  • Between restarts, latency is normal.
  • Nobody is restarting anything by hand: every time the process exits, the container runtime restarts the container.
  • Recent deploys:
VersionWhenChange
2.17.1yesterday404 instead of 500 for an unknown customer in order history
2.17.02 days agocache catalog responses in memory for 60 s
2.16.1last weekexpress and pino version upgrade
2.16.02 weeks agoimage gallery and description on product cards

If you’ve set up the lab, start the incident:

git clone https://github.com/FARUK-YILDIRIM/nodejs-production-failure-lab.git
cd nodejs-production-failure-lab
./lab start 002

💡 Want to try it yourself first? Stop here, open Grafana (http://localhost:3000), and investigate on your own for 30 minutes. You’ll need to wait ~4 minutes for the first crash. The results of each step below are tucked into collapsible sections; open them when you get stuck. For the lab’s built-in hints: ./lab hint 002.


3. Investigation, step by step

Step 1: Are the restarts really random?

“Random” usually means “we haven’t put it next to the right graph yet.” Look at the API restarts count and the Requests per second by status panel on the dashboard, then switch to the Node.js runtime → Memory panel for the same time range.

What do we see?

The restarts aren’t random at all. In my run, the process started at 23:19:07, then restarted at 23:23:07, 23:27:07, 23:31:02, and 23:34:47: each process lives for 225–240 seconds, roughly 4 minutes.

The memory panel draws a sawtooth with the same rhythm: after each restart, heap used starts at a few tens of MB and climbs to the heap limit line (259 MiB), then resets the moment it touches the ceiling. Every tooth is a restart.

The right-hand panel shows a thin blue wave of 502s at every restart. For a few seconds there’s no API behind Traefik; that’s the “Bad Gateway” customers see. In 15 minutes, 279 of 47,793 requests (0.58%) came back as 502.

Grafana: on the left, the memory panel, where the heap used and live heap (after full GC) lines climb to the 259 MiB heap limit and reset every 4 minutes; on the right, requests by status code, with thin blue 502 waves at each restart

The yellow “live heap (after full GC)” line sits just below the green “heap used” line and climbs with it. On the right, notice the 502 waves: the first crash at 23:23 is barely visible (more on why below); the following ones are at 23:27, 23:31, and 23:35.

The 502s from the first crash not showing up in the graph isn’t a trap the lab left on purpose; it’s just how Prometheus works: the 502 counter series is created when the first 502 arrives, and rate() can’t count a series’ first value as an increase. Error-rate panels undercounting the first event happens in real systems too.

Lesson: First match a “random” failure against time. Something periodic (every 4 minutes) almost always points to a resource that fills up gradually.

Step 2: Read the last words before death

Is the process exiting on its own, or is it being killed from outside? Even though the container gets restarted, ./lab logs api also shows the output of the same container’s previous runs. Look for a line starting with FATAL.

What do the logs say?

Terminal: output of ./lab logs api; two 'slow request' lines taking 1258 ms, then two Mark-Compact lines in the Last few GCs section and a red FATAL ERROR: Reached heap limit Allocation failed - JavaScript heap out of memory; at the bottom, the container restarts with a Debugger listening line

The last two Mark-Compacts took 211 ms and 154 ms and could reclaim only 0.7 and 0.6 MB out of a 254 MB heap. The product requests just before them took 1.26 seconds.

  • FATAL ERROR: Reached heap limit … JavaScript heap out of memory: nobody is killing the process from outside (it’s not Docker’s OOM killer, not a SIGKILL). V8 itself hits the heap limit and shuts the process down.
  • The process died 239 seconds after it started (239163 ms): the same 4-minute period as in Step 1.
  • The heap limit doesn’t come from the container’s 512 MB but from V8’s own limit: on the dashboard, nodejs_heap_size_limit_bytes = 271,581,184 bytes = 259 MiB. The container was given 512 MB, but the JavaScript heap runs out at roughly half of that.

Lesson: If a process restarts silently, read the last lines of the previous run. “No errors” often means “the process that would have logged the error is dead.”

Step 3: Load or leak?

Here’s the red herring: “Traffic is up 50%, the service can’t handle the load, let’s scale out.” The way to test that claim is to look not at how full the heap gets, but at how much remains after GC.

What does the live heap say?

The yellow live heap (after full GC) line in the memory panel is how much remains on the heap after each full GC, i.e. the objects that are genuinely reachable.

  • In a busy but healthy service, this line draws a flat floor: requests create lots of objects, but once a request finishes they all become garbage and the GC collects them.
  • Here the floor keeps rising: deriv(nodejs_heap_used_after_gc_bytes[3m]) gives ~820–870 KB/s across three separate teeth. Every second, ~0.8 MB of objects survive GC and never leave.

The garbage collection panel and the edge latency tell the same story: as the heap approaches its ceiling, major GCs (yellow) get more frequent, and right before every crash the p95 at the edge shoots up to 1.5–2 seconds.

Grafana: on the left, the garbage collection panel with minor and major GC time; major GC peaks before every crash; on the right, latency at the edge, with p95/p99 jumping to 2 seconds at crash times; two large peaks of 4 and 10 seconds at 23:20 and 23:21

Major GC (yellow) peaks before every crash; the edge p99 climbs to 2 seconds at the same moments. The 4 s and 10 s peaks at 23:20 and 23:21 aren’t from the leak but from the two heap snapshots I took: the process stops completely while a snapshot is being taken (Step 5).

Hypothesis: Something holds a reference to a few more objects on every request, and never lets go.

Lesson: The size of the heap measures load; the slope of the post-GC floor measures a leak. Look at the bottom of the sawtooth, not the top.

Step 4: Find whatever holds on to objects on purpose

What in the codebase stores objects on purpose? In the change history, 2.17.0: “cache catalog responses in memory for 60 s.” Check how well the cache is working: the API publishes the http_response_cache_lookups_total metric with a result (hit/miss) label.

Is the cache doing its job?

In Grafana Explore, sum by (result) (rate(http_response_cache_lookups_total{job="api"}[1m])):

Grafana Explore: cache lookups; ~39 misses per second, ~5 hits per second

Yellow “miss” at ~39 per second, green “hit” at ~5 per second. In 15 minutes, only 4,856 of 39,744 lookups were hits: 12%.

Product listings are per category and page, a bounded set that repeats constantly. A cache serving that set should answer most requests from memory. A 12% hit ratio says the cache almost never sees the same key twice. ~39 misses per second = ~39 new entries per second.

Continuous profiling points the same way. In Drilldown → Profiles, choose the memory/inuse_space profile type: this profile shows where the objects living on the heap were allocated.

Grafana Drilldown Profiles: shopflow-api memory/inuse_space; the pg-protocol parser, express response, src/catalog/images.ts, and catalog.routes.ts toCard near the top of the Top Table; catalog.routes.ts and shared/response-cache stacks in the flame graph

Next to Express’s response code and the pg driver, catalog/images.ts (202 MiB) and catalog.routes.ts:toCard (520 MiB total) stand out: most of the live memory is product cards built for catalog responses.

A heap profile and a snapshot answer different questions: the profile asks “where were these objects born?”, the snapshot asks “who is keeping these objects alive?” For a leak, the second one matters more.

Step 5: See what’s being held: comparing heap snapshots

The most conclusive evidence is the heap itself. Right after a restart (while the heap is small, so the snapshot is fast): chrome://inspect → 127.0.0.1:9229 → Memory tab → Heap snapshot. Take a second snapshot a minute later, select it, and switch the view from Summary to Comparison. Expand the rows with the largest positive delta and follow them upward in the Retainers section at the bottom.

⚠️ While a heap snapshot is being taken, the process stops completely, and it may need extra memory on the order of the heap size. In my measurements, a 74 MB snapshot file took 2.8 seconds and a 124 MB file took 8 seconds, leaving two peaks of 4 s and 10 s in the edge latency graph. In production, do this on a replica that’s been pulled out of traffic.

What does the snapshot show?

Heap snapshot comparison: in 70 seconds, +636,228 strings (+43.4 MB) and +73,749 Objects; key strings containing fbclid go from 1,631 to 3,790; retainer chain string → the Map's internal table → Map → entries in the response-cache.ts module scope → the cacheResponses middleware → Express Route

In 70 seconds, more than 636 thousand new strings and 73 thousand new objects survived. Among them, URLs containing fbclid= went from 1,631 to 3,790, all in the same Map’s table. And the Map is held by the entries variable in response-cache.ts’s module scope.

The retainer chain tells the whole story in one line:

"/api/products?category=luggage&page=3&limit=48&utm_source=facebook&utm_medium=paid_social&utm_campaign=summer_sale&fbclid=IwAR2rNn_Dslc…"
  ← the Map's internal table ← Map ← entries (response-cache.ts module scope) ← cacheResponses() middleware ← Express Route

The keys are full URLs: utm_* parameters plus an fbclid unique to every click. Even when two campaign visitors request the same listing, their keys are different. Because the Express route lives for the lifetime of the process, so do the middleware’s closure, the module scope, and the Map inside it.

Step 6: The code, last

// shared/response-cache.ts (2.17.0)
const entries = new Map<string, Entry>();          // module level: lives as long as the process

export function cacheResponses(ttlMs: number): RequestHandler {
  return (req, res, next) => {
    const key = req.originalUrl;                   // path + the entire query string
    const hit = entries.get(key);
    if (hit && hit.expiresAt > Date.now()) {       // expiry is only checked on read
      res.set('X-Cache', 'HIT').json(hit.body);
      return;
    }
    const send = res.json.bind(res);
    res.json = (body: unknown) => {
      if (res.statusCode === 200) entries.set(key, { body, expiresAt: Date.now() + ttlMs }); // never deletes anything
      return send(body);
    };
    next();
  };
}

Three problems stack on top of each other:

  1. The key is too specific. Only category, page, and limit change the response; utm_* and fbclid don’t, but they end up in the key.
  2. Expiry is lazy and never deletes anything. An expired entry is only overwritten if the same URL comes in again. A URL with a unique fbclid never comes back; the entry, and the 48-product-card response it holds, stay in the Map forever.
  3. No upper bound. The cache’s size grows with the number of distinct URLs clients can generate. And that number is infinite.

Once again, the trigger and the root cause are different: the cache has been in production for two days. Before the campaign, keys were bounded by the catalog (categories × pages × products), and memory grew a little and then leveled off. The campaign gave every click a unique URL and turned a bounded key space into an infinite one.

The lab’s diagnosis questions and answers (./lab submit 002)
QuestionAnswer
What runs out before every restart?JavaScript heap memory
What prevents that memory from being freed?An in-memory cache that never lets go of entries
Why did it get so much worse this week?Every campaign click has a unique URL (utm_ and fbclid parameters)*

4. Mitigation: stop the bleeding first

  • Roll back 2.17.0. Without the cache, the API serves every request from Postgres again: a bit slower, but the database was already carrying this load the week before. The restarts stop immediately.
  • Or scheduled restarts / more memory. These only buy time; every restart still drops in-flight requests. Giving it 1 GB instead of 512 MB pushes the crash back by a few minutes, and that’s it.
  • Don’t: scale out as a “fix.” Every new replica leaks at its own share of the rate and just crashes a little later.

5. The fix: a cache has to be bounded

Constraint: the cache stays, and no response changes. The fix has three parts.

Build the key from what changes the response. Each route declares the parameters it uses; everything else (utm_*, fbclid, any tracking parameters added in the future) is ignored:

function cacheKey(req: Request, params: string[]): string {
  const query = new URLSearchParams();
  for (const name of params) {
    const value = req.query[name];
    if (typeof value === 'string') query.set(name, value);
  }
  const path = `${req.baseUrl}${req.path}`;
  return query.size > 0 ? `${path}?${query}` : path;
}

Bound the size and evict the least recently used. In JavaScript, a Map iterates in insertion order. If you delete and re-insert an entry on a hit, the most recently used moves to the end and the least recently used stays at the front. That’s a small, dependency-free LRU:

export function cacheResponses({ ttlMs, params = [], maxEntries = 1_000 }: CacheOptions): RequestHandler {
  const entries = new Map<string, Entry>();            // a separate cache per route

  return (req, res, next) => {
    const key = cacheKey(req, params);
    const hit = entries.get(key);
    if (hit) entries.delete(key);                      // even if expired, it's no longer here
    if (hit && hit.expiresAt > Date.now()) {
      entries.set(key, hit);                           // re-insert: the most recently used moves to the end
      res.set('X-Cache', 'HIT').json(hit.body);
      return;
    }
    const send = res.json.bind(res);
    res.json = (body: unknown) => {
      if (res.statusCode === 200) {
        entries.set(key, { body, expiresAt: Date.now() + ttlMs });
        if (entries.size > maxEntries) entries.delete(entries.keys().next().value as string); // evict the oldest
      }
      return send(body);
    };
    res.set('X-Cache', 'MISS');
    next();
  };
}
// catalog.routes.ts
catalogRouter.get('/products', cacheResponses({ ttlMs: CATALOG_TTL_MS, params: ['category', 'page', 'limit'] }), …);

One cache per route. A flood on one route can’t evict another route’s entries.

Memory is now bounded by maxEntries × response size, no matter what clients send. On top of that, the cache is a better cache: campaign visitors now share the same entry.

6. Verification

./lab deploy
./lab verify 002

In this lab, verify runs a 60-second warm-up followed by 120 seconds of campaign traffic (open model, ~55 requests/s); memory trends take time.

MetricTargetBeforeAfter
Catalog p95< 250 ms70 ms11 ms
Error rate< 0.5%0.00%0.00%
Restarts (in the measurement window)000
Live heap growth (deriv(nodejs_heap_used_after_gc_bytes))< 300 KB/s834 KB/s63 KB/s
Heap used (max)224 MB105 MB
Event loop delay (max)341 ms293 ms
Cache hit ratio (from the dashboard, campaign traffic)12%55%

There are no restarts or errors in the “Before” column. That’s not a measurement error; it’s the sneakiest thing about leaks: verify measures for 3 minutes from a clean start, and the old code lives ~4 minutes until its first crash. A short test that looks at latency, error rate, and restart count would have called the old code “healthy” too. The only measurement that catches the difference is the slope of the live heap: 834 KB/s versus 63 KB/s. That’s why the lab sets this SLO. (The small positive slope after the fix comes from the bounded cache filling up as it warms; the 5-minute measurement on my dashboard is −4.7 KB/s, i.e. flat.)

The graphs tell the same story. The dashed orange line marks the deploy (23:38:44):

Before and after the fix: the sawtooth in the memory panel disappears after the deploy, heap used flat between 40 and 70 MiB; the 502 waves stop

No sawtooth after the deploy: heap used and live heap sit level in the 40–70 MiB band, deriv −4.7 KB/s (flat). The orange RSS stays at ~250 MiB: V8 doesn’t immediately return memory to the operating system once it has it, and that’s not a leak. On the right, the 502 waves stop.

Before and after the fix: GC time drops, and the edge latency peaks disappear after the deploy

After the deploy, the major GC peaks and the 2-second spikes at the edge are gone.

Before and after the fix: cache misses drop from ~39 to ~20 per second, hits rise from ~5 to ~25

The cache hit ratio went from 12% to 55%. Normalizing the key closed the leak and, at the same time, made the cache genuinely useful.


7. Fixes that look right but aren’t

AttemptWhy it falls short
More memory for the container, raising --max-old-space-sizeAn unbounded structure fills any limit. It postpones the crash without fixing the leak; and with a bigger heap, every major GC takes longer.
Scaling outEvery replica leaks at its own share of the rate. Restarts become less frequent, but they don’t go to zero.
Scheduled restartsEvery restart drops in-flight requests and empties the cache. It also wipes out the evidence every time.
Just shortening the TTLExpiry is only checked on read; entries that are never read again still stay forever.
WeakMapIts keys must be objects; a URL is a string. And since nothing else would hold the key, entries would vanish immediately.
“502 = the proxy is broken”Traefik returns 502 because there’s no API behind it. The proxy is the messenger of the symptom, not its cause.

8. In production: alternatives and prevention

Use an off-the-shelf LRU. The 20-line LRU in this article is for teaching; in production you may want a byte limit alongside an entry count, because response sizes vary. lru-cache supports max (entry count), ttl, and maxSize + sizeCalculation (total size).

Other options:

ApproachWhen
Stripping tracking parameters at the edge (proxy middleware)A good second line of defense; but the application should never trust that URLs are bounded.
A CDN / reverse proxy cache with a normalized keyTakes the work off the API entirely.
Redis with maxmemory and an eviction policyShared across replicas, and the limit comes with the configuration; the price is a network round trip.

Alert on the cause, not the symptom. A restart alert comes too late (in this incident it took two restarts). The slope of the live heap catches the leak before the first crash:

- alert: ApiMemoryLeak
  expr: deriv(nodejs_heap_used_after_gc_bytes{job="api"}[15m]) > 100e3
  for: 15m
  labels:
    severity: ticket

Make the next crash leave its own evidence. node --heapsnapshot-near-heap-limit=1 writes a snapshot to disk when the heap approaches its limit (Node.js CLI). Taking a snapshot costs time and extra memory; leave headroom under the container limit.

Code review checklist, for every cache, Map, or module-level array:

  • What’s the key? Is it a value the user, the browser, or marketing controls? (URL, header, query string, user ID)
  • What bounds its size? An entry count, bytes, or nothing?
  • What evicts entries? LRU, active cleanup with a TTL, or “if it happens to be overwritten”?

Generate realistic URLs in load tests. A load test that replays a fixed list of URLs will never find a key space explosion. Reproduce the variety of real traffic (tracking parameters, random IDs), and watch memory for at least half an hour, not a few minutes.


Key takeaways

  • In JavaScript, a leak is an object that’s “reachable but useless.” The GC can’t collect it because someone still holds a reference.
  • Line up “random” restarts against memory. Periodic crashes mean a resource that’s filling up.
  • Read the last line of the previous run: FATAL ERROR … heap out of memory tells you V8 itself shut the process down.
  • The metric that separates load from a leak is the live heap after GC: if the bottom of the sawtooth is rising, it’s a leak.
  • A profile shows where an object was born; a heap snapshot shows who’s holding on to it. For a leak, you want the second.
  • Every structure keyed by user input must be bounded. The key should consist of what changes the response; never utm_* or fbclid.

Test yourself

1. The memory graph draws a sawtooth. How do you prove it’s a leak and not load?

I look at the live heap after GC (nodejs_heap_used_after_gc_bytes). In a busy but healthy service the floor is flat, because the objects a request creates become garbage once it finishes. If the floor keeps rising, objects are surviving GC. For conclusive proof, I compare two heap snapshots and find the retainer of the object that’s piling up.

2. The cache had been in production for two days. Why is it crashing today?

Before the campaign, keys were bounded by the catalog: the same category and page URLs kept coming in, and memory grew a little and then leveled off. The campaign links added a unique fbclid to every click, and the key space became infinite. The campaign is the trigger; the unbounded, wrongly keyed cache is the root cause.

3. Why isn’t raising the container’s memory from 512 MB to 2 GB a solution?

The heap limit grows and the crash is delayed, but the cache still grows with every click and will eventually fill that limit too. Meanwhile, as the heap grows, major GCs get longer and the latency peaks get bigger. No limit is ever big enough for an unbounded structure.

4. Which metric would you alert on for a memory leak?

The slope of the live heap after GC: for example, deriv(nodejs_heap_used_after_gc_bytes[15m]) > 100e3 (growing faster than 100 KB per second), sustained for 15 minutes. As support: an alert on the first restart (not the second), and automatic evidence with --heapsnapshot-near-heap-limit.

Further reading

Basics

Deep dives

Real-world incidents


Next up: Error explosions. The API is dying every now and then again and the 502 waves are back, but this time memory is flat. We’ll learn how a promise rejection nobody catches can kill the whole Node.js process, and how to handle async errors.

The full lab: https://github.com/FARUK-YILDIRIM/nodejs-production-failure-lab. If you’ve solved the lab, run ./lab report 002 to generate a postmortem template and compare it with your own write-up.