Skip to content
mentoor

Topic 4 of 5 · 5 min read

Memory leaks and unbounded growth

Goal: Identify the line that causes unbounded memory growth in AI-written code and pick a bounded alternative.

A memory problem in a long-running program is usually something that grows and is never released; find the structure that only gets added to, or the data read all at once. Garbage collection frees what nothing refers to. A leak is a reference you forgot you were holding.

Check yourself · 1 of 3

Which line is the most likely cause of unbounded memory growth in a long-running service?

Choose one answer

Why it matters

Services run for days. A leak of 2 KB per request is invisible in a test and becomes gigabytes after millions of requests, ending in a crash and a restart. Separately, loading a 2 GB file or a table with 10 million rows into a list works on a laptop sample and kills the process at production size. Assistants write code that is correct for the data in front of them and rarely ask how big the data can get.

The usual suspects

  1. Unbounded caches. A module-level dict or Map that stores results by key and never evicts. Every new key stays forever.
  2. Listeners and callbacks never removed. emitter.on(...) or addEventListener called per request or per component, with no matching removal.
  3. Global lists that collect. Logs, history or metrics appended to a module-level array.
  4. Closures holding big objects. A small callback keeps a large response alive.
  5. Whole-file and whole-table reads. readFile, .read(), .fetchall(), SELECT * into a list.
  6. Timers and intervals never cleared.

How to fix it

  • Bound every cache: a maximum size and an eviction rule, such as LRU, plus an expiry.
  • Pair every on with an off (or once), and clear timers when the owner is done.
  • Stream: read a file in chunks or lines, fetch rows with a cursor or in pages, and process each piece before reading the next.
  • Keep only what you need from a big object, not the whole thing.

Before and after

# Weak: loads every row, then processes
rows = cursor.execute("SELECT * FROM events").fetchall()
for row in rows:
    handle(row)

# Fixed: iterate in batches of 1,000
cursor.execute("SELECT id, kind, payload FROM events")
while batch := cursor.fetchmany(1000):
    for row in batch:
        handle(row)

What goes wrong

  • Calling a cache a fix. A cache with no bound is a leak with a nicer name.
  • Guessing the cause. Take a heap snapshot or use tracemalloc and see what grows.
  • Streaming then collecting. If you stream the file and then append every line to a list, you are back where you started.

Examples

The module-level cache

const cache = new Map<string, Result>();
export async function lookup(query: string) {
  if (!cache.has(query)) cache.set(query, await search(query));
  return cache.get(query)!;
}

Users type free text, so keys are almost never repeated. The Map grows with every request. Replace it with an LRU cache capped at 1,000 entries and a 10 minute expiry.

Listener added per request

A request handler calls bus.on("update", cb) each time and never removes it. After 50,000 requests Node.js prints a MaxListenersExceededWarning, and each stale callback still holds its request object. Use bus.once, or remove the listener when the request closes.

Key points

  • Memory problems are almost always something that grows without bound, or data read all at once.
  • Every cache needs a maximum size, an eviction rule and ideally an expiry.
  • Every listener, timer and subscription added needs a matching removal.
  • Read big files and tables in chunks or pages instead of loading them whole.
  • Confirm the cause with a heap snapshot or allocation trace instead of guessing.

Common mistakes

  • Adding an in-memory cache with no size limit or expiry.
  • Registering listeners or timers inside a handler without cleaning them up.
  • Reading a whole file or query result into memory because the sample was small.
  • Treating a rising memory graph as normal until the process is killed.

Check yourself · 2 of 3

An AI script runs fetchall() on a table with 40 million rows and loops over the result. What is the best fix?

Choose one answer

Check yourself · 3 of 3

What is the best first step to find what is leaking in a Node.js service?

Choose one answer

Practice items, not counted towards your mastery.

Start here

More for this topic