Detecting Catastrophic Backtracking in Regex Engines
How to find catastrophic backtracking in regex via NFA ambiguity analysis, pump-string fuzzing, and CI gates before ReDoS hits production.

Underlined words are defined in the KBY Lexicon. Tap or click one to see what it means.
A single short, unauthenticated request can tie up a CPU core — not through volumetric flood, but through a validation regex that nobody has load-tested against pathological input. This is catastrophic backtracking: a worst-case exponential blowup in backtracking regex engines that turns a microsecond-scale string match into a CPU-pinned hang.
If your platform accepts user-supplied strings anywhere near a regular expression — header parsing, log ingestion, form validation, WAF rulesets — you have a latent denial-of-service vector sitting in plain sight. A diagnostic tool can find it before production does.
#The Bottleneck: Exponential-Time Regex Evaluation
Most language runtimes (PCRE, Python’s re, JavaScript’s RegExp, .NET’s Regex) implement backtracking virtual machines by default rather than true finite automata (.NET also offers an opt-in NonBacktracking mode). These engines support backreferences and lookaround by walking the pattern depth-first, and on failure, unwinding to try alternative paths. This gives enormous expressive power at the cost of a worst-case time complexity that is not linear in input length — it can be O(2^n) for pathological patterns.
The canonical trigger is a quantified group whose inner expression can match the same substring in multiple overlapping ways, nested inside an outer quantifier. Consider:
1const vulnerable = /^(a+)+$/;
2const input = "a".repeat(30) + "!";
3
4const start = process.hrtime.bigint();
5vulnerable.test(input);
6console.log(Number(process.hrtime.bigint() - start) / 1e6, "ms");Runtime roughly doubles with each additional “a”, so measure on your own engine starting with small values (for example 20 to 25) before increasing the count, and run the experiment on a test machine, never on a production host. The cost grows quickly because the engine is exploring an exponentially growing tree of ways to partition the “a” run between the inner and outer + quantifiers before finally failing against the trailing !. This is the exact mechanism behind several documented incidents referenced in the OWASP ReDoS advisory, and it is not an exotic edge case — it is a direct consequence of how backtracking VMs are architected.
#Architectural Breakdown: Why Backtracking Engines Fail
#Thompson NFA Simulation vs Backtracking VM
Engines such as RE2 and the Rust regex crate sidestep the problem entirely by using automata-based engines (Thompson NFA simulation and lazy DFAs) that track all active states simultaneously, guaranteeing matching time linear in input length for a given pattern. The trade-off is that backreferences and certain lookaround constructs become unrepresentable, because they require remembering which specific path led to a state rather than just which states are reachable. Backtracking engines choose the opposite trade-off: full expressive power, no complexity guarantee.
This is the architectural fork every platform team eventually has to reckon with when choosing a validation layer, and it belongs in the same category of decision as the request-routing and state-management choices discussed under architectural patterns more broadly — you are trading expressiveness for a worst-case bound, and that trade-off needs to be explicit rather than accidental.
#Ambiguity: EDA and IDA
The formal way to characterise catastrophic backtracking is through the degree of ambiguity of the pattern’s underlying automaton, a concept from the static ReDoS analysis literature (Weideman et al.). A pattern exhibits:
- Exponential Degree of Ambiguity (EDA) — a single state can be returned to through two or more distinct looping paths that consume the same string, so the number of ways to match grows exponentially with input length, causing worst-case exponential time. This is the
(a+)+class of vulnerability. - Infinite Degree of Ambiguity (IDA) — two distinct loops, on different states, are connected by a path and can both consume the same string, so the number of matching paths grows polynomially (often quadratic or cubic) with input length — still dangerous under sustained load but not an instant kill. An example is
a*a*. - Finite/None — no such overlapping loops; the number of ways to match is bounded regardless of input shape.
Detecting catastrophic backtracking, therefore, is not a matter of pattern-matching against a blocklist of “bad-looking” regexes. It requires building the automaton and proving whether an ambiguous, self-intersecting loop exists in it.

