Quick revision
The short answer
The pattern ^(\w+\s?)*$ is ambiguous: because the space is optional, a run of letters can be cut into groups in an enormous number of ways, and when the input almost matches but fails at the end, the backtracking regex engine tries every one of those ways before it gives up. We fix it by rewriting the pattern so that each input can be matched in only one way, by using possessive quantifiers or atomic groups that never give characters back, and by limiting the input length before the pattern ever runs.
What to remember
In this answer, we saw that the JDK regex engine backtracks through every choice a pattern allows, and that an ambiguous pattern like ^(\w+\s?)*$ gives it exponentially many choices on a long input that fails at the last character. A thread dump full of Pattern frames points us to the validator. We fixed it by rewriting the pattern so each input has one parse, by using atomic groups or possessive quantifiers, and by bounding the input length, and we keep user-supplied patterns away from the request thread or run them on a linear engine.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
The pattern ^(\w+\s?)*$ is ambiguous: because the space is optional, a run of letters can be cut into groups in an enormous number of ways, and when the input almost matches but fails at the end, the backtracking regex engine tries every one of those ways before it gives up. We fix it by rewriting the pattern so that each input can be matched in only one way, by using possessive quantifiers or atomic groups that never give characters back, and by limiting the input length before the pattern ever runs.
Why this question is asked
A regular expression that works perfectly in tests can take a whole CPU core hostage in production, and a single request is enough to do it. This failure has a name, catastrophic backtracking, and attackers use it on purpose (it is then called ReDoS, a regular expression denial of service). Interviewers ask about it because it tests whether we understand how the regex engine works rather than just how to write patterns. In this answer, we will recap how java.util.regex matches text, see exactly why this pattern explodes, find the culprit in a thread dump, and then go through three fixes and how to protect a service that has to accept patterns from users.
1A Quick Recap of How java.util.regex Matches
The regex engine in the JDK is a backtracking engine. It walks through the pattern and the input together, and whenever the pattern offers a choice, such as how many characters a + should take or whether an optional ? should match, it picks one option and remembers the others as places it can come back to. If the match fails later, it returns to the most recent choice and tries the next option. This is what makes features like backreferences possible.
The cost is that there is no promise about time. A backtracking engine is fast when the first choices it makes are the right ones, but when a match fails, it must prove that no combination of choices works. For most patterns that is a handful of combinations. For some patterns the number of combinations grows exponentially with the input length. Engines built on a different design, such as RE2 and its Java port RE2/J, guarantee time linear in the input, but they give up features like backreferences to do it.
2Why ^(\w+\s?)*$ Explodes on a Near Miss
Let us read the pattern piece by piece. \w+ means one or more word characters, \s? means an optional whitespace character, and the group around them is repeated any number of times with *. The intent is a list of words separated by single spaces. The trouble is the question mark: because the space is optional, nothing forces a group to end where a word ends. The word aaaa can be matched as one group, as aa plus aa, as a plus aaa, as a plus a plus a plus a, and so on.
- Group 1 takes aaaa greedily\s? matches nothing
- $ meets the ! and failsback to the last choice
- Group 1 gives back one letteraaa, then group 2 takes a
- $ fails again at the !the same character every time
- Any splitting left to try?YesBack up and split the letters differentlyNoReport no match
5 steps in order. Play them, or step through them one at a time.
Every way of cutting the letters into groups ends at the same ! and fails. With n letters there are 2^(n-1) ways.
Notice that the successful case is fast. The engine takes the greedy choices, reaches the end and stops. The failing case is the dangerous one: the exclamation mark at the end can never match $, so every one of the 8 million ways of grouping the letters fails at the same last character, and the engine tries them all. Each extra letter doubles the work. That is why the bug hides in tests, which usually use short valid input, and appears when someone sends a long input that is almost valid.
But there is a catch when we try to reproduce it. JDK 9 added a memo that catches simple greedy group loops like this one, so on a recent JDK the exact pattern may fail fast (check your version). Small variants are not caught: on JDK 21 the lazy form ^(\w+?\s?)*?$ took about half a second for 24 letters and grows ten times for every four more, and very long inputs can also end in a StackOverflowError. The engine guarantees nothing, so we fix the pattern rather than rely on the memo.
3Finding the Culprit in a Thread Dump
In production we rarely know which pattern is guilty. The quickest evidence is a thread dump, taken with jcmd <pid> Thread.print or jstack <pid>. Take two or three dumps a few seconds apart. The stuck thread stays RUNNABLE and its top frames are always inside java.util.regex.
The exact inner class names change between JDK versions, but the shape is always the same: a deep stack of Pattern frames with one of our own classes underneath. So we scroll down to the first frame from our package, which tells us the validator and therefore the pattern. If we can also log the input length at that call site, we usually find a single request with a very long, nearly valid value.
4Fix 1: Rewrite the Pattern So Each Input Has One Parse
The root cause is ambiguity, so the best fix removes it. We want words separated by single spaces, with an optional space at the end. We can say exactly that: one word, then any number of groups that each start with a mandatory space followed by a word.
Now there is only one way to match any input. A group can begin only at a space, so the letters of one word cannot be shared between groups, and when the ! fails there are no other splits to try. Notice the last line: the rewrite is not identical to the original, because the original also accepted an empty string. When we rewrite a pattern we must write down the intended behaviour and keep tests for the edge cases, so that the safer pattern does not quietly change what we accept.
5Fix 2: Possessive Quantifiers and Atomic Groups
Java also lets us forbid the engine from going back into part of a match. A possessive quantifier, written with an extra plus such as \w++ or *+, takes as much as it can and never gives anything back. An atomic group, written (?>...), does the same for a whole group: once it has matched, its choices are thrown away.
With the atomic group, the first group swallows all the letters and cannot hand any back, so there is exactly one attempt and it fails at the !. This is a quick fix when a rewrite is hard. The last line shows the catch: possessive matching changes meaning when a later part of the pattern needs characters the quantifier already took. So we use it where the next token can never match what the quantifier consumed, and we keep tests around the change.
6Fix 3: Bound the Input and Keep Patterns Under Control
Even a safe pattern should not see unlimited input. A display name has no reason to be longer than, say, 100 characters, so we check the length first, which costs nothing, and reject the request before the regex runs. In Spring we can put @Size(max = 100) next to @Pattern on the request field so that Bean Validation enforces both, and we should also cap the overall request size at the server. A length limit turns any remaining worst case from hours into microseconds, because exponential growth needs long input to hurt.
We also compile patterns once into static final constants, and we never run patterns supplied by users inside request threads: a user who can supply a pattern can supply a slow one.
| Fix | What it changes | Cost |
|---|---|---|
| Rewrite to one parse | No alternative splits to try | Needs care to keep the same meaning |
| Atomic group or possessive | Engine cannot give characters back | Can reject input the original matched |
| Length limit before matching | Worst case stays small | Must pick a sensible maximum |
| Linear engine such as RE2/J | Time grows linearly with input | No backreferences or lookaround |
7Follow-up questions
How would you protect a service that must accept user-defined patterns?
I would start by not using java.util.regex for them. RE2/J compiles patterns into an automaton and matches in time linear in the input, so a user cannot write a pattern that explodes; it rejects backreferences, which is usually acceptable for search filters. If we must use the JDK engine, we limit the pattern length and the input length, reject constructs such as backreferences and nested quantifiers at compile time, and run the match on a separate bounded thread pool with a deadline. Because Matcher does not check for interrupts, the deadline is enforced by wrapping the input in a CharSequence whose charAt() checks the clock and throws once time is up. Finally, we monitor match times per tenant so that a slow pattern is visible.
Why does the pattern only misbehave on input that fails?
A successful match stops at the first path that works, and greedy quantifiers usually find that path straight away. To answer no, the engine must show that every path fails, and an ambiguous pattern has exponentially many paths. So we test patterns with long near misses, such as many valid characters followed by one invalid character at the end, rather than only with valid input.
8Conclusion
In this answer, we saw that the JDK regex engine backtracks through every choice a pattern allows, and that an ambiguous pattern like ^(\w+\s?)*$ gives it exponentially many choices on a long input that fails at the last character. A thread dump full of Pattern frames points us to the validator. We fixed it by rewriting the pattern so each input has one parse, by using atomic groups or possessive quantifiers, and by bounding the input length, and we keep user-supplied patterns away from the request thread or run them on a linear engine.
Open with
This is catastrophic backtracking. The JDK regex engine is a backtracking engine with no linear-time guarantee: at every choice, like how much a plus takes or whether an optional matches, it remembers the alternatives and comes back to them when the match fails.
Then, if they want more
In this pattern the space is optional, so a run of letters can be split into groups in two to the power of n minus one ways.
When the input is long and almost valid, say lots of letters and then an exclamation mark, every split fails at the same last character and the engine tries all of them, so each extra character doubles the time. Valid input is fast, which is why tests miss it.
I would confirm it with two or three thread dumps: the stuck thread is runnable with a deep stack of java.util.regex Pattern frames, and the first frame from our code names the validator.
To fix it, I rewrite the pattern so there is only one way to match, for example a word followed by groups that each start with a mandatory space, and I check edge cases such as the empty string because the rewrite can change meaning.
Where a rewrite is hard, an atomic group or possessive quantifiers stop the engine from giving characters back. I also bound the input length before matching, with @Size next to @Pattern, and precompile patterns as constants.
And I would never run user-supplied patterns on the request thread; if we must accept them, I would use a linear engine like RE2/J, or a separate pool with a deadline checked inside the match.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- Java 21, Java 9
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- The Java Language Specification, Java SE 21, Java SE 21 API documentation
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "A request with a long input string pegs a CPU core at 100 percent inside...": https://scrivio-interview-library.netlify.app/java/strings/116e53670a/