Node Performance: Memory Leaks and Blocking the Event Loop

Node.js and Express: Build a Back End API from Scratch · Architecture, Reliability and Performance · 5 min read · Updated

Two ways a Node app slows down

  1. A leak keeps references to data nobody needs, so the garbage collector cannot free it.
  2. The fix is a limit: bounded caches, expiry times, removed listeners and cleared timers.
  3. Blocking is a long synchronous task. Every other request waits behind it.
  4. Split the work, use a worker thread or move it to a background queue.

When a Node app is slow, the cause is nearly always one of a few things: a slow database query, too many sequential calls that could run together, memory that grows until the process is killed, or code that blocks the event loop. The first two are about your design. This lesson covers the last two, which are Node-specific and which interviewers ask about often. Each has a small program that makes the problem visible.

Memory leaks

Node cleans memory with a garbage collector, which frees anything that nothing refers to. A leak is memory that you no longer need but still refer to, so it is never freed. The heap grows slowly until the process becomes slow and finally dies with an out-of-memory error, often at the worst hour. The usual causes are: a global array or object that only grows, such as a cache without a size limit; event listeners added again and again and never removed; timers that are never cleared; and closures that hold large objects.

// A memory leak you can see, and the fix. Run with:  node --expose-gc pf40-memory.js
const heapMb = () => { global.gc(); return Math.round(process.memoryUsage().heapUsed / 1024 / 1024); };

// LEAK: this cache only ever grows, because nothing removes old entries.
const leaky = new Map();
function handleRequestLeaky(id) { leaky.set(id, Array.from({ length: 1000 }, (_, k) => k + id)); }

// FIX: a cache with a size limit that drops the oldest entry (a simple LRU idea).
const bounded = new Map();
function handleRequestBounded(id, limit = 100) {
  bounded.set(id, Array.from({ length: 1000 }, (_, k) => k + id));
  if (bounded.size > limit) bounded.delete(bounded.keys().next().value);
}

const before = heapMb();
for (let i = 0; i < 20_000; i++) handleRequestLeaky(i);
const afterLeak = heapMb();
leaky.clear();
const afterClear = heapMb();
for (let i = 0; i < 20_000; i++) handleRequestBounded(i);
const afterBounded = heapMb();

console.log('Leaky cache grew the heap by more than 50 MB:', afterLeak - before > 50);
console.log('Bounded cache stays small (under 20 MB more):', afterBounded - afterClear < 20);
console.log('Bounded size:', bounded.size);
  1. Make a folder and open it in a terminal. Run npm init -y, then open package.json and add "type": "module" so that import works.
  2. Save the code as memory.js and run it with node --expose-gc memory.js. The flag lets the program ask for garbage collection, so the numbers are steady.
Leaky cache grew the heap by more than 50 MB: true
Bounded cache stays small (under 20 MB more): true
Bounded size: 100

The program does the same work twice. The leaky version stores every result in a Map that never forgets, and the heap grows by tens of megabytes. The bounded version keeps at most 100 entries and throws away the oldest, so the heap stays flat. The fix for most leaks is exactly that: put a limit on anything that grows, use a cache with a maximum size and an expiry, and remove listeners and timers when you are done with them.

How to look for a leak in a real app

  • Watch the memory of the process over time, with process.memoryUsage() or your monitoring tool. A line that only goes up is the sign.
  • Start the app with node --inspect, open chrome://inspect, and take heap snapshots at two moments. Compare them to see which objects increased.
  • Look at what you store in module-level variables. A Map or array at the top of a file lives as long as the process.
  • Check that every on has a matching off, and every setInterval has a clearInterval.

Blocking the event loop

The event loop runs your JavaScript one piece at a time. A piece that runs for 300 milliseconds means that every other request waits 300 milliseconds. Common culprits are huge JSON.parse calls, heavy loops, synchronous file functions such as readFileSync in a handler, slow regular expressions, and password hashing with a synchronous function. The program below starts a timer that should tick every 10 milliseconds, runs a heavy loop, and measures how long the loop kept the timer waiting.

// Blocking the event loop: one slow synchronous task freezes EVERY request.
import { monitorEventLoopDelay } from 'node:perf_hooks';

const histogram = monitorEventLoopDelay({ resolution: 10 });
histogram.enable();

function blockFor(ms) { const end = Date.now() + ms; while (Date.now() < end) { /* busy */ } }

setTimeout(() => {
  blockFor(300);                                   // pretend: a huge JSON.parse, a big loop, sync crypto
  setTimeout(() => {
    histogram.disable();
    const maxMs = histogram.max / 1e6;
    console.log('The event loop was stuck for about 300 ms:', maxMs >= 250);
  }, 50);
}, 50);
The event loop was stuck for about 300 ms: true

Your exact number will differ. The remedy depends on the cause. Use asynchronous versions of functions. Break a big job into smaller pieces that give the loop a turn between them. Move real CPU work to a worker thread, as in lesson 18, or to a background queue, as in lesson 35. Use the asynchronous bcrypt.hash, not a synchronous version. And measure: perf_hooks can report the event loop delay in production, and a rising delay is an early warning.

Other quick wins

  • Run independent calls together with Promise.all.
  • Turn on compression, for example with the compression package, or let nginx do it.
  • Add indexes and use lean() or limited fields in database queries.
  • Cache repeated answers, as in lesson 34.
  • Set NODE_ENV=production.

Your task

  1. Run the memory program again with a limit of 10 and with a limit of 10,000 and compare.
  2. Change the blocking loop to run in pieces, using setImmediate between them, and see the stuck time fall.
  3. Print process.memoryUsage().heapUsed every second in one of your own servers for a minute.

How to check it worked

  • You can explain why an unbounded Map is a leak.
  • You can say what blocks the event loop.
  • You can name two fixes for blocking.

Frequently asked questions

How do I know if my app has a memory leak?

Watch memory over time. If it keeps rising and never falls back after garbage collection, there is probably a leak. Heap snapshots show which objects grow.

Is readFileSync always bad?

Not at start-up, for example reading config once. Inside a request handler it blocks every other user, so use the asynchronous version there.

What is event loop delay?

How late the loop runs a timer that should be on time. A rising delay means something is blocking it.

Practise with interview questions