#Implementation Logic: Building the Detector
A production-grade catastrophic backtracking detector combines static automaton analysis with dynamic attack-string fuzzing, because static analysis alone produces false positives on patterns that are technically ambiguous but practically bounded by anchors or length limits elsewhere in the application.
#Step 1 — Parse to AST
Use a proper regex parser (for example regexp-tree or a hand-rolled recursive-descent parser) rather than string heuristics, so nested groups, alternations, and quantifiers are represented as a real tree.
#Step 2 — Thompson Construction
Compile the AST into an epsilon-NFA. Tag every transition with the AST node it originated from, which is essential later for pointing the developer at the exact offending sub-pattern.
#Step 3 — Self-Product Ambiguity Check
Construct the cross-product automaton of the NFA with itself. Search for a pair of distinct paths that start from the same state, consume an identical non-empty substring, and return to overlapping states within a quantified loop. A cycle satisfying this condition indicates an EDA loop — the structural signature of catastrophic backtracking.
#Step 4 — Attack String Synthesis
Once a vulnerable loop is located, generate a pump string automatically: a prefix that reaches the loop, a repeated “pump” segment that exploits the ambiguity, and a suffix engineered to force final failure (the failure is what forces the engine to exhaust every backtracking path rather than short-circuiting on first match).
#Step 5 — Timeout-Bounded Dynamic Verification
Execute the synthesised string against the real engine in a separate process under a hard timeout, increasing the pump length by one on each pass, and record each execution time. Check that the ratio between consecutive times stays roughly constant above 1 before declaring exponential behaviour; a single timeout is not proof, since polynomial patterns can also time out, so report a timeout alone as “suspected”.
#Code and Configuration
A simplified structural detector, ignoring full automaton construction for brevity, flags one common catastrophic backtracking shape — a quantifier nested inside a quantified group or another repetition. It does not detect quantified alternations with overlapping branches (for example (a|a)+) or overlapping character classes; those need the automaton-based check or the dynamic probe:

