JDK 23 memoizes (a+)+ but not bounded, nested or back-referencing loops, which still double per character. Possessive rewrites and a read budget for untrusted input.
A validation regex that takes the service down
The order service of Belgavi's Book Store validates gift-message sender addresses with a pattern someone wrote years ago: ([a-z0-9]+[-.]?){1,63}@bookstore\.test. It works for every real address. Then a client sends a long run of letters with no @ at the end, and one request thread spends seconds inside Matcher.matches(). A few such requests in parallel and the thread pool is gone.
This is catastrophic backtracking. Java's java.util.regex is a backtracking engine: when a match fails, it goes back and tries every other way the pattern could have split the input. For patterns with nested or overlapping repetition, the number of ways grows exponentially with input length. And unlike .NET, whose Regex takes a match timeout, java.util.regex has no timeout parameter at all.
This guide measures which pattern shapes are actually dangerous on a current JDK, which is not the list most articles give, and shows two defences that work in Java: rewriting the pattern so it cannot backtrack, and bounding the work of any match on untrusted input. All numbers come from the companion probe regex_backtracking_bound, run on JDK 23.0.2.
Measure reads, not milliseconds
Timing a regex is noisy. The probe instead wraps the input in a CharSequence that counts every charAt call the matcher makes. The count is deterministic for one JDK build, so it shows the growth rate exactly. Each input is n letters a followed by a character that makes the match fail.
| Pattern | n = 8 | n = 12 | n = 16 | n = 20 |
|---|---|---|---|---|
(a+)+b | 81 | 169 | 289 | 441 |
(a+){1,64}b | 766 | 12,286 | 196,606 | 3,145,726 |
((a+)+)+b | 1,515 | 24,547 | 393,179 | 6,291,411 |
(a+)+\1b | 1,044 | 16,828 | 269,412 | 4,310,796 |
(a++){1,64}b | 11 | 15 | 19 | 23 |
a+b | 17 | 25 | 33 | 41 |
([a-z0-9]+[-.]?){1,63}@bookstore\.test | 1,021 | 16,381 | 262,141 | 4,194,301 |
([a-z0-9]++[-.]?){1,63}@bookstore\.test | 12 | 16 | 20 | 24 |
The first row is the textbook example of catastrophic backtracking, and on JDK 23 it is not exponential. It reads 81, 169, 289 and 441 characters, which is (n+1) squared: quadratic. The other exponential rows multiply by 16 for every four extra characters, which means the work doubles per character. At 40 characters the bounded pattern would read on the order of a trillion characters.
Why the textbook case is safe and its neighbours are not
The JDK source explains the table. In java/util/regex/Pattern.java at jdk-23+37, a greedy loop over a group that can match in more than one way is compiled into a Loop node. Loops at the top level of the pattern get a memo of input positions where the loop body already failed, and the matcher skips those positions instead of trying them again. That optimization is what makes (a+)+b quadratic. The source spells out three conditions:
- The loop must be greedy with no maximum. Only
cmax == MAX_REPS, that is+or*, is added to the list of top-level closure nodes. A bounded repetition such as{1,64}is not memoized, so it is exponential. - The loop must be at the top level. Loops nested inside another group's repetition are removed from that list when the enclosing group is compiled, so
((a+)+)+bis exponential. - The pattern must have no back-reference. A field named
hasGroupRefturns the optimization off for the whole pattern, so(a+)+\1bis exponential.
Bounded repetitions are common in validation patterns, because people copy limits from specifications: 63 characters per DNS label, 64 characters in a local part. The real-world pattern in the table is exponential for exactly that reason. The bound turns off the protection.
find() makes it worse, because it retries the whole match from every start position. For the bounded pattern the probe reads 1,515 characters at n = 8 and 6,291,411 at n = 20, about twice what matches() reads.
Defence 1: rewrite so nothing can backtrack
The cause is ambiguity: the same input can be split between the inner and outer repetition in many ways. Remove the ambiguity and the engine has nothing to retry.
- Possessive quantifiers (
++,*+,?+) consume as much as they can and never give any back.([a-z0-9]++[-.]?){1,63}reads 24 characters at n = 20. - Atomic groups
(?>...)do the same for a whole group. - Flatten nested repetition.
(a+)+bmeans the same asa+b.
Possessive quantifiers change what the pattern matches when backtracking would have been needed for a legitimate match, so add the cases you expect to match to the pattern's unit tests before rewriting. For the address pattern, a label of letters and digits followed by an optional separator has only one way to split, and the possessive form accepts the same addresses.
Defence 2: bound the work on untrusted input
A rewrite fixes one pattern. A service that accepts user-supplied patterns, or has hundreds of patterns in configuration, needs a limit that does not depend on reviewing each one. Java gives you two practical tools.
First, cap the input length before matching. Most validation inputs have a natural maximum: 254 characters for an email address, a few hundred for a name. An exponential pattern on 30 characters is still slow; on 300 it never finishes, so the cap must come with a rewrite, not instead of one.
Second, stop the match after a budget. Because Matcher reads input only through CharSequence.charAt, a wrapper can throw once a read budget or a deadline is exhausted:
final class BudgetedChars implements CharSequence {
private final CharSequence text; private final long budget; private final long[] reads;
BudgetedChars(CharSequence text, long budget, long[] reads) { this.text = text; this.budget = budget; this.reads = reads; }
public char charAt(int i) {
if (++reads[0] > budget) throw new MatchBudgetExceeded(budget);
return text.charAt(i);
}
public int length() { return text.length(); }
public CharSequence subSequence(int s, int e) { return new BudgetedChars(text.subSequence(s, e), budget, reads); }
}In the probe, (a+){1,64}b on 41 characters stops at exactly 5,000,000 reads, in about 55 ms on the test machine, and a valid 41-character input under the same budget matches after 43 reads. The exception is a normal runtime exception, so the request can fail with a validation error instead of hanging. Map it to a 400 response and count it as a metric: a rising count means someone is probing you.
A read budget is more predictable than a wall-clock deadline, because a deadline check on every charAt adds a clock read per character and depends on machine load. Use the budget for request paths and a deadline only for batch jobs that must finish by a time.
Other ways out
- A different engine. RE2/J, a Java port of RE2, matches in time linear in the input and rejects features that need backtracking, such as back-references. It is a good fit for user-supplied patterns. Its syntax is not identical to
java.util.regex, so test the patterns you migrate. - Not a regex. A hand-written parser for a fixed format is often shorter than the pattern and has no backtracking at all.
Failure modes and verification
The failures to look for in review are bounded repetition of a group that can match variable-length text, repetition nested inside repetition, alternatives that overlap, and back-references. For each pattern that touches untrusted input, add a test that matches a long non-matching input, such as 40 repeated characters followed by a mismatch, under a read budget, and assert that it completes. Run the probe on the JDK version you deploy. The memoization described here is what the jdk-23+37 source does; another JDK can memoize different shapes, so measure rather than rely on it.