Every regex you test looks fine. It matches the good inputs, rejects the bad ones, and returns in microseconds. Then one day a user pastes a long line that almost matches, and a server spends the next hour on a single request. That failure has a name, ReDoS, and it comes from how most regex engines work, not from a typo.
How a backtracking engine works
Most engines, including the one in every browser and in Node.js, match by trying one path and, when it fails, stepping back to try another. That is backtracking. For most patterns it is fast, because failed paths die quickly. The trouble starts when the pattern lets the engine reach the same result through exponentially many different paths, and the input then fails at the very end, so every path has to be tried.
The classic case is ^(a+)+$. The text aaaaaaaaaaaaaaaaaaaaaaaab ends with a b, so the match must fail. But before giving up, the engine tries every way to split the run of a characters between the inner + and the outer +: one group of 24, a group of 23 and a group of 1, and so on. A run of n letters can be split in 2^(n−1) ways. Each extra character doubles the work.
Measured with Node.js on a laptop (CPU time of one failed match of (a+)+$ against n letters a followed by b):
| n | 16 | 18 | 20 | 22 | 24 |
|---|---|---|---|---|---|
| time | 2 ms | 8 ms | 33 ms | 135 ms | 556 ms |
Your numbers will differ, but the shape will not: every two extra characters multiply the time by four. Carry the table on to 40 characters and one match takes roughly ten hours. That is an extrapolation, so do not run it on a machine you care about.
Three shapes of trouble
1. A quantifier inside a quantified group. ^(\d+)+$ against 111111111111111111111111x (24 digits and an x) took about 240 ms, and each extra digit doubles it. Real code hides this inside longer patterns: (\w+\s?)* to match a list of words is the same trap.
2. Alternatives that overlap. ^(a|aa)+$ can read aaaa as four a or two aa or a, aa, a, and so on. The number of ways grows like the Fibonacci sequence, which is slower than doubling but still exponential: 0.05 ms at 16 characters, 0.3 ms at 20, 2 ms at 24 and 16 ms at 28 in the same measurement. At 28 it is still comfortable; at 60 it is not.
3. Quadratic, the one that looks harmless. \s+$ is a very common way to trim trailing whitespace. Against a long run of spaces followed by a non-space, the engine starts a match at every space and scans to the end each time. The cost is proportional to n squared: doubling the input quadruples the time. 5,000 spaces took about 37 ms, 10,000 took 146 ms, 20,000 took 590 ms and 40,000 took 2.4 seconds. The built-in trim() does the same job in 0.1 ms for 40,000.
Quadratic is the easiest kind to miss, because it passes every test with short inputs. In July 2016 a regular expression meant to trim whitespace from the start and end of a line made Stack Exchange’s servers slow to a crawl: the time grew with the square of the length of the text it was trimming. Three years later, in July 2019, a single backtracking-prone expression in a firewall rule exhausted the CPUs on Cloudflare’s network, and traffic was disrupted for about 27 minutes. Neither pattern was exotic.
The “safe” version that is not
It is tempting to simplify (a+)+$ into a+$ and call it fixed. Without an anchor at the start, the engine tries every starting position: a+$ against 100,000 letters a and a final b ran for more than 20 seconds in the same measurement. It is no longer exponential, but it is still quadratic. Adding ^ makes the same input take under a millisecond:
| Pattern | Input of 100,000 characters | Time |
|---|---|---|
a+$ |
aaaa…ab |
over 20 seconds |
^a+$ |
aaaa…ab |
under 1 ms |
^\d+$ |
111…1x |
under 1 ms |
How to fix a pattern
- Remove the nested quantifier.
^(\d+)+$and^\d+$accept exactly the same strings. So do^(a|aa)+$and^a+$. The tool’s regex tester gives the same answer for both versions, and only one of them can hang. - Make alternatives mutually exclusive.
(a|aa)overlaps,(a|b)does not. If two branches can match the same text, merge or reorder them. - Anchor the pattern with
^and$when you mean the whole string. An unanchored search is the usual source of quadratic cost. - Do not look for atomic groups. JavaScript has no possessive quantifiers and
(?>…)is a syntax error, so the fix has to be in the pattern. - Use a parser when you can. Splitting a URL, a CSV line or an HTML tag with a regex is where patterns grow nested and fragile. The URL parser and a real CSV reader, as in CSV edge cases, cannot backtrack in this way.
- Cap the input length before matching. A limit of a few thousand characters makes even a quadratic pattern harmless.
If you must run someone else’s pattern
A pattern typed by a user is hostile by default. Run it where a runaway match cannot take the rest of the application down: in a Web Worker you can terminate, in a separate process with a time limit, or with an engine that guarantees linear time, such as RE2. The regex tester on this site does the first of these. It runs every pattern in a Web Worker and stops it after 5 seconds with the message “Stopped after 5 seconds — the input is too large, or a pattern backtracks catastrophically”. The page stays responsive. To see the effect, paste ^(\d+)+$ as the pattern and a run of digits ending in a letter as the text, then add digits one at a time: on a typical laptop it stops somewhere around 28 to 30 digits.
Testing for it
Add a test with an input designed to almost match: a long run of valid characters followed by one invalid one. Compare the cost at two lengths rather than the absolute time, because absolute times depend on the machine. If doubling the input multiplies the cost by far more than two, the pattern is not linear. Linters such as eslint-plugin-regexp can also flag nested quantifiers statically, and fuzzing with long near-miss inputs finds the cases you did not think of.
Checklist before a regex goes to production
- Does a quantified group contain another quantifier?
- Can two alternatives match the same text?
- Is the pattern anchored when it should cover the whole string?
- Is the input length capped before matching?
- Did you try an input that almost matches, at two lengths?
- Could a parser or a built-in such as
trim()do the job instead?
Everything you paste into the regex tester is processed in your browser and never uploaded.
Frequently asked questions
What is ReDoS?
Regular expression Denial of Service: an input crafted (or just unlucky) so that a backtracking regex engine tries an enormous number of paths before it fails. One request can then keep a CPU core busy for seconds or hours. The pattern is not wrong in what it matches; it is wrong in how long it takes to say no.
How can I tell whether my regex is vulnerable?
Look for a quantifier inside a quantified group, such as (a+)+ or (\w+\s?)*, and for alternatives that can match the same text, such as (a|aa)+. Then test it: run the pattern against an input that almost matches (a long run of valid characters followed by one bad one) and double the length. If the time doubles or quadruples each time, it is vulnerable.
Does JavaScript have atomic groups or possessive quantifiers to prevent this?
No. Those features exist in engines such as PCRE and Java, but a JavaScript RegExp rejects the syntax (?>...) with an error. In JavaScript you fix the pattern itself: remove the nested quantifier, make alternatives mutually exclusive, and anchor the pattern. You can also run untrusted patterns in a worker you can terminate.
Which languages are affected?
Any engine that backtracks: JavaScript, Python, Java, .NET, PCRE, Ruby and Perl. Engines built on automata, such as RE2 and the one in Go, run in time proportional to the input, at the cost of not supporting backreferences or lookaround.
Should I limit the length of the input?
Yes, always, before the regex runs. A length limit turns an unbounded problem into a bounded one: a quadratic pattern on 200 characters is harmless, on 200,000 it is an outage. Combine it with a safe pattern, not instead of one.
More guides
- CIDR notation: why a /31 has two usable hosts, what a /32 is for, and the subnet mistakes to avoid
- Hashing is not encryption: what a hash can do, and why passwords need bcrypt
- Unix timestamps: seconds, milliseconds or microseconds, and the dates where they go wrong
- UUID v4, UUID v7 and ULID: which ID to use, and what is inside each
- Base64 is not encryption: what it does, and the bugs it causes
- JSON, CBOR, MessagePack and Protobuf: the same data in four sets of bytes
- URL encoding pitfalls: %20 or +, double encoding, and the characters that break links
- Cron and time zones: why your 02:30 job runs twice or never
- CSV edge cases: quotes, newlines, delimiters and the leading zero
- Why JSON silently changes your big numbers (and how to stop it)
- JWT pitfalls: decoding a token is not verifying it
- YAML surprises: the Norway problem, octal numbers and version strings