1const { parse } = require("regexp-tree");
2
3function findCatastrophicPatterns(ast) {
4 const findings = [];
5
6 function walk(node, parentQuantified) {
7 if (!node || typeof node !== "object") return;
8
9 if (node.type === "Repetition" && parentQuantified) {
10 // a quantifier inside a quantified group or repetition
11 findings.push({
12 type: "nested-quantifier",
13 offset: node.loc ? node.loc.start.offset : null
14 });
15 }
16
17 const nowQuantified = node.type === "Repetition" || parentQuantified;
18
19 if (node.expression) walk(node.expression, nowQuantified);
20 if (Array.isArray(node.expressions)) {
21 node.expressions.forEach(n => walk(n, nowQuantified));
22 }
23 if (node.left) walk(node.left, nowQuantified);
24 if (node.right) walk(node.right, nowQuantified);
25 }
26
27 walk(ast.body, false);
28 return findings;
29}
30
31console.log(findCatastrophicPatterns(parse(/^(a+)+$/, { captureLocations: true })));This structural pass is a first filter only. It will miss some vulnerable patterns (see above) and will flag some safe ones, so every finding should be confirmed dynamically and patterns it does not flag should not be assumed safe. The verification harness pumps the input and measures wall-clock growth. Each attempt runs in a child process that is killed on timeout, because a signal handler cannot interrupt Python’s C-level re loop until it returns:
1import multiprocessing as mp
2import re
3import time
4
5def _run(pattern, attack, q):
6 compiled = re.compile(pattern)
7 start = time.monotonic()
8 compiled.match(attack)
9 q.put(time.monotonic() - start)
10
11def _timed(pattern, attack, budget_s):
12 q = mp.Queue()
13 p = mp.Process(target=_run, args=(pattern, attack, q))
14 p.start()
15 p.join(budget_s)
16 if p.is_alive():
17 p.kill()
18 p.join()
19 return None
20 return q.get()
21
22def probe(pattern, pump_char, prefix, suffix, start_n=10, max_pump=40, budget_s=1.5):
23 times = []
24 for n in range(start_n, max_pump + 1):
25 attack = prefix + (pump_char * n) + suffix
26 elapsed = _timed(pattern, attack, budget_s)
27 if elapsed is None:
28 print(f"n={n:>3} TIMEOUT (>{budget_s}s) -- suspected super-linear growth")
29 break
30 times.append(elapsed)
31 print(f"n={n:>3} elapsed={elapsed:.4f}s")
32
33 ratios = [b / a for a, b in zip(times, times[1:]) if a > 1e-4]
34 if len(ratios) >= 3:
35 print("consecutive ratios:", [round(r, 2) for r in ratios])
36 print("roughly constant ratio above ~1.5 suggests exponential; "
37 "a ratio trending toward 1 suggests polynomial")
38 return times
39
40if __name__ == "__main__":
41 probe(r"^(a+)+$", "a", "", "!")Wire the two stages into a CI gate so no ambiguous pattern reaches production without an explicit override. The script names and flags below are hypothetical — the scripts above take no command-line arguments, so you would need to write wrappers that provide them. The allowlist file is the override mechanism: each entry should name the pattern, an owner and a justification, and be reviewed like any other code change:
1jobs:
2 regex-safety-scan:
3 runs-on: ubuntu-latest
4 steps:
5 - uses: actions/checkout@v4
6 - name: Install detector
7 run: npm ci --prefix tools/redos-scanner
8 - name: Static ambiguity scan (hypothetical CLI)
9 run: node tools/redos-scanner/scan.js --path src/ --allowlist tools/redos-scanner/allowlist.json
10 - name: Dynamic pump verification (hypothetical CLI)
11 run: python3 tools/redos-scanner/probe.py --budget 1.5 --report findings.json --allowlist tools/redos-scanner/allowlist.json
12 - name: Upload report
13 uses: actions/upload-artifact@v4
14 with:
15 name: redos-report
16 path: findings.jsonIntroduce the gate in report-only mode on one repository first, review the findings and tune the allowlist, and only then make it blocking. To undo, remove the job or switch it back to report-only.
#Failure Modes and Edge Cases
A detector built purely on structural heuristics will misfire in both directions. Character classes that appear to overlap syntactically ([a-z]+[a-zA-Z]+) are only polynomially ambiguous, and may be harmless once anchoring and input length limits are accounted for, producing false positives that erode developer trust in the tool. Conversely, ambiguity can be hidden behind indirection: a pattern assembled at runtime from configuration strings, or composed via RegExp constructor concatenation, will not appear as a literal in source and will slip past a purely static AST scan.
Named capture groups and atomic-group emulation via lookahead and backreference ((?=(...))\1) also confuse naive parsers, since the AST shape no longer maps cleanly onto a simple quantifier-over-quantifier pattern, yet the underlying ambiguity is identical. Patterns using \p{...} Unicode property escapes introduce another wrinkle: the effective alphabet size explodes, which changes the pump-string synthesis strategy because a single-character pump may not trigger the ambiguous branch at all.
The dynamic verification stage has its own failure mode: engines with internal memoisation (Ruby 3.2 and later, for example) can suppress catastrophic backtracking for specific pump characters while remaining vulnerable to a differently shaped attack string. A detector that only tries one pump character and declares the pattern safe on a negative result is providing false assurance — the probe harness should iterate across a small alphabet, not a single repeated character.
#Scaling and Security Trade-offs
- Static-only scanning is fast enough for pre-commit hooks (sub-second per file) but produces a non-trivial false-positive rate on legitimately safe but structurally ambiguous patterns, requiring an allowlist mechanism to avoid alert fatigue.
- Dynamic pump verification is expensive — each confirmed catastrophic backtracking case can consume the full timeout budget by design, so CI jobs must run probes in parallel worker processes with a hard kill (
SIGKILL) fallback, not justSIGALRM, since some backtracking states are unresponsive to signal delivery until the current C-level loop yields. A negative result is not a proof of safety. - Runtime mitigation via engine substitution (moving hot-path validation to RE2 or the Rust
regexcrate via FFI) eliminates the class of vulnerability entirely at the cost of losing backreference support — acceptable for input validation, unacceptable for text-processing pipelines that depend on backreferences for correctness. Pilot it on one validation path and compare results against the old engine before widening. - Runtime mitigation via request-level timeouts (wrapping match calls in a worker thread with a kill switch) bounds the blast radius per request but does not fix the underlying pattern, and under sustained attack still allows thread-pool exhaustion if the timeout is set conservatively high.
- Defence-in-depth combines both: CI-time static and dynamic detection to stop new catastrophic backtracking patterns from merging, plus a per-request evaluation timeout as the last line of defence against patterns that predate the tooling or arrive via third-party dependencies.
None of these controls are mutually exclusive, and in practice the CI gate catches many cases before they ship, while the runtime timeout absorbs whatever the static analysis inevitably misses. Treat the detector as a continuously tuned pipeline rather than a one-off audit — new catastrophic backtracking shapes surface every time a developer reaches for a “clever” nested quantifier under deadline pressure.
Evidence trail
Sources and verification
Primary documentation and external technical references used in this article.
About this page
Credited to
Dates
Published
Last updated
Recommended reading
More from KBY that goes with this article.
- Microsoft Intune error
0x800705b4: Autopilot self-deploying mode fails at Securing your hardware
2 min read


Was this useful?
Reports go to the site owner and are used to correct pages. Corrections are listed at /corrections.
New engineering tools, ready to use.
Receive new calculators, diagnostic tools, Engineering Labs and technical reference systems.
Comments
Add a thoughtful note on Detecting Catastrophic Backtracking in Regex Engines. Comments are checked for spam and held for moderation before appearing.