← Back to Node.js, page 6

nodejs-0119 · Hard senior

Latency spikes hit every endpoint when one particular input arrives. How can a regular expression block the event loop, and how do you diagnose and fix it?

A regular expression with nested quantifiers, such as /^(a+)+$/, can take exponential time on a near-match input. JavaScript regex runs on the main thread, so one request freezes timers, I/O and every other request. Diagnose with event loop delay metrics and a CPU profile, then fix by using a linear pattern, limiting input length, a safe regex engine, or running risky matching in a worker with a time limit.

Full answer

The scenario: p99 latency jumps to seconds, CPU for one process is at 100 percent, and all endpoints are slow at once, not only one route. Logs show nothing wrong. A single request is blocking the loop.

Why a regex can do this:

  • V8 uses a backtracking engine. For a pattern like (a+)+$ on aaaa...ab, the engine tries every way to split the a's before it fails. Time grows exponentially with the input length: about 2 to the power n.
  • The match runs synchronously on the main thread, so nothing else (timers, sockets, other requests) runs meanwhile.
  • Danger signs: nested quantifiers (a+)+, (a|aa)+, (.) , alternations that overlap, and patterns applied to user input without length limits. Email, URL and 'validate everything' regexes are common sources.

Diagnosis:

  • Track event loop delay (monitorEventLoopDelay) and alert on its p99 and max.
  • Take a CPU profile (node --cpu-prof, or the inspector) during the spike. The hot frame is the RegExp exec or the function calling it.
  • Log the length and a hash of inputs for slow requests. Add timing around suspicious regex calls.

Fixes, in order of preference:

  1. Rewrite the pattern to be unambiguous (^a+$). Avoid nested quantifiers.
  2. Limit the input length before matching (for example 254 characters for an email).
  3. Use a parser or a validation library instead of a custom regex.
  4. Use a linear-time engine (such as RE2 through a package) for untrusted patterns or input.
  5. Run risky work in a worker thread and terminate the worker after a time limit.
  6. Add a regex test with an evil input to the test suite and a lint rule that detects unsafe patterns.

Node regexes have no built-in timeout, so prevention matters more than reaction.

javascript
const { Worker } = require('node:worker_threads');
const { performance } = require('node:perf_hooks');

const evilInput = 'a'.repeat(26) + 'b';

function lagOf(work) {
  // Schedule a 10 ms timer, run the work synchronously, and measure how late the timer is.
  return new Promise((resolve) => {
    const start = performance.now();
    setTimeout(() => resolve(performance.now() - start - 10), 10);
    work();
  });
}

async function main() {
  const lag1 = await lagOf(() => /^(a+)+$/.test(evilInput));
  console.log('nested quantifier delays the timer by more than 100 ms:', lag1 > 100);

  const lag2 = await lagOf(() => /^a+$/.test(evilInput));
  console.log('linear pattern delays the timer by less than 20 ms:', lag2 < 20);

  // Run the dangerous pattern in a worker and stop it after 50 ms.
  const worker = new Worker(`
    const { parentPort, workerData } = require('node:worker_threads');
    parentPort.postMessage(/^(a+)+$/.test(workerData));
  `, { eval: true, workerData: evilInput });
  const start = performance.now();
  const outcome = await Promise.race([
    new Promise((resolve) => worker.once('message', (ok) => resolve('finished: ' + ok))),
    new Promise((resolve) => setTimeout(() => resolve('timed out'), 50)),
  ]);
  await worker.terminate();
  console.log('worker result:', outcome);
  console.log('main thread stayed responsive (took under 300 ms):', performance.now() - start < 300);
}
main();

The same input is tested with a bad pattern, a good pattern and a bad pattern inside a worker with a time limit. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): nested quantifier delays the timer by more than 100 ms: true linear pattern delays the timer by less than 20 ms: true worker result: timed out main thread stayed responsive (took under 300 ms): true

Key points

  • Nested quantifiers can make regex time exponential.
  • The match runs on the main thread and freezes everything.
  • Event loop delay and CPU profiles point to the culprit.
  • Fix with a linear pattern and an input length limit.
  • A worker with terminate() can enforce a time limit.

Common mistakes

  • Validating user input with a complicated regex and no length limit.
  • Looking for the problem in the database instead of the CPU profile.
  • Believing that async code makes a regex non-blocking.
  • Adding a timeout around the request and expecting it to stop the regex.
  • Copying an email regex from the internet without testing evil input.

Follow-ups

  • How does RE2 avoid exponential time?
  • How would you alert on this in production?
  • How can a ReDoS attack be rate limited at the edge?

Tips

  • Describe the symptom as 'every endpoint slow at once'.
  • Explain backtracking in one sentence.
  • Give the fix list in order.