Skip to the content

Lesson 190 of 296

Blocking vs non-blocking code

What you will learn

  • What blocking the event loop means, and how to recognise it
  • Sync vs async APIs
  • CPU-heavy work and how to handle it
  • Dangerous patterns: big JSON, regular expressions, sync crypto
  • Measuring event loop delay
On this page

Blocking the event loop

Blocking means your JavaScript keeps the main thread busy, so the event loop cannot run anything else: no other request is answered until it finishes.

TypeScript
import { createServer } from "node:http";

function slowFibonacci(n: number): number {
  return n < 2 ? n : slowFibonacci(n - 1) + slowFibonacci(n - 2);
}

export const blockingServer = createServer((req, res) => {
  if (req.url === "/fib") {
    const result = slowFibonacci(40);
    res.end(String(result));
    return;
  }
  res.end("ok");
});

While one user calls /fib (about a second of CPU work), a request to / from another user waits, even though it needs almost no work. With many users, the whole server freezes.

Sync vs async APIs

Node.js offers many functions in two forms:

Blocking (sync)Non-blocking (async)
fs.readFileSync(path)await fs.promises.readFile(path)
crypto.pbkdf2Sync(...)crypto.pbkdf2(..., callback) or a promisified version
zlib.gzipSync(buffer)zlib.gzip(buffer, callback)

Rule: inside request handlers, use the async versions. Sync versions are fine at start-up (reading config before the server starts) and in short scripts.

What blocks in practice

CauseFix
Heavy calculations (image processing, big reports, data crunching)Worker threads (Lesson 192), a background job queue (Lesson 204), or another service
JSON.parse / JSON.stringify of very large data (tens of MB)Avoid huge payloads; paginate (Lesson 197); stream (Lesson 191)
Sorting or looping over huge arrays in a requestDo it in the database; paginate
Badly written regular expressions on user input"ReDoS": a pattern like /^(a+)+$/ can take exponential time on crafted input. Keep patterns simple, limit input length, validate with libraries
Sync file or crypto functions in handlersUse the async versions
Infinite or very long loopsFix the bug; add limits

Splitting work into chunks

For a moderately long task, you can process in batches, giving the event loop a chance to handle other callbacks between batches:

TypeScript
export async function sumInChunks(values: number[], chunkSize = 10_000): Promise<number> {
  let total = 0;
  for (let i = 0; i < values.length; i += chunkSize) {
    const end = Math.min(i + chunkSize, values.length);
    for (let j = i; j < end; j++) total += values[j]!;
    await new Promise<void>((resolve) => setImmediate(resolve));
  }
  return total;
}

Each await of a setImmediate promise lets pending I/O callbacks run before the next chunk. It does not make the work faster; it keeps the server responsive. For truly heavy work, use worker threads.

Measuring event loop delay

Node.js can measure how late the event loop is running, a key health metric for a Node.js service:

TypeScript
import { monitorEventLoopDelay } from "node:perf_hooks";

export function startLoopMonitor() {
  const histogram = monitorEventLoopDelay({ resolution: 20 });
  histogram.enable();
  return () => {
    const p99Ms = histogram.percentile(99) / 1e6;
    histogram.reset();
    return p99Ms;
  };
}

If the 99th percentile delay is high (for example over 100 ms), something is blocking. Tools such as Clinic.js and the --cpu-prof flag find the culprit.

How to say it in an interview

"Blocking means synchronous JavaScript keeps the main thread busy, so no other request or callback can run. Typical causes are CPU-heavy calculations, huge JSON parsing, catastrophic regular expressions and sync APIs like readFileSync or pbkdf2Sync inside handlers. I use async APIs in request paths, keep sync calls for start-up, paginate and stream large data, and move heavy work to worker threads or a job queue. I monitor event loop delay to detect blocking in production."

Key words

WordMeaning
BlockingKeeping the main thread busy so nothing else runs
CPU-boundLimited by calculation speed, not waiting
I/O-boundLimited by waiting for network or disk
ReDoSDenial of service caused by a slow regular expression
Event loop delayHow late the loop runs scheduled work; a health metric

Now prove it

This lesson is complete when you pass the quiz and all three practice levels.