Chapter 8: Performance & ReDoS
Goal: Learn why some patterns are slow and how to avoid them.
1) What is ReDoS?
ReDoS (Regular Expression Denial of Service) happens when a seemingly harmless pattern takes exponentially longer to match certain inputs.
The engine doesn’t crash, it just gets stuck trying an enormous number of possible ways to match — called catastrophic backtracking.
Safe: /a+b/ matches "aaaaab" quickly
Dangerous: /(a+)+$/ can grind to a halt on "aaaaaaaa...!"
In PHP with default settings, this often results in preg_match() returning false with “backtrack limit exhausted”, rather than hanging forever. But it’s still a real problem for user input.
2) How Catastrophic Backtracking Happens
Remember from Chapter 4: when a match fails, the engine backtracks — it tries different splits by giving characters back.
With nested quantifiers, those splits multiply. In /(a+)+$/, the same run of a’s can be divided between the inner a+ and the outer (a+)+ in many ways: all the a’s in one repetition of the outer group, one a per repetition, or anything in between. Each division is a separate path through the pattern, and the engine may have to try them all.
// /(a+)+$/ against lots of 'a' and a final '!': no split can ever match,
// so the engine tries them all — until the backtrack limit stops it
$pattern = '/(a+)+$/';
$subject = str_repeat('a', 24) . '!';
preg_match($pattern, $subject, $matches);
print_r($matches); // nothing matched
echo preg_last_error_msg(); // Backtrack limit exhausted
For /(a+)+$/ against "aaaa...!" (lots of a’s followed by !):
- Every division of the
a’s between the two repetitions is one path to try - None of the paths let
$match, because the!is in the way - The engine keeps trying paths until none is left or PHP’s backtrack limit stops it; in that second case
preg_match()returnsfalse, not0 - Each extra
aroughly doubles the number of paths — 24a’s already means millions of them
3) Risky Patterns to Avoid
Nested quantifiers
// Risky
'/(a+)+$/'
'/(a*)+$/'
'/([a-z]+)+$/'
Overlapping alternatives
// Risky - "a" and "aa" overlap
'/(a|aa)+$/'
Dot-star in repetition
// Risky in some forms
'/(.*)+$/'
Rule of thumb: Be very cautious when you have a quantifier inside another quantifier, or alternatives that can match the same text.
4) Safer Alternatives
Simplify
Often the fix is to remove the nesting entirely.
// Risky
'/(a+)+$/'
// Safe - same result for valid matches
'/a+$/'
Use atomic groups (?>...)
An atomic group matches once and never backtracks. Once (?>...) commits to what it matched, it’s locked in.
// Risky
'/(a+)+$/'
// Safer with atomic group
'/(?>a+)+$/'
Use possessive quantifiers ++, *+, ?+
Possessive quantifiers are like greedy ones, but they never give back characters.
// Risky
'/(a+)+$/'
// Safer with possessive quantifier
'/(a++)+$/'
For overlapping alternatives, simplify or make possessive
// Risky
'/(a|aa)+$/'
// Best fix - simplify
'/a+$/'
// Also works - make the unit possessive
'/(?:a|aa)++$/'
Reordering alternatives (/(aa|a)+$/) does not fix this. Putting the longer alternative first can only make a successful match arrive sooner; when the match is going to fail anyway, the engine must still try every path before it can report “no match”, whatever the order.
5) General Best Practices
- Keep it simple - If you can write it with fewer quantifiers, do it
- Avoid nesting quantifiers -
+,*,{n,m}should rarely be inside each other - Be specific -
[a-z]+is often safer than.* - Anchor when possible -
^...$helps the engine fail faster in some cases, but won’t fix catastrophic backtracking - Test with worst-case inputs - Think “what if this is all the same character followed by something that won’t match?”
- Use atomic/possessive only when needed - They change behavior, so make sure you still match what you intend
6) Exercises
Exercise 1: Spot the risk
Which of these are potentially dangerous?
/\d{4}-\d{2}-\d{2}//(a+)+$//^[a-z]+$//(x|xx)+y/
Solution
- Safe - no nested quantifiers
- Dangerous - nested
+inside+ - Safe - single quantifier
- Dangerous - overlapping alternatives
Exercise 2: Fix it
Rewrite /(a+)+$/ to be safe in two different ways.
Solution
// Option 1: Simplify
'/a+$/'
// Option 2: Atomic group
'/(?>a+)+$/'
// Option 3: Possessive
'/(a++)+$/'
Exercise 3: Think
Why doesn’t /(aa|a)+$/ fix the issue from /(a|aa)+$/?
Solution
Because on a failing match, the engine still tries all possible splits regardless of which alternative it tries first. Alternative order only matters when multiple alternatives match at the same position — it picks the first. On failure, it backtracks through everything.
Key Takeaways
- Catastrophic backtracking happens with nested quantifiers or overlapping alternatives
- Simplify first — often the easiest and safest fix
- Atomic groups
(?>...)and possessive quantifiers++/*+/?+prevent backtracking - Reordering alternatives won’t help on failing matches
- Be skeptical of patterns with quantifiers inside quantifiers
Optional: Tools to Detect ReDoS
If you’re working with user-provided patterns or want extra reassurance, tools can analyze them. These are completely optional.
vendor/bin/regex debug '/(a+)+$/' --redos-mode=confirmed
use PHPRegex\Toolkit\Regex;
$regex = Regex::create();
$analysis = $regex->redos('/(a+)+$/');
// Check $analysis->severity