← Back to Node.js, page 1

nodejs-0005 · Easy fresher

What does it mean to block the event loop, and how do you avoid it?

Blocking the event loop means running long synchronous code on the main thread, so no other callback, timer or request can run until it finishes. Avoid it by using async APIs, splitting work into small chunks, or moving CPU-heavy work to worker threads or another service.

Full answer

Because all JavaScript callbacks share one thread, a callback that takes 500 ms makes every other request wait 500 ms. Nothing else can run while it works: not a timer, not a new connection, not a health check. In a busy API this looks like a sudden jump in latency for everyone.

Typical causes:

  • Synchronous APIs such as fs.readFileSync or execSync inside a request handler.
  • Large JSON.parse or JSON.stringify calls on megabyte-sized data.
  • A regular expression with catastrophic backtracking.
  • A long for loop (sorting, hashing, image or PDF work) over a large array.
  • Synchronous crypto such as pbkdf2Sync.

Ways to avoid it:

  1. Use the async version of every I/O API.
  2. Split a long loop into chunks and give control back between chunks with setImmediate.
  3. Move real CPU work to worker_threads or to a separate service or queue.
  4. Measure with the event loop delay histogram from perf_hooks or with a profiler, so you see the problem before users do.

Synchronous calls are fine at start-up, in CLI scripts and in build tools, because no one is waiting on the loop there.

javascript
const TOTAL = 60_000_000;

function blocking() {
  let sum = 0;
  for (let i = 0; i < TOTAL; i++) sum += i;
  return sum;
}

function chunked(done) {
  let sum = 0;
  let i = 0;
  function step() {
    const end = Math.min(i + 2_000_000, TOTAL);
    for (; i < end; i++) sum += i;
    if (i < TOTAL) setImmediate(step); // let other callbacks run between chunks
    else done(sum);
  }
  step();
}

function run(label, work) {
  return new Promise((resolve) => {
    let timerRanEarly = false;
    const finish = (sum) => {
      console.log(label, 'sum =', sum, '| 1 ms timer ran before the work finished:', timerRanEarly);
      resolve();
    };
    setTimeout(() => { timerRanEarly = true; }, 1);
    if (work === blocking) finish(blocking());
    else chunked(finish);
  });
}

(async () => {
  await run('blocking:', blocking);
  await run('chunked: ', chunked);
})();

The timer is only able to run during the chunked version. The numbers are fixed, so the output does not depend on machine speed. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): blocking: sum = 1799999970000000 | 1 ms timer ran before the work finished: false chunked: sum = 1799999970000000 | 1 ms timer ran before the work finished: true

Key points

  • One long synchronous task delays all other work in the process.
  • Common causes: sync APIs, huge JSON, bad regex, long loops, sync crypto.
  • Fixes: async APIs, chunking with setImmediate, worker threads, a queue.
  • Sync APIs are acceptable at start-up and in scripts.

Common mistakes

  • Using readFileSync or JSON.parse on large input inside a request handler.
  • Thinking that wrapping heavy work in a Promise or an async function makes it non-blocking. It still runs on the main thread.
  • Chunking with a very large chunk size, which still blocks for a long time.
  • Ignoring regular expression backtracking as a cause.

Follow-ups

  • How would you detect event loop lag in production?
  • Why does async/await not help with CPU-heavy work?
  • When would you pick chunking over a worker thread?

Tips

  • Say the key sentence: async does not mean parallel for JavaScript code.
  • Name the event loop delay metric (perf_hooks.monitorEventLoopDelay) to sound production-aware.
  • Give one safe use of a sync API to show balanced judgement.