Lesson 4 of 9 · 28m
Catastrophic Backtracking: The Regex Denial-of-Service You Ship Yourself
Recognize ambiguous quantifier combinations, reproduce exponential failure safely, and rewrite dangerous patterns using disjointness, anchors, and atomic control.
Every senior engineer eventually meets a production incident caused by a regex that looked harmless. A user submits a long but plausible string, a worker pins a CPU core, the health check dies, and suddenly input validation is part of your threat model. That is catastrophic backtracking: correctness by exhaustion.
The canonical trap
import re
rx = re.compile(r"^(a+)+$")
text = "a" * 30 + "!"
# rx.fullmatch(text) explores many partitions before failing.The pattern accepts strings of one or more a characters. It also contains two quantifiers that can divide the same run of as. The final ! cannot match, so the engine unwinds and tries another split. Then another. The number of possible partitions grows explosively with input length.
Overlapping tokenization is the poison
Nested quantifiers are not required. This shape is also dangerous:
rx = re.compile(r"^(\w+\s?)+$")\w+ consumes a word; optional whitespace can sometimes be empty; the outer group repeats. Multiple representations of the same input exist. Ambiguity, not nesting alone, is the poison. Classic motifs include (a|a)+, (.*)+, (\w+\s*)*, and (.+)+suffix.
Reproduce with a time budget
Never prove danger by freezing a production process. Measure locally on increasing input sizes and include near-misses:
for n in (8, 12, 16, 20):
s = "a" * n + "!"
# Time fullmatch in a bounded subprocess; re has no per-match timeout.Python's standard re does not expose a match timeout. For hostile input, run matching in a bounded worker, use the third-party regex module's timeout, use a safer engine such as RE2 where compatible, or redesign the pattern.
Fix ambiguity, don't decorate it
The best repair is a stricter contract:
bad = r"^(\w+\s?)+$"
good = r"^\w+(?:\s+\w+)*$"The repaired grammar gives each input one natural parse. Separators are consumed by exactly one construct. Other useful repairs: use [^,]+ instead of .*? when comma terminates a field, require a literal after variable text, anchor once, and use atomic control only when overlap is impossible.
Benchmark rejection, not just acceptance
A validator can be dangerous precisely because it rejects malicious input. Benchmark valid examples, invalid early failures, invalid late failures, maximum lengths, empty sections, and adversarial near-misses. If runtime grows faster than input length for equivalent inputs, suspect algorithmic backtracking rather than constant-factor overhead.
Field notes
- Backtracking explosions usually happen on rejection, not acceptance.
- Ambiguous tokenization is the core problem; nested quantifiers are merely its loudest symptom.
rehas no built-in timeout, so process isolation or a different engine is required for adversarial workloads.- A timeout is a circuit breaker, not a fix; remove the ambiguity too.
- A regex that validates untrusted input is part of your denial-of-service surface.
Was this lesson helpful?