ReDoS in Three Engines: PHP Gives Up, Python Never Does, and Node Freezes Everything
I ran the textbook catastrophic regex through PCRE in PHP 8.6, Python 3.15's re and V8 in Node 26. Python took 2.5 seconds on a 27-character string and kept doubling, Node froze its event loop, and PHP stopped in 2 ms by returning false, which turned a deny rule into an allow rule.
A regular expression looks like a declaration: this is what a valid email address looks like. In PHP, Python and JavaScript, it's actually a program, run by a backtracking engine that will try every way a pattern can match before it admits that it doesn't. Most patterns finish in microseconds. A few, usually with a quantifier nested inside another quantifier, take time that doubles with every extra character of the right input. That's Regular Expression Denial of Service, ReDoS, and it has taken down real services, from Stack Overflow in 2016 to Cloudflare in 2019, with no exploit beyond a long string.
The three languages fail in three different ways. One is slow, one is a stall that takes down the whole process, and one is a security decision you didn't know you'd made. I ran the same pattern through all three to show each failure, then tested the defenses each one gives you.
How ReDoS Hits PHP, Python and Node Differently
The pattern is the canonical example, ^(a+)+$, against a string of as that ends in !. The ! means it can never match, but the engine only finds that out after trying every way to divide the as between the inner and outer +. For a string of n as, that's on the order of 2^n attempts.
These are the scripts. Python:
import re, sys, time
PATTERN = re.compile(r"^(a+)+$") # nested quantifier: the textbook catastrophic case
print("Python", sys.version.split()[0])
for n in (16, 18, 20, 22, 24, 26):
s = "a" * n + "!" # almost matches, then fails at the last character
t = time.perf_counter()
m = PATTERN.match(s)
print(f"n={n:<3} match={m is not None!s:<6} {(time.perf_counter() - t) * 1000:10.1f} ms")
SAFE = re.compile(r"^(?:a++)$") # possessive quantifier (3.11+): no backtracking into the group
t = time.perf_counter(); SAFE.match("a" * 100_000 + "!")
print(f"possessive a++, n=100000: {(time.perf_counter() - t) * 1000:8.3f} ms")
PHP:
<?php
echo "PHP ", PHP_VERSION, " PCRE ", PCRE_VERSION, " jit=", ini_get('pcre.jit'), " backtrack_limit=", ini_get('pcre.backtrack_limit'), "\n";
foreach ([16, 20, 24, 26, 28, 30] as $n) {
$s = str_repeat("a", $n) . "!";
$t = hrtime(true);
$r = preg_match('/^(a+)+$/', $s);
printf("n=%-3d preg_match=%-6s %8.1f ms %s\n", $n, var_export($r, true), (hrtime(true) - $t) / 1e6, preg_last_error_msg());
}
Node:
console.log("Node", process.version, "V8", process.versions.v8);
const re = /^(a+)+$/;
for (const n of [16, 18, 20, 22, 24, 26]) {
const s = "a".repeat(n) + "!";
const t = performance.now();
const m = re.test(s);
console.log(`n=${String(n).padEnd(3)} match=${String(m).padEnd(6)} ${(performance.now() - t).toFixed(1).padStart(10)} ms`);
}
The results:
Python 3.15.2
n=16 match=False 2.0 ms
n=18 match=False 7.7 ms
n=20 match=False 30.9 ms
n=22 match=False 126.2 ms
n=24 match=False 624.9 ms
n=26 match=False 2512.2 ms
possessive a++, n=100000: 0.118 ms
PHP 8.6.0 PCRE 10.44 2024-06-07 jit=1 backtrack_limit=1000000
n=16 preg_match=0 1.4 ms No error
n=20 preg_match=false 1.7 ms Backtrack limit exhausted
n=24 preg_match=false 1.6 ms Backtrack limit exhausted
n=26 preg_match=false 1.7 ms Backtrack limit exhausted
n=28 preg_match=false 1.7 ms Backtrack limit exhausted
n=30 preg_match=false 2.3 ms Backtrack limit exhausted
validator sees match? false | preg_last_error_msg(): Backtrack limit exhausted
PHP 8.6.0 PCRE 10.44 2024-06-07 jit=0 backtrack_limit=1000000
n=16 preg_match=0 2.1 ms No error
n=20 preg_match=false 11.2 ms Backtrack limit exhausted
n=24 preg_match=false 11.2 ms Backtrack limit exhausted
n=26 preg_match=false 13.2 ms Backtrack limit exhausted
n=28 preg_match=false 15.7 ms Backtrack limit exhausted
n=30 preg_match=false 15.9 ms Backtrack limit exhausted
validator sees match? false | preg_last_error_msg(): Backtrack limit exhausted
Node v26.13.1 V8 14.6.202.34-node.40
n=16 match=false 4.9 ms
n=18 match=false 3.0 ms
n=20 match=false 10.9 ms
n=22 match=false 42.8 ms
n=24 match=false 168.5 ms
n=26 match=false 413.0 ms
| n (a's before the "!") | Python 3.15 re |
Node 26 (V8 irregexp) | PHP 8.6 PCRE (JIT) |
|---|---|---|---|
| 16 | 2.0 ms | 4.9 ms | 1.4 ms, returns 0 |
| 20 | 30.9 ms | 10.9 ms | 1.7 ms, returns false |
| 22 | 126.2 ms | 42.8 ms | โ |
| 24 | 624.9 ms | 168.5 ms | 1.6 ms, false |
| 26 | 2,512 ms | 413 ms | 1.7 ms, false |
| 30 | (โ40 s, extrapolated) | (โ7 s, extrapolated) | 2.3 ms, false |
Python and Node show textbook exponential growth: every two extra characters multiply the time by about four. A 40-character input would run for hours. PHP stays flat at about 2 ms, because it gives up.
We recommend reading CVE-2025-62718: Critical Axios SSRF Vulnerability Explained to continue reading our selection of content. Untrusted input reaching a library's parser is how most Node incidents start, and the Axios case shows the pattern in full.
CVE-2025-62718: Critical Axios SSRF Vulnerability Explained A critical SSRF flaw in Axios was used in a North Korean supply chain attack. Here's what it does and how to patch it today. SudoSecurity ยท Santhdium
Python: Correct, Patient and Single-Threaded
Python's re module has no backtracking limit and no timeout. It will find the correct answer eventually. With the GIL, a request handler stuck in a regex holds a thread and its share of the interpreter, and in an asyncio app it holds the entire event loop. Twenty-six characters cost 2.5 seconds of CPU per request. Ten such requests per second will saturate any normal worker pool.
What Python does give you is the syntax to write patterns that can't backtrack. Since 3.11, re supports possessive quantifiers (a++, *+) and atomic groups ((?>...)). The last line of the Python output above is the possessive version against 100,000 characters: 0.118 ms. A possessive quantifier grabs what it matches and never gives any of it back, so there's nothing to retry.
The third-party regex module goes further. It has a timeout parameter, and it also handled both catastrophic patterns quickly on its own:
import time
import regex # third-party "regex" module, not the stdlib re
for pattern in (r"^(a+)+$", r"x(a+)+y|<script"):
s = "x" + "a" * 40 + " <script>" if "script" in pattern else "a" * 40 + "!"
t = time.perf_counter()
try:
m = regex.search(pattern, s, timeout=0.1)
print(f"{pattern:<20} result={m is not None!s:<6} {(time.perf_counter() - t) * 1000:8.1f} ms")
except TimeoutError as e:
print(f"{pattern:<20} TimeoutError: {e} after {(time.perf_counter() - t) * 1000:.1f} ms")
^(a+)+$ result=False 0.2 ms
x(a+)+y|<script result=True 0.9 ms
The timeout never fired, because regex 2026.11.23 avoided the blowup entirely, including on the alternation pattern you'll see in the PHP section that took stdlib re 600 ms. That's no guarantee for every pattern, so set the timeout anyway. It's the only Python engine with one.
Node: One Regex, Whole Process
V8's numbers are about 6x faster than Python's, which doesn't help much. Node runs your JavaScript on one thread, so a 400 ms regex isn't a slow request. It's 400 ms during which no other request on that process gets anything done: no timers, no I/O callbacks, no health checks. It's the same failure mode as the blocking-call test elsewhere in this series, and the outcome is the same: one bad input can take down a process that was handling thousands of good ones.
V8 has an answer that most Node developers have never heard of: a non-backtracking engine, behind flags. With --enable-experimental-regexp-engine, the l flag on a regex sends it to a linear-time engine:
// Run with: node --enable-experimental-regexp-engine redos-linear.mjs
const linear = new RegExp("^(a+)+$", "l"); // 'l' = V8's linear-time engine
for (const n of [26, 100_000]) {
const s = "a".repeat(n) + "!";
const t = performance.now();
const m = linear.test(s);
console.log(`linear engine n=${n}: match=${m} ${(performance.now() - t).toFixed(3)} ms`);
}
try { new RegExp("^(a+)\\1$", "l"); } catch (e) { console.log("backreference with 'l':", e.name, "-", e.message); }
linear engine n=26: match=false 0.027 ms
linear engine n=100000: match=false 10.618 ms
backreference with 'l': SyntaxError - Invalid regular expression: /^(a+)\1$/l: Cannot be executed in linear time
The same catastrophic pattern ran in 0.027 ms at n=26 and in 10.6 ms against 100,000 characters. The trade-off is in the last line: features that need backtracking, like backreferences, are rejected with "Cannot be executed in linear time."
There's a second flag that needs no code change. --enable-experimental-regexp-engine-on-excessive-backtracks makes V8 fall back to the linear engine automatically after --regexp-backtracks-before-fallback backtracks (50,000 by default):
Node v26.13.1 V8 14.6.202.34-node.40
n=16 match=false 1.6 ms
n=18 match=false 0.4 ms
n=20 match=false 0.4 ms
n=22 match=false 0.3 ms
n=24 match=false 0.4 ms
n=26 match=false 0.4 ms
Every n ran in under 2 ms. Both flags are marked experimental in node --v8-options, and they belong to V8, not to Node's stable API, so test before you ship them. For untrusted patterns or very hot paths, the re2 npm package (Google's RE2, linear time by design) is the established option.
PHP: Fast Failure, and a Security Decision
PCRE, the engine behind preg_*, counts backtracking steps and stops at pcre.backtrack_limit, 1,000,000 by default. Hit the limit and preg_match() doesn't throw. It returns false and sets an error you have to go and ask for:
PHP 8.6.0 PCRE 10.44 2024-06-07 jit=1 backtrack_limit=1000000
n=16 preg_match=0 1.4 ms No error
n=20 preg_match=false 1.7 ms Backtrack limit exhausted
n=24 preg_match=false 1.6 ms Backtrack limit exhausted
n=26 preg_match=false 1.7 ms Backtrack limit exhausted
n=28 preg_match=false 1.7 ms Backtrack limit exhausted
n=30 preg_match=false 2.3 ms Backtrack limit exhausted
From a DoS point of view, that's the best behavior of the three: 2 ms whatever the input. JIT off was slower, about 16 ms, but just as bounded. The problem is what false means in PHP code. false is falsy, just like 0, so if (preg_match(...)) treats "the engine gave up" exactly like "no match." For a validation rule that's annoying. For a deny rule, it's a bypass:
<?php
// A deny rule: block any input containing "<script". The first alternative is a badly written extra rule.
$deny = '/x(a+)+y|<script/i';
$input = "x" . str_repeat("a", 30) . " <script>";
$r = preg_match($deny, $input);
echo "preg_match returned: ", var_export($r, true), " (", preg_last_error_msg(), ")\n";
echo (preg_match($deny, $input) ? "BLOCKED" : "allowed"), " <- if (preg_match(...)) treats the error as no match\n";
// Fail closed: treat an engine error as a match.
function matchesOrFails(string $pattern, string $subject): bool {
$r = preg_match($pattern, $subject);
if ($r === false) {
throw new RuntimeException("regex failed: " . preg_last_error_msg());
}
return $r === 1;
}
try { matchesOrFails($deny, $input); } catch (RuntimeException $e) { echo "fail-closed: ", $e->getMessage(), "\n"; }
preg_match returned: false (Backtrack limit exhausted)
allowed <- if (preg_match(...)) treats the error as no match
fail-closed: regex failed: Backtrack limit exhausted
The input clearly contains <script. The rule says to block it. But the first alternative, a badly written extra check, burned through the backtrack limit before PCRE reached the <script alternative, so preg_match returned false and the request went through. Python's re gets the right answer for the same rule and input. It just takes 606 ms to do it.
The fix is to fail closed. Check === false (or preg_last_error() !== PREG_NO_ERROR) and treat an engine error as a match, or as a rejected request. Never as a pass. I'd wrap every security-relevant preg_match in a helper like matchesOrFails() above and ban bare if (preg_match(...)) on untrusted input in code review.
We recommend reading php2shell: The PHP Bug That Fires Before Your Code Runs to continue reading our selection of content. Input that turns PHP's own behavior against you is the theme of php2shell too, from a very different angle.
php2shell: The PHP Bug That Fires Before Your Code Runs php2shell (CVE-2026-109618/109619) is a 9.2 PHP RCE firing during request setup, before your code runs. Versions, mitigations, KEV status. SudoSecurity ยท Santhdium
Writing Patterns That Can't Blow Up
The engines differ, but the defenses at the pattern level are the same everywhere:
- No nested quantifiers over the same characters.
(a+)+,(\w+\s?)*and(.*)*are the shapes to look for. Rewrite them so each character can be matched in only one way. - No overlapping alternation inside a repeat.
(a|aa)+and(\d|\d\d)+give the engine many ways to split the same input. - Use possessive quantifiers or atomic groups where the engine supports them. PCRE and Python's
re(3.11+) do. JavaScript doesn't. - Anchor and bound everything.
^\d{1,10}$instead of\d+. - Limit input length before the regex runs. A 40-character cap on a username field makes even a bad pattern survivable. A regex over a 2 MB request body never is.
- Don't run user-supplied patterns on a backtracking engine. Use RE2 (the
re2npm package, Python bindings, orgoogle/re2through FFI in PHP) or V8's linear engine.
Catching It in CI: Two Static Checkers Compared
Most ReDoS bugs are visible in the pattern itself, so they can be caught before deploy. I ran two npm checkers over the patterns from this article plus some common real-world shapes: safe-regex2 5.1.2, a fast heuristic that measures "star height," and recheck 4.6.2, which analyzes the pattern's automaton:
// Run two static ReDoS checkers over the patterns from this article plus a few common real-world shapes.
import safeRegex from "safe-regex2";
import { checkSync } from "recheck";
const patterns = [
"^(a+)+$", // the textbook case
"x(a+)+y|<script", // the deny rule from the PHP section
"^(\\w+\\s?)*$", // "words separated by spaces"
"^([a-zA-Z0-9._-]+)*@example\\.com$",
"^\\d{1,10}$", // bounded, safe
"^[a-z0-9-]{3,32}$", // a username rule, safe
"(\\d|\\d\\d)+x", // overlapping alternation
];
console.log("pattern".padEnd(40), "safe-regex2".padEnd(12), "recheck");
for (const p of patterns) {
const r = checkSync(p, "");
console.log(p.padEnd(40), (safeRegex(p) ? "safe" : "UNSAFE").padEnd(12), r.status === "vulnerable" ? `vulnerable (${r.complexity.type})` : r.status);
}
pattern safe-regex2 recheck
^(a+)+$ UNSAFE vulnerable (exponential)
x(a+)+y|<script UNSAFE vulnerable (exponential)
^(\w+\s?)*$ UNSAFE vulnerable (exponential)
^([a-zA-Z0-9._-]+)*@example\.com$ UNSAFE vulnerable (exponential)
^\d{1,10}$ safe safe
^[a-z0-9-]{3,32}$ safe safe
(\d|\d\d)+x safe vulnerable (exponential)
Both flagged every nested-quantifier pattern, including the email-ish one and the "words separated by spaces" one that shows up in form validators everywhere, and both passed the bounded patterns. They disagreed on (\d|\d\d)+x: safe-regex2 called it safe and recheck called it exponential. Overlapping alternation inside a repeat has a star height of one, so a star-height check can't see it, even though the engine has the same exponential choice of ways to split the input.
The practical setup is safe-regex2 (or the equivalent ESLint rule) on every commit, since it's instant, and recheck in CI over any pattern that touches user input. recheck can also generate a triggering string for each finding, which is useful for writing a regression test against your own code. It parses JavaScript regex syntax, so check PHP and Python patterns with it only when they don't use engine-specific features.
What This Doesn't Cover
- Semgrep and language-specific linters. I compared two npm checkers above. Semgrep rules and Python or PHP linters cover the same ground with different accuracy.
- Real-world CVEs. Plenty of popular packages have shipped ReDoS fixes. I've kept this to the mechanism and the defenses rather than cataloging trigger inputs for specific libraries.
- Other engines. Java, .NET (which has a timeout API), Go and Rust (both linear by design) behave differently.
- Database regexes.
REGEXPin MySQL and~in Postgres run on their own engines, on your database server's CPU.
The Actual Point
A backtracking regex is a program whose run time is set by your attacker's input. Python will run it to completion, however long that takes. Node will run it to completion and stop everything else on the process while it does. PHP will give up quickly and hand you false, which your if statement reads as "fine." Know which of those you're working with: cap input lengths, write patterns that can't backtrack, use V8's linear engine or RE2 where you can, set the regex module's timeout in Python, and in PHP make every security check fail closed.
Sources: the PHP PCRE runtime configuration and preg_last_error_msg() documentation, the Python re documentation (possessive quantifiers and atomic groups since 3.11), the regex package's timeout documentation, and V8's own flag descriptions from node --v8-options. All timings and outputs were run by me on Python 3.15.2 with regex 2026.11.23, php:8.6-cli (PCRE 10.44) and node:26-slim (V8 14.6). Every script and output block above is reproduced verbatim from those runs; the scripts are original teaching code.
$ tail -f /forums
Discussion
Comments live on the community forums โ sign in there to reply.