The name validator on the Ratna's Kitchen PO form checks Dina in an instant. Then someone types a 40-letter name ending in an exclamation mark, and the server goes quiet: no other buyer can order. The regex hasn't failed; it just hasn't finished.
That is called ReDoS (Regular expression Denial of Service): one regex needs so long for one particular input that the program running it freezes. The browser tab hangs, or a server stops serving everyone. The cause is catastrophic backtracking. Picture being asked whether a piece of writing can be cut into valid words, and your method is to try every way of cutting it, one at a time. If the writing is valid, the first way works at once. If it isn't, you may only say "no" after trying them all: 4 letters have 8 ways to cut, 27 letters have 67 million. In this lesson we take apart why that name validator behaves like this, and how to write a safe one.
Backtracking: step back, then try another way
In the quantifier lesson you saw + take as much as it can, then step back when the rest of the pattern doesn't match. Stepping back is called backtracking. JavaScript's regex engine works like that: at every choice (how many letters + takes, take or skip ?, left or right |), it picks one and keeps going. When it gets stuck, it returns to the last choice and tries another. Only when every choice is used up does it answer false.
Usually there are few choices, so it's fast. Trouble starts when one text can be matched in many ways.
A risky pattern: ^(\w+\s?)+$
A validator for the customer's name: "one word or more, separated by spaces". The first pattern that comes to mind:
const risky = /^(\w+\s?)+$/;
const namesInChat = [...new Set(chat.match(/(?<=\] )[^:]+(?=:)/g))];
for (const name of namesInChat) {
console.log(name, risky.test(name));
}
// Ratna (Admin) false
// Dina true
// Bayu true
// Sari true
All fast. But look inside the group: \w+ then \s?. Because \s? may be empty, one word can be cut into several rounds of the group. Dina can be read 8 ways: [Dina], [Din][a], [Di][na], [Di][n][a], [D][ina], [D][in][a], [D][i][na], [D][i][n][a]. Between every two letters there's a gap, and each gap may be cut or not. So n letters have 2 to the power (n - 1) ways: 20 letters already have 524,288.
- When the name is valid, the first way (all letters in one
\w+) matches right through to$. Fast. - When it ends in
!, every way fails at the!. The engine doesn't know that, so it tries every way of dividing (every partition of) the letters before giving up. That's catastrophic backtracking.
Measuring: each letter doubles the time
Measure with performance.now(), and put on a brake so the measuring stops before it hangs:
const risky = /^(\w+\s?)+$/;
risky.test("Dina!"); // warm-up: the first call is always slower
for (let n = 18; n <= 27; n++) {
const name = "Dina" + "a".repeat(n - 4) + "!";
const start = performance.now();
const result = risky.test(name);
const ms = performance.now() - start;
console.log(n, "letters:", result, ms.toFixed(1), "ms");
if (ms > 500) break; // stop before it hangs
}
The output in Node 22, on one laptop:
18 letters: false 1.9 ms
19 letters: false 3.6 ms
20 letters: false 7.0 ms
21 letters: false 14.4 ms
22 letters: false 27.9 ms
23 letters: false 56.8 ms
24 letters: false 113.1 ms
25 letters: false 225.3 ms
26 letters: false 460.0 ms
27 letters: false 930.0 ms
Every one extra letter doubles the time: 18 letters 1.9 ms, 19 letters 3.6 ms. The numbers on your computer will differ, but the doubling stays. From it you can work out (not measure): 30 letters about 7 seconds, 40 letters about 2 hours.
While a regex runs, JavaScript does nothing else. In a browser, the tab freezes. On a Node.js server, every other request waits too. One person sending a 40-letter name ending in ! is enough to stop the server for everyone: that's the denial of service.
The safe version: ^\w+(?:\s\w+)*$
const safe = /^\w+(?:\s\w+)*$/;
console.log(safe.test("Dina"), safe.test("Cheese Sticks"), safe.test("Ratna (Admin)")); // true true false
console.log(safe.test("Dina" + "a".repeat(23) + "!")); // false, 0.0 ms
console.log(safe.test("Dina" + "a".repeat(99996) + "!")); // false, about 0.5 ms for 100,000 letters
\w+is one word, then(?:\s\w+)*: "a space, then a word", zero times or more.- Every letter has only one place: in the
\w+of the word being read. A space has only one place too: the\sat the start of the next word, because\wnever matches a space. - When it fails at the
!, the engine can only give letters back from\w+one by one, and each step fails at once. The time grows with the input's length (linear), not double per letter.
This pattern is safe, but \w in JavaScript is only A-Z, a-z, 0-9 and _. Real names such as José, Mary O'Brien and Anne-Marie are refused too. For real names, replace \w with the list "a letter of any language, an apostrophe, or a hyphen":
const name = /^[\p{L}'’-]+(?:\s[\p{L}'’-]+)*$/u;
console.log(name.test("José"), name.test("Mary O'Brien"), name.test("Anne-Marie")); // true true true
console.log(name.test("Ratna (Admin)")); // false
console.log(name.test("Dina" + "a".repeat(99996) + "!")); // false, about 1 ms
\p{L} needs the u flag. The shape is the same as the safe version: a space is not in the list, so every character still has one place.
Other risky patterns and their safe partners:
| Risky pattern | Why it's ambiguous | Safe version |
|---|---|---|
/^(a+)+$/ |
a quantifier inside a quantifier | /^a+$/ |
/^(\w+)+$/ |
the same, for any letter | /^\w+$/ |
/^(\w+\s?)+$/ |
\s? may be empty, so words can be cut anywhere |
/^\w+(?:\s\w+)*$/ |
/^(a|aa)+$/ |
both choices can match the same text | /^a+$/ |
The sign: a quantifier (+, *) inside a group that is repeated too, where the group's content can cut the same text in more than one way. The fix: drop the wrapper you don't need ((\w+)+ becomes \w+), or make each round start with something the previous round can't eat (\s before \w+).
Extra layers of safety
- Limit the input's length before the regex runs:
if (name.length > 50) return false;. But for an exponential pattern a limit of 50 doesn't help: 30 letters already take about 7 seconds. Fix the pattern first; the length limit is the second layer. - An engine without backtracking. RE2 and Go's
regexppackage (which works the RE2 way) are guaranteed linear; for Node there's there2package. The price: no backreference\1and no lookaround. Details in the lesson Regex Across Languages. - Features per language. Python 3.11 and later and PHP have atomic groups
(?>...)and possessive quantifiers such as\w++: once they match, they never give their text back, so^(?>\w+\s?)+$fails at once for 40 letters ending in!. JavaScript doesn't have them:new RegExp("^(?>\\w+\\s?)+$")throwsInvalid regular expression: /^(?>\w+\s?)+$/: Invalid group. PHP doesn't hang either: after thepcre.backtrack_limit(1,000,000 by default),preg_match('/^(\w+\s?)+$/', $input)returnsfalse, not0, andpreg_last_error_msg()holdsBacktrack limit exhausted.if (!preg_match(...))reads thatfalseas "no match", so check with=== false. - Never turn a user's input into a pattern with
new RegExp(input)without escaping it. Besides errors, the user can send a risky pattern.
This isn't just theory. Stack Overflow was down for 34 minutes (2016) when a whitespace-trimming regex met a post with about 20,000 spaces in a row, and Cloudflare went down worldwide for 27 minutes (2019) because one firewall rule held .*(?:.*=.*).
⚠️ Risky patterns that pass the tests, and tests that freeze the tab
- Testing only valid input. A valid input matches on the first try, so a risky pattern looks fast. Also test long inputs that fail at the end, such as
"a".repeat(25) + "!". ?or*inside a repeated group.(\w+\s?)+and(\w*)+let one text be cut many ways.- Relying on a length limit alone. A limit that is safe for an exponential pattern is too short for real names.
- Measuring without a brake. A loop that keeps adding letters will freeze the tab. Add
if (ms > 500) break. The Playground here stops code that runs longer than 3 seconds and prints Timeout.
TL;DR: ReDoS = a regex that hangs because of catastrophic backtracking: the engine steps back and tries every way of dividing (every partition of) the text before answering false. The trigger is an ambiguous quantifier inside a quantifier, such as /^(a+)+$/, /^(\w+)+$/ or the name validator /^(\w+\s?)+$/, plus a long input that fails at the end ("Dina" + "a".repeat(23) + "!"). Every extra letter doubles the time: 27 letters take almost 1 second, 40 letters about 2 hours. The fix: give every character only one way to be matched, for example /^(\w+)+$/ becomes /^\w+$/, and /^\w+(?:\s\w+)*$/ for words separated by spaces. Limit the input's length as a second layer, and for patterns from outside use a linear engine such as RE2. Always test failing inputs, and measure with a brake.
⚡ A regex that never finishes
Meaning: ReDoS is one regex taking so long on one particular input that the program running it freezes. The cause is catastrophic backtracking: the engine steps back and tries every way of dividing the text before it answers false.
⚡ A quantifier inside a quantifier
Write:
const risky = /^(\w+\s?)+$/;
risky.test("Dina" + "a".repeat(23) + "!");
Guess first: a 27-letter name ending in !. How long does it take?
Almost 1 second, and every extra letter doubles it: 40 letters take about 2 hours. \s? may be empty, so one word can be cut into many rounds of the group, and the engine tries them all.
Meaning: The sign is a quantifier inside a repeated group, such as /^(a+)+$/, /^(\w+)+$/ or /^(\w+\s?)+$/, plus a long input that fails at the end.
⚡ Give each letter one place
Write:
const safe = /^\w+(?:\s\w+)*$/;
console.log(safe.test("Dina" + "a".repeat(23) + "!")); // false, 0.0 ms
Meaning: Drop the wrapper you don't need (/^(a+)+$/ becomes /^a+$/), or start each round with something the round before can't eat, like \s before \w+.