Video in progress

Senior ☕ Core Java

An endpoint with a regex that extracts emails from text pushed the CPU to 100% on large requests. How does regex backtracking turn into a DoS, and how do you protect against it in Java?

java.util.regex is a backtracking engine: on text that doesn't match, it retries many alternatives. Java 9+ softened the classic (a+)+ blow-up quite a bit, but quadratic and worse cases remain. The protection is to limit the input length, write the regex so it's unambiguous, and never run a user-supplied regex.

📖 Answer

Code that looks harmless:

static final Pattern EMAIL = Pattern.compile("[\\w.]+@[\\w.]+");

Matcher m = EMAIL.matcher(body);   // body is the text the user sent
while (m.find()) { ... }

body is 40,000 letters and has no @. find() starts at position 0, swallows the whole text with [\w.]+, can't find an @, backtracks... and then does the same from position 1. The result is O(n²): on my laptop with JDK 21, a single call takes about 1.5 seconds. 20 parallel requests, and the whole thread pool is busy.

There's worse: ^(.*?,){11}P (checking the 12th column in a CSV) takes about 3 seconds on a 61-character line, and every {11} layer adds another level. Patterns with backreferences ((a+)+\1) have also turned exponential.

One catch: most of the ReDoS examples on the internet (^(a+)+$) have run almost instantly since Java 9, because the JDK added internal memoization. So it's wrong to say "we're on Java 17, no risk", and just as wrong to test an old example and conclude "there's no problem".

The sign in prod: CPU at 100%, and in a thread dump deep stacks with java.util.regex.Pattern$...match. Sometimes a StackOverflowError: on a long text, an alternation (a|b)* falls into recursion.

The protection:

  1. Length first. A cheap check before the regex: if (s.length() > 254) reject. Limit the body size at the server level too.
  2. An unambiguous regex. Remove nested quantifiers; put a boundary on find(): (?<![\w.])[\w.]+@ doesn't retry from the middle of a word, and on those same 40,000 characters it takes 2 ms.
  3. Possessive/atomic (a++, (?>...)) cuts off backtracking, but it doesn't remove the position-by-position attempts in find(). Measure it.
  4. A regex given by the user (a search filter, an admin setting): don't use java.util.regex, use a library that guarantees linear time, like RE2/J. It has no backreferences, and that's the price.
  5. Testing. For a validator with a regex, write a JMH benchmark or a plain unit test with a timeout, using a "bad" input.

For email, a regex is often unnecessary anyway: it has an @, the length is reasonable, and the confirmation email checks the rest.