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:
- Rewrite the pattern to be unambiguous (^a+$). Avoid nested quantifiers.
- Limit the input length before matching (for example 254 characters for an email).
- Use a parser or a validation library instead of a custom regex.
- Use a linear-time engine (such as RE2 through a package) for untrusted patterns or input.
- Run risky work in a worker thread and terminate the worker after a time limit.
- 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.
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.