Software Development

How Regex Engines Work: Backtracking, Finite Automata and ReDoS

Why one regular expression can take a minute on a 30-character string, and how linear-time engines like RE2 avoid it

Zarton EditorsNov 18, 2026 · 7 min read

On July 2, 2019, one regular expression took a large slice of the web offline. Cloudflare pushed a new firewall rule, and the pattern inside it pinned every CPU core serving HTTP traffic across its network for 27 minutes. Nothing was hacked. The regex had simply been handed a question it could not answer quickly.

Regular expressions feel like magic strings you copy from a forum and forget about. Underneath, though, every language ships a regex engine, and engines are built in two very different ways. This guide explains how regex engines work, why one design can take exponential time on a 30-character string, what a ReDoS attack is, and the habits that keep your patterns fast.

From pattern to state machine

A regular expression describes a set of strings. Computer scientists showed long ago that every such pattern can be turned into a finite automaton: a small machine with states and arrows labeled by characters. You feed it the input one character at a time, and if it ends in a "match" state, the string matches.

These machines come in two flavors:

  • DFA (deterministic finite automaton): from any state, each input character leads to at most one next state. Very fast to run, but it can need many states.
  • NFA (nondeterministic finite automaton): a state may offer several possible next moves. Easy to build straight from a pattern, but something has to decide which move to take.

Ken Thompson described how to compile a regex into an NFA in a 1968 paper, and his construction yields roughly one state per character of the pattern. The interesting question is what comes next: how do you run an NFA on a real computer that can't guess? The answer splits the regex world in two.

Strategy one: backtracking

The intuitive approach is to try one option, and if it fails later, back up and try the next. That's backtracking, and it's what Perl, PCRE (and therefore PHP), Python's re, Java, Ruby and the default JavaScript engines use.

Backtracking is simple to implement and easy to extend with powerful features: backreferences like \1, lookahead and lookbehind assertions, and lazy quantifiers. For most patterns on most inputs it's quick, because the first guess is usually right.

The trouble starts when the input almost matches. To report "no match," a backtracking engine must try every possible way of dividing the input among the pattern's pieces before it gives up.

Catastrophic backtracking in action

Take OWASP's textbook example, ^(a+)+$, run against a string of a characters followed by an !. The inner and outer + can split the letters in an enormous number of ways. OWASP counts 16 possible paths for four letters and 65,536 for sixteen; every extra letter doubles the work.

import re, time

evil = re.compile(r'^(a+)+$')

for n in (18, 20, 22, 24):
    text = 'a' * n + '!'          # almost matches, then fails
    start = time.perf_counter()
    evil.match(text)
    print(n, f'{time.perf_counter() - start:.3f}s')

# The fix: ^a+$ matches exactly the same strings, in linear time.
Run this yourself and the time roughly doubles with each extra character. Don't push n much past 30.

Russ Cox's widely cited 2007 benchmark makes the point vividly: matching a pathological pattern against a 29-character string took Perl more than 60 seconds, while a small implementation of Thompson's algorithm finished in about 20 microseconds.

Strategy two: track every state at once

Thompson's own answer to "the machine can't guess" was simply not to guess. Instead, the engine keeps a set of every state the NFA could currently be in and advances all of them together as each character arrives. It reads the input exactly once and never backs up.

Because an NFA has at most m states (roughly the pattern's length), each character costs a bounded amount of work. Total time is proportional to m × n for a text of length n, which is linear in the input. No pattern is pathological for this approach.

Engines go further by caching each set of states as a DFA state the first time it appears, building the DFA lazily as the text is scanned. Cox notes that awk, Tcl and GNU grep build DFAs this way, and that Al Aho's egrep used a DFA as far back as 1979.

The catch: features that need backtracking

Some popular features don't fit the "all states at once" model. Backreferences are the big one: matching (cat|dog)\1 means remembering which text a group captured, and the general problem is NP-complete. So automata-based engines like Google's RE2 deliberately leave out backreferences and look-around assertions. In exchange, RE2 guarantees match time linear in the input, works within a configurable memory budget, and avoids recursion so it can't overflow the stack. Google has used it in production since 2006.

Backtracking vs. automata engines at a glance

Backtracking enginesAutomata-based engines
ExamplesPerl, PCRE/PHP, Python re, Java, Ruby, default JavaScriptRE2, Rust's regex crate, GNU grep, awk, .NET NonBacktracking
Worst-case timeExponential in input lengthLinear in input length
Backreferences / look-aroundSupportedGenerally not supported
Typical speedVery fast when the first guess is rightSteady, with some fixed overhead per character
Safe for untrusted inputOnly with timeouts and careful reviewDesigned for it

RE2's documentation frames the trade-off neatly: a backtracking engine is optimistic and tries alternatives one by one, while RE2 is pessimistic and evaluates them in parallel, paying a small constant cost so the worst case never arrives.

ReDoS: when a slow regex becomes an attack

A regular expression denial of service (ReDoS) happens when an attacker sends input crafted to trigger catastrophic backtracking. One request can tie up a CPU core for seconds or minutes, and in single-threaded runtimes such as Node.js it stalls every other request at the same time. Vulnerability databases are full of ReDoS reports against popular libraries, from MIME-type parsers to front-end frameworks.

OWASP describes the warning signs of an "evil" regex: a group that repeats and contains its own repetition, or alternatives that can match the same text. Classic shapes include:

  • (a+)+ and ([a-zA-Z]+)*: a quantifier nested inside another quantifier
  • (a|aa)+ and (a|a?)+: alternatives that overlap
  • (.*a){x} for larger values of x: repeated greedy wildcards

Cloudflare's 2019 rule contained this kind of structure, with stacked .* wildcards. In its postmortem the company said it would move to an engine with run-time guarantees, such as RE2 or Rust's regex crate.

How to keep your regexes fast and safe

  1. Remove nested quantifiers. (a+)+ almost always simplifies to a+. Make sure alternatives can't match the same text.
  2. Be specific instead of using .*. [^"]* inside quotes gives the engine far fewer ways to split the input than .*.
  3. Use atomic groups or possessive quantifiers. (?>...) and a++ tell the engine never to back into a group once it has matched. Python's re gained both in version 3.11; Java and PCRE have had them for years.
  4. Set a timeout. .NET lets you pass a match timeout to Regex and even set a process-wide default with the REGEX_DEFAULT_MATCH_TIMEOUT setting.
  5. Pick a linear engine where you can. .NET 7 added RegexOptions.NonBacktracking, which Microsoft documents as guaranteeing linear-time processing, and RE2 bindings exist for most languages.
  6. Cap input length. Exponential blow-up needs room to grow. Rejecting a 50 KB "email address" before it reaches the regex is cheap insurance, alongside sensible API rate limiting.
  7. Test the failure case. Benchmark patterns on input that almost matches, not just valid input, and add a ReDoS linter to CI.
// C#: two safety nets for untrusted input
var safe = new Regex(@"^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$",
                     RegexOptions.NonBacktracking | RegexOptions.IgnoreCase);

var timed = new Regex(pattern, RegexOptions.None,
                      TimeSpan.FromMilliseconds(100)); // throws RegexMatchTimeoutException
NonBacktracking removes the exponential case; a timeout caps the damage when you need backtracking-only features.

One more gotcha: classes like \w and . behave differently depending on whether your engine works on bytes, code points or UTF-16 units. If your patterns touch international text, our explainer on how Unicode and UTF-8 work covers why.

Key takeaways

  • Every regex can be compiled into a finite automaton; engines differ in how they run it.
  • Backtracking engines (Perl, Python, Java, JavaScript, PCRE) are flexible but can take exponential time on input that almost matches.
  • Automata engines such as RE2 track all states at once and guarantee linear time, at the cost of dropping backreferences and look-around.
  • ReDoS turns catastrophic backtracking into a denial-of-service attack; nested and overlapping quantifiers are the usual culprits.
  • Simplify patterns, use atomic groups, set timeouts and prefer linear-time engines for untrusted input.

Frequently asked questions

What is catastrophic backtracking?

It's when a backtracking regex engine tries an exponential number of ways to split the input among a pattern's quantifiers before concluding there is no match. It usually involves nested or overlapping quantifiers and input that almost matches.

Which regex engines are immune to ReDoS?

Engines that never backtrack, such as RE2, Rust's regex crate and .NET's NonBacktracking mode, guarantee time linear in the input length, so a crafted string can't trigger exponential run time.

Why don't all languages use linear-time engines?

Backreferences and look-around assertions are popular features that, in general, only backtracking implementations support. Languages keep backtracking for compatibility, and some offer a linear engine as an option.

Do possessive quantifiers fix every slow regex?

No. They stop the engine from backing into a group, which removes many blow-ups, but they can also change what a pattern matches. Test the rewritten pattern on both valid and invalid input.

Sources

Comments

No comments yet — be the first to share your thoughts.

Join the discussion

Comment

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

Keep reading

All posts

Run your whole business from one conversation.

Get startedTalk to us