Thirty-one characters, eight seconds
Here is the result first; everything after this is explanation. The pattern below is under ten characters long and contains nothing that looks dangerous:
/^(a+)+$/
Match it against a run of a followed by one X. Because of the X, the match is guaranteed to fail. Vary the number of a from 20 to 30 — so the input is 21 to 31 characters — and time how long test() takes to come back:
const re = /^(a+)+$/;
for (let i = 0; i < 200; i++) re.test('a'.repeat(12) + 'X'); // warm-up, see the last section
for (let n = 20; n <= 30; n++) {
const s = 'a'.repeat(n) + 'X';
const t0 = performance.now();
re.test(s);
console.log(n, (performance.now() - t0).toFixed(1) + ' ms');
}
Measured on Node v22.17.1 / Apple M1 Pro / macOS 26.5.2, three runs per length, minimum taken:
a count |
Time | Ratio to previous row |
|---|---|---|
| 20 | 6.7 ms | — |
| 21 | 13.7 ms | 2.04 |
| 22 | 27.0 ms | 1.97 |
| 23 | 54.4 ms | 2.01 |
| 24 | 113.4 ms | 2.08 |
| 25 | 218.6 ms | 1.93 |
| 26 | 497.2 ms | 2.27 |
| 27 | 922.1 ms | 1.85 |
| 28 | 2051.5 ms | 2.22 |
| 29 | 4160.6 ms | 2.03 |
| 30 | 8101.1 ms | 1.95 |
Every extra a doubles the time. What makes that rule frightening is that it does not level off: extrapolating at the same rate, 40 a takes about 2.3 hours (8101.1 ms × 2¹⁰) and 50 a about 98 days (× 2²⁰). Those last two are extrapolations — I did not sit and wait — but the basis for extrapolating is that ratio column sitting steadily at 2.0.
A user typing ten extra letters into a form field is enough to turn one request into an incident.
Why exactly double
The premise first: JavaScript uses a backtracking engine, as do Java, Python, Ruby and PCRE. It matches by trying one path, and when that path fails, unwinding and trying another. (RE2, mentioned later, is the other kind — it does not backtrack.)
Faced with ^(a+)+$, a backtracking engine has to divide the run of a between two nested quantifiers: the inner a+ consumes a chunk each time round, the outer + decides how many chunks there are. The number of ways to cut n items into a sequence of non-empty chunks is 2ⁿ⁻¹. Twenty a gives over 520,000 arrangements; thirty gives over 530 million.
If the string could match, the engine would stop at the first arrangement that works. But the trailing X means $ can never line up, so every arrangement is pushed all the way to the end before being rejected. The engine has to exhaust all 530 million before it has earned the right to say “no match”. That ratio of 2.0 in the table is 2ⁿ⁻¹ projected onto a time axis — theory and measurement agree, which is not a coincidence.
The danger is failure, not success
This is the least intuitive part, and the part worth remembering. Give the same ^(a+)+$ input it can match:
- 30
a(matches): 0.000037 ms - 1,000
a(matches): 0.000401 ms - 10,000
a(matches): 0.003198 ms
All three use the same method — warm up, then average over many iterations, varying only the iteration count (200,000 for the first two, 20,000 for the last; the slower the case, the fewer repetitions needed for a stable number). Keeping the method identical and the significant figures generous both matter here: single-shot jitter and rounding are each large enough to distort the ratios below.
Cost on the success path grows roughly linearly with length: from 1,000 to 10,000 characters, a 10× increase in length costs 8.0× the time (0.000401 → 0.003198). The shortest case has the smallest absolute time but the highest cost per character, because at 30 a the real matching work has shrunk below the fixed overhead of the call itself. All three stay in microseconds, because a greedy quantifier swallows the whole string on its first attempt and succeeds immediately. No backtracking happens at all.
The comparison that matters is against the failure path, with inputs that differ by a single character: 30 a matches in 0.000037 ms; add one X — 31 characters — and it takes 8101 ms. One character of difference, 220 million times the work, eight orders of magnitude. (The failure figure is the measured value from the first table, taken by a different method; but when two numbers differ by eight orders of magnitude, methodology is not what separates them.)
The practical consequence: this bug will not show up in your tests. Test cases usually look like one valid sample (success path, fast) and one obviously invalid sample — an empty string, a few characters — which is also fast. The input shape that detonates it is specific: a long, almost-matching prefix with one character at the end that breaks the match. That shape does not appear in hand-written fixtures. It appears in production, where users paste half-finished logs and attackers construct it deliberately.
So catastrophic backtracking almost always makes its first appearance in production, and that first appearance is usually site-wide.
Three shapes, and how fast each one detonates
Recognising the danger is about shape, not experience. These three cover most real cases. I have included the measured growth order for each, because “can blow up” is not a binary — the speed varies enormously.
1. Nested quantifiers: (x+)+, (x*)*, (x+)*. The example above. Exponential, base 2. The signature is a quantified group wrapped in another quantifier.
2. A quantifier over alternatives that overlap: (a|a)*, (a|aa)+. The danger is not alternation itself but overlap — the same text being reachable through different combinations of branches, so one string has more than one decomposition. In (a|a)* the branches are literally identical. In (a|aa)+ they differ, but a run of a can be cut one at a time or two at a time, so again there are many decompositions, and on failure the engine tries all of them.
By contrast (a|ab)+ is also “a quantifier over alternation” and does not blow up: a and ab end in different characters, so every b in the string pins down exactly where ab must be cut. The decomposition is unique, leaving no search space. Fed 10,000 a plus an X — also a failure path — it averages 0.04 ms over 2,000 runs.
Back to the one that does blow up. Measured, ^(a|aa)+$ against n a plus an X:
a count |
Time | Ratio to previous row (per 2 extra a) |
|---|---|---|
| 24 | 0.7 ms | — |
| 26 | 1.9 ms | 2.71 |
| 28 | 5.0 ms | 2.63 |
| 30 | 13.1 ms | 2.62 |
| 32 | 34.5 ms | 2.63 |
| 34 | 89.5 ms | 2.59 |
| 36 | 234.6 ms | 2.62 |
| 38 | 615.8 ms | 2.62 |
| 40 | 1613.5 ms | 2.62 |
| 42 | 4247.5 ms | 2.63 |
Still exponential, but the base has changed. Decomposing n using parts of size 1 and 2 is counted by the Fibonacci numbers, which grow as φⁿ with φ = 1.618, so two extra a costs φ² = 2.618×. Apart from the shortest row — 0.7 ms, too small for the noise floor — the measured column sits at 2.62, matching theory to two decimal places.
A smaller base makes it more insidious, not less. At 40 a it is 1.6 seconds: that reads as “a bit slow”, not “broken”. Extrapolate at the same rate and 60 a is nearly 7 hours (4247.5 ms × 2.618⁹).
3. Adjacent greedy wildcards: .*.*, .*.*=.*. This one differs in kind from the first two. Measured, /.*.*=.*/ against n x with no equals sign anywhere, so failure is certain:
| Characters | Time | Ratio to previous row (length doubles) |
|---|---|---|
| 1,000 | 516.7 ms | — |
| 2,000 | 4106.4 ms | 7.95 |
| 4,000 | 32703.4 ms | 7.96 |
Double the length, eight times the work — that is cubic. Polynomial, not exponential. At 8,000 characters it projects to about 4.3 minutes (32703.4 ms × 7.96); I killed it rather than finish.
Polynomial sounds gentler than exponential, but look at the units on the horizontal axis. The first two shapes detonate at a few dozen characters. This one needs a few thousand bytes — and a few thousand bytes is an utterly ordinary size for an HTTP header or request body. The shape that causes large-scale outages is rarely the most violent one; it is the one that ordinary traffic can push past the threshold.
Cloudflare, 2 July 2019
There is a textbook example of that last sentence. On 2 July 2019, Cloudflare’s edge returned 502s globally for under half an hour, triggered by an update to a managed WAF rule.
The incident report names exactly this adjacent-greedy-wildcard shape; the simplified form it uses to explain the problem is written .*.*=.*. I am not reproducing the full rule here — quoting a regex from memory and getting one character wrong is just propagating misinformation, so read the official report if you want the original. The rule’s intent, blocking inline-JavaScript XSS, was sound. Its shape was not.
Two technical points are worth keeping. First, that WAF ran on Lua and PCRE; PCRE backtracks, a single runaway rule can saturate a CPU core, and nothing in that deployment would cut it off. Second, the rule skipped staged rollout and went to every machine at once, so every machine began burning CPU simultaneously, and the only remaining way to stop the bleeding was to disable the WAF globally.
Put that beside the magnitudes in the previous section and it is clear: cubic backtracking, at global scale, on request content entirely controlled by outsiders, does not need to be exponential to burn through a global network. The report: https://blog.cloudflare.com/details-of-the-cloudflare-outage-on-july-2-2019/
Fixes, most practical first
Rewrite the pattern to remove the ambiguity. This is the only real cure. Ambiguity here means one input having several decompositions the same pattern accepts. The safe equivalent of ^(a+)+$ is simply to drop the outer quantifier:
/^a+$/
Both accept exactly the same set of strings — “one or more a” — so the outer + never added expressive power, only an exponential number of ways to split the input. Measured against 100,000 a plus an X: 0.294 ms. A hundred thousand characters, about 28,000 times faster than the original managed on thirty-one — four orders of magnitude.
Narrow the wildcards. .* is backtracking fuel. If you want what precedes an equals sign, write [^=]* rather than .*; for content within a line, [^\n]*; inside quotes, [^"]*. Once narrowed, the engine fails immediately on wrong branches instead of swallowing the line and regurgitating it one character at a time. Anchors help too, but the two ends do different jobs: ^ eliminates an entire dimension of attempts — retrying from each later starting position — while $ does not reduce starting positions, it lets length-mismatched branches be rejected sooner rather than after the rest of the pattern has been tried.
Use an engine that does not backtrack. Go’s regexp (RE2) and Rust’s regex crate guarantee linear time, at the cost of backreferences and lookaround. On a server that trade is almost always worth taking. If any part of your pattern comes from user input or external configuration, a backtracking engine is the wrong tool.
Use atomic groups or possessive quantifiers. PCRE and Java support both — (?>...) is an atomic group, a++ a possessive quantifier; .NET supports atomic groups. The semantics are “once this part has matched, never give any of it back”, which deletes the backtracking points outright.
JavaScript has no atomic groups, but they can be simulated. Lookahead plus a backreference is equivalent: (?=(a+))\1 behaves like (?>a+). The lookahead greedily measures the longest run and captures it; the backreference then consumes exactly that, leaving no fork to return to. Measured, /^(?:(?=(a+))\1)+$/ against 10,000 a plus X: 0.010 ms, and it agrees with the original on both aaaa (true) and aaaaX (false). The cost is a capture group out of nowhere, renumbering every group after it, and total unreadability without a comment — so when ^a+$ will do, do that instead.
The last resorts are capping input length and running the match somewhere killable. The first works precisely because exponential growth cuts both ways: keep n small enough and 2ⁿ stays small. The second is what this site does, and is the next section.
Why it has to be a Web Worker, not setTimeout
The regex tester here runs matching inside a Web Worker, with a 1500 ms timer on the main thread that calls terminate() on the whole Worker when it fires.
The obvious question is why not run it on the main thread and use setTimeout for the timeout. The answer is that such a timeout never fires in time — not once. JavaScript is single-threaded; a setTimeout callback is queued, and it only gets to run after the current synchronous block finishes and control returns to the event loop. Regex matching is synchronous: during those eight seconds of backtracking the main thread never leaves the test() call. By the time the timer finally runs, the match has long since completed and the timeout check sees a finished result. AbortController is no help either — it cancels asynchronous operations and has nothing to say about synchronous code.
There is no other opening. JavaScript regexes have no timeout parameter, no step limit, no cancellation token; a match in progress cannot be interrupted from outside and cannot stop itself. The only reliable way to stop it is to kill the execution context, and in a browser the only context you can kill without taking the page with it is a Worker.
A few implementation details that were learned the hard way:
- A new Worker per run. A terminated Worker cannot be reused, so both the timeout path and the normal path must clean it up, as must component teardown.
- The Worker source is injected via
collectMatches.toString(), not written twice. That way unit tests cover the code that actually runs in production rather than a copy of it — and copies drift. - 200 ms debounce on input. Spawning a Worker per keystroke creates a crowd of short-lived threads, each of which may be running a half-typed pattern that happens to have a dangerous shape.
- The “risky” warning in the UI is a shape-level heuristic — regexes matching regexes, looking for the
(x+)+and(a|b)+families. It deliberately warns rather than blocks: whether a pattern explodes depends on the input, and deciding that statically is undecidable in general. The hint tells you where to look; the timeout is what protects you.
The limits of this approach are worth stating plainly. For the 1.5 seconds before the Worker is killed it really is saturating a CPU core — just not the main thread’s, so the page still scrolls and edits. The heuristic has both false negatives and false positives. The timeout is wall-clock, so on a slow device a legitimate large input can be killed. This solves one specific problem — the page freezing with no recourse but closing the tab — and nothing more.
The trap waiting if you measure this yourself
Run the snippet at the top of this article and your first set of numbers will probably be nonsense. My first run, with no warm-up, gave 35.1 ms at 20 a and 13.5 ms at 21 — more characters, less time, with the curve inverted from the very first row.
The cause is that the first call pays for regex compilation and JIT warm-up, and that fixed cost is larger than the real work at the shortest length, drowning the early rows completely. Add a round of warm-up on short input, take the minimum of three runs per length, and the curve resolves into the clean doubling above. The lesson generalises to any microbenchmark: when the quantity you are measuring is small, the measurement apparatus is your largest source of noise.