Catastrophic backtracking and ReDoS

Intermediate · 11 min

Measure (a+)+$ doubling with every extra character, see the same cost behind two real outages, learn to spot the shape, and see which engines are immune.

Before thisHow a backtracking engine matchesQuantifiers: star, plus and questionAlternation

Ground Truth · 11 min

Catastrophic backtracking and ReDoS

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Ground TruthReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • When a match fails, a backtracking engine tries every other way the pattern could have matched. With nested quantifiers such as (a+)+$, the number of ways doubles with each extra character.
  • The slow input is the near miss, a long almost-match that fails at the end. The same pattern on a matching string returned instantly.
  • Not every blow-up is exponential. \s+$ on a long run of spaces and .*(?:.*=.*) on text without an equals sign are polynomial, and still took seconds on inputs of a few thousand characters.
  • Spot the shape: a quantifier inside a quantified group, overlapping alternatives like (a|a)+, adjacent quantifiers that can match the same text, and an unanchored pattern that retries from every start.
  • Engines differ. On the same pattern, V8, Python and Ruby 2.6 blew up, PCRE2 hit its match limit, Perl and BSD grep did not slow down, and Go's regexp ran in linear time.

A short pattern that never finishes

You validate a field with ^(a+)+$. It looks harmless. Then someone sends thirty a characters and an exclamation mark, and your server sits at 100% CPU for several seconds. One more a and it takes twice as long. This is catastrophic backtracking, and when an attacker supplies the input it is called ReDoS, regular expression denial of service.

The last lesson showed the engine backing off from a choice that failed. The problem here is that some patterns have many choices that all fail, and the engine tries every combination before giving up.

Measure it

Node 26, one run per size, on a string of n letter a followed by !:

/^(a+)+$/       n=22     18 ms
                n=24     73 ms
                n=26    281 ms
                n=28   1208 ms
                n=30   4710 ms

Each extra a doubles the time. These are warm runs: I tested smaller sizes first on the same regex object. On a brand-new regex the very first call at n=26 took 3,159 ms against about 280 ms on later calls, and with node --no-regexp-tier-up the first call took 318 ms, which suggests V8 runs a regex’s first execution in a slower interpreter before compiling it. So measure more than once. I stopped at 30. At that rate 40 would take around 80 minutes and 50 would take weeks, which is arithmetic from this table, not a run. Compare the other cases:

/^(a+)+$/ on "aaaa...a" (30 letters)    0.01 ms     matches, so it stops
/^(a+)+$/ on "aaaa...a" (5000 letters)  0.01 ms
/^a+$/    on 30 a's then !              0.02 ms
/^a+$/    on 1,000,000 a's then !       0.70 ms

The slow input is the near miss. When the string matches, the engine’s first guess works. When it fails at the very end, the engine has to prove that no split of the as into groups can work, and for n letters there are about 2^n splits (each gap between letters either closes the group or does not). The safe rewrite ^a+$ means the same thing and has exactly one way to match.

Not always exponential

Two real incidents were cheaper per input and still took services down.

Stack Overflow, July 2016. Michael Tsai’s write-up quotes the company’s postmortem. The pattern was ^[\s‌]+|[\s‌]+$, meant to trim whitespace from the ends of a line. The postmortem says it was not classic catastrophic backtracking but “O(n²)”, and the fix was replacing the regex with a substring function. I reproduced the shape: on "x" followed by n spaces and another "x", JavaScript took 26 ms at 8,000 spaces, 100 ms at 16,000, 393 ms at 32,000 and 1,565 ms at 64,000. Four times the cost for twice the input is quadratic. The second branch retries at every space, and each attempt scans to the end of the run.

Cloudflare, July 2, 2019. Cloudflare’s own postmortem says a new firewall rule was deployed at 13:42 UTC, CPU hit nearly 100% worldwide, the WAF was disabled globally at 14:07, and traffic recovered by 14:09. It says the service was down for 27 minutes, and names .*(?:.*=.*) as the critical part of the regex. Its remediation list includes “switching to either the re2 or Rust regex engine which both have run-time guarantees”. I tested just that fragment, not their full rule:

/.*(?:.*=.*)/  on n letters x, no "="
  n=500    22 ms
  n=1000  154 ms
  n=2000  1166 ms
  n=4000  9432 ms

Doubling the input multiplied the time by about 8, which is cubic. Anchoring it with ^ took it from 9.4 seconds at 4,000 characters to about 7 ms, because the engine no longer retried at every start. Making the dots lazy (.*?) only cut 9.4 s to 5.1 s. Cloudflare’s post says the same: laziness “isn’t the total solution”.

How to spot the shape

Look for these in any pattern that touches untrusted input:

  • A quantifier inside a quantified group: (a+)+, (\w+\s?)*.
  • Overlapping alternatives under a quantifier: (a|a)+ took 393 ms at 26 letters, and (a|aa)+ grew too, 475 ms at 38.
  • Adjacent quantifiers that can consume the same text: .*.*.
  • No anchor, so the engine retries from every start position.

Which engines are affected

I ran ^(a+)+$ against aaa...! in several tools:

V8 (Node)         blows up      (above)
Python 3.9 re     blows up      n=26 took about 1.4 s
Ruby 2.6          blows up      n=28 took about 2.9 s
PCRE2 pcre2grep   error -47 immediately (the match limit)
Perl 5.34         no slowdown, 1000 letters in 7 ms (whole process)
BSD grep -E       no slowdown, 100,000 letters in 3 ms (whole process)
Go regexp         0.03 ms at n=26, 40 ms at n=1,000,000

Error -47 is PCRE2_ERROR_MATCHLIMIT in the PCRE2 header: the library stopped the search rather than hang. I did not investigate why Perl is fast; I would not rely on it for patterns I have not tested. Go’s regexp follows the RE2 design and simply has no backtracking, but it refuses \1 and (?= at compile time. Node also has an experimental linear engine behind the flag --enable-experimental-regexp-engine and the l regex flag; with it /^(a+)+$/l took 3 ms on 100,000 characters, and /(a)\1/l threw “Cannot be executed in linear time”. It is experimental, so do not ship on it. The linear-time lesson explains the trade.

About the video

“This 7-Character Regex Took 48 Seconds to Fail” by Ground Truth was published 9 October 2026 and runs 11 minutes 7 seconds. The description says it shows why ^(a+)+$ is slow, covers the Stack Overflow 2016 and Cloudflare 2019 outages, and ends with Thompson’s method, RE2 and three fixes in Python. Its chapters match: “Every way to cut the string”, “The doubling, measured”, “Stack Overflow, 2016”, “Cloudflare, 2019”, “Matching without going back”. I couldn’t read a transcript, and the figures in the description come from their machine and Python 3.11, so I did not re-run them. My Python was 3.9, which is why my timings differ. It is from a small channel, so check its claims against the Cloudflare postmortem. English per its title and description.

What I did not run

The fixes that need Python 3.11 or newer (possessive quantifiers and atomic groups, next lesson), RE2 itself (I used Go’s regexp instead), Rust’s regex directly, and real ReDoS tooling or fuzzers. I did not run Cloudflare’s full pattern, only the fragment their postmortem names, and I did not fetch Stack Overflow’s own postmortem page, which blocked my request, so its details come from Michael Tsai’s quotation of it.

Next

You can defuse a pattern by rewriting it, or by telling the engine not to go back. Atomic groups and possessive quantifiers do the second.

Check yourself

  1. 01Why is /^(a+)+$/ fast on 'aaaa...a' but slow on 'aaaa...a!'?

    On the matching string the first way of splitting the a's succeeds and the engine stops. With the trailing ! every split fails at the end, so the engine tries all of them before giving up. The number of splits doubles with each added a.

  2. 02What is the difference between exponential and polynomial backtracking, and why do both matter?

    Exponential cost doubles with every extra character, so 30 characters can take seconds and 60 effectively never finish. Polynomial cost grows with n squared or n cubed. It is gentler, but I measured seconds at a few thousand characters, and web requests can carry that much.

  3. 03You must keep a backtracking engine. Which rewrite fixes ^(a+)+$ and why?

    ^a+$. The group and inner plus add no meaning here, since one plus already matches any run of a's. Removing the nesting removes the ambiguity, and my test ran a million characters in under a millisecond.

  4. 04How can you be safe from ReDoS without rewriting every pattern?

    Use a linear-time engine such as RE2 or Go's regexp for untrusted input, or cap input length and run time. Those engines reject backreferences and lookaround to keep the guarantee.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark