Catastrophic Backtracking & Performance
Most regexes run in a blink. But a badly shaped pattern can take seconds, minutes or years on input only a few dozen characters long — freezing a browser tab or taking down a server. This is called catastrophic backtracking, and attacks that exploit it are known as ReDoS (Regular expression Denial of Service).
How backtracking works
JavaScript, Python, Java, .NET, PCRE and Ruby use backtracking engines. When part of a pattern can match in several ways, the engine picks one, continues, and — if the rest fails — comes back to try the next way. Usually there are only a few choices. Trouble starts when the number of ways grows exponentially.
The classic bad pattern
^(a+)+$ asks for "one or more groups of one or more as" — then the end. On aaaa it matches instantly. But on aaaa…ab, the final b makes every attempt fail, and the engine tries every possible way to split the as between the inner and outer +. For n letters that is about 2ⁿ ways.
How many ways are there? Each of the n − 1 gaps between neighbouring as can either be a split point or not, so there are 2ⁿ⁻¹ ways to cut the run into groups — and the engine tries them all before giving up. This program prints that count (rather than timing the regex, which would vary from machine to machine):
for (const n of [5, 10, 20, 30, 40]) {
const ways = 2 ** (n - 1);
console.log(`${String(n).padStart(2)} letters: ${ways.toLocaleString("en-US")} ways to try`);
} 5 letters: 16 ways to try
10 letters: 512 ways to try
20 letters: 524,288 ways to try
30 letters: 536,870,912 ways to try
40 letters: 549,755,813,888 ways to try
Each extra a doubles the work. If you'd like to feel it, paste this into your browser's developer console (not the playground) and increase n slowly:
const n = 24;
console.time("regex");
/^(a+)+$/.test("a".repeat(n) + "b");
console.timeEnd("regex");At around 30 letters it takes seconds; at 40 it would run for many minutes.
Recognising dangerous shapes
The warning signs are nested quantifiers or overlapping alternatives that can match the same text in many ways, followed by something that can fail:
| Dangerous | Why | Safer |
|---|---|---|
(a+)+ |
inner and outer + split the same as |
a+ |
(\w+\s?)*$ |
\s? is optional, so words can be split anywhere |
(?:\w+\s)*\w*$ or simply [\w\s]*$ |
(a|aa)* |
both alternatives match the same text | a* |
(.*,)* |
. overlaps with , |
(?:[^,]*,)* |
\d+\d+\d+x |
adjacent quantifiers over the same characters | \d{3,}x |
The fix is always the same idea: make sure there is only one way to match any given piece of text.
Rewrite: make the choices exclusive
A CSV-ish line pattern written lazily, ^(.*,)*end$, explodes on long lines that don't end with end. Using a negated class removes the ambiguity — each field can only stop at a comma:
const line = "a,".repeat(40) + "x";
console.log(/^(?:[^,]*,)*end$/.test(line)); // fails instantly
console.log(/^(?:[^,]*,)*end$/.test("a,b,end"));false
true
Other performance tips
| Tip | Example |
|---|---|
| Anchor when you can | ^ERROR lets the engine fail fast on lines that don't start with it |
Prefer specific classes to .* |
"[^"]*" instead of ".*?" |
| Put the most likely alternative first | (?:com|net|org) ordered by frequency |
| Compile once, reuse | create the RegExp outside loops |
| Limit input size | reject a 1 MB "email address" before matching |
| Avoid backreferences in hot paths | they prevent many optimisations |
Atomic groups and possessive quantifiers
Some engines let you forbid backtracking into a part of the pattern:
| Feature | Syntax | Supported in |
|---|---|---|
| Atomic group | (?>...) |
Java, .NET, PCRE, Ruby, Python 3.11+ |
| Possessive quantifier | a++, a*+ |
Java, PCRE, Python 3.11+ |
JavaScript has neither. A known trick emulates an atomic group with a lookahead and a backreference: (?=(a+))\1 — the lookahead captures greedily, and the backreference consumes exactly that text with no way to give any back.
/^\d+5/
123451 match
#1 "12345" at index 0
The ordinary \d+ gives back the final 5 so that the literal 5 can match. The emulated atomic version grabs all digits and refuses to give any back, so it fails:
/^(?=(\d+))\1(?:5)/
12345No match
Linear-time engines
RE2 (Google), Go's regexp and Rust's regex crate use automata instead of backtracking, guaranteeing time proportional to the input length. The price: no backreferences and no lookarounds. When you must run patterns supplied by users, a linear-time engine is the safe choice.
Tip: Never run a regex written by an untrusted user on a backtracking engine without a timeout. .NET has
Regextimeouts built in (matchTimeout); in JavaScript you would run the match in a Worker you can terminate.
Test yourself
Which pattern is prone to catastrophic backtracking?
^\d+$^(\d+)+$^[a-z]*$^\w{3}$
Why are Go's regexp and Rust's regex immune to ReDoS?
- They run on multiple threads
- They use automata with linear-time guarantees
- They limit input to 1 KB
- They cache results
What is a good general fix for an ambiguous pattern?
- Add the
gflag - Make sure each piece of text can be matched in only one way
- Wrap it in another group
- Use
.*more