Quick revision
The short answer
The filter almost certainly compiles a regular expression on every request, often hidden inside String.matches, replaceAll or split, and compiling a pattern is far more expensive than matching it. The fix is to compile the pattern once into a static final Pattern and create a cheap Matcher per call, because Pattern is thread-safe and Matcher is not. We verify by profiling again under the same load and comparing CPU per request, and add a JMH benchmark if the filter is on a critical path.
What to remember
In this answer, we saw that Pattern.compile parses a regex into an object tree, which costs far more than matching, so a filter that compiles on every request spends a large share of its CPU there. The compilation is often hidden in String.matches, replaceAll and split with a real regex. The fix is a static final Pattern shared by all threads, since Pattern is thread-safe, with a new Matcher per call, since Matcher is not. We verified it by profiling again under the same load and comparing CPU per request, and protected it with a JMH benchmark.
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 filter almost certainly compiles a regular expression on every request, often hidden inside String.matches, replaceAll or split, and compiling a pattern is far more expensive than matching it. The fix is to compile the pattern once into a static final Pattern and create a cheap Matcher per call, because Pattern is thread-safe and Matcher is not. We verify by profiling again under the same load and comparing CPU per request, and add a JMH benchmark if the filter is on a critical path.
Why this question is asked
A flame graph that shows 35 percent of CPU in one library method is a gift: it points straight at a fix that can cut a service's CPU by a third. Repeated regex compilation is one of the most common findings of this kind in Java services, because the expensive call is often hidden behind convenient String methods. Interviewers ask this question to check that we can read a flame graph, connect it to a known performance trap, fix it correctly with thread safety in mind, and prove the fix worked. In this answer, we will recap what Pattern.compile does, find the hidden compilation, apply the fix, look at other places the same trap hides, and verify the result.
1What Pattern.compile Actually Does
A regular expression in Java goes through two stages. Pattern.compile(regex) parses the text of the expression and builds an internal tree of node objects that knows how to match it. That involves parsing, character class construction and allocation of many small objects. Then pattern.matcher(input) creates a Matcher, a small object that holds the state of one matching attempt, such as the current position and captured groups, and runs the node tree against the input.
Compiling is the expensive part, and for a typical header pattern it can cost several times more than matching a short string. So code that compiles once and matches many times is cheap, while code that compiles on every call pays the expensive part every time.
2Finding the Hidden Compilation
The flame graph says Pattern.compile is called from the filter, so we look for regex use in it. Very often there is no visible Pattern.compile at all, just String methods that take a regex.
String.matches(regex) is a convenience method that calls Pattern.matches(regex, this), which compiles the pattern and throws it away. replaceAll does the same. At 3,000 requests per second, this filter compiles 6,000 patterns per second, and each compilation allocates a tree of objects that becomes garbage at once. So the cost shows up twice: as CPU under Pattern.compile in the flame graph, and as extra allocation that keeps the garbage collector busy.
3The Fix: Compile Once, Match Many Times
We move each pattern into a static final field, so it is compiled once when the class is initialised, and we create a Matcher per call.
Notice what is shared and what is not. A Pattern is immutable and the Javadoc states that instances are safe for use by multiple concurrent threads, so one static instance can serve every request thread. A Matcher holds mutable matching state and is not thread-safe, so we never store a Matcher in a field; we create a new one for each call, which is cheap because it only allocates a small state object.
In this particular case, we could also ask whether a regex is needed at all. A loop that checks each character is in [A-Za-z0-9-] and the length is between 8 and 64 is faster still, but the static Pattern already removes the 35 percent, and it keeps the rule readable.
4Other Places the Same Trap Hides
Once we have seen it, we search the code base for the other regex-taking methods. String.matches, String.replaceAll, String.replaceFirst and Pattern.matches always compile their regex argument. String.split(regex) compiles too, with one useful exception: the JDK has a fast path for a single character that is not a regex metacharacter, such as split(","), and for an escaped single character, which avoids compilation. String.replace(CharSequence, CharSequence), by contrast, does not use regular expressions at all and is the right choice for a plain text replacement.
A static analysis rule or a code review checklist item that flags these methods inside hot paths, such as filters, serialisers and loops, keeps the problem from coming back.
| Method | Compiles a regex each call? | Better choice in a hot path |
|---|---|---|
s.matches(regex) | yes | static Pattern, matcher(s).matches() |
s.replaceAll(regex, r) | yes | static Pattern, or replace() for plain text |
s.split(",") | no, single-character fast path | fine as it is |
s.split("\\s*,\\s*") | yes | static Pattern, PATTERN.split(s) |
s.replace("a", "b") | no regex at all | fine as it is |
5Verifying the Fix
A fix is not finished until the profile says so. We deploy the change to a test environment, or a canary, and run the same load as before, for example the same 3,000 requests per second with the same request mix. Then we profile again with async-profiler in CPU mode for the same duration and compare.
The comparison that matters is CPU per request, not just total CPU, because traffic changes. If before the fix pods used 2.4 cores at 3,000 requests per second, that is 0.8 ms of CPU per request; if after the fix they use 1.6 cores at the same rate, that is about 0.53 ms, a reduction of a third, which matches the 35 percent the flame graph promised. We also check that Pattern.compile has disappeared from the new flame graph, that allocation rate and GC frequency dropped, and that p99 latency improved or at least did not get worse.
If the filter is performance-critical, a JMH benchmark comparing the old and new validation methods makes the gain visible in isolation and protects it in the build. JMH, the Java Microbenchmark Harness, handles warmup and dead-code elimination so the numbers are trustworthy.
- CPU flame graph35% under
Pattern.compile - Find the call site
String.matches,replaceAllin the filter - Static final Patternnew Matcher per call
- Same load test again3,000 requests per second
- CPU per request down about a third?YesShip, add JMH benchmark if criticalNoLook for other compilation sites
5 steps in order. Play them, or step through them one at a time.
6Follow-up questions
Could we cache Matcher objects in a ThreadLocal to save even more?
It is possible, using matcher.reset(input), but rarely worth it. Creating a Matcher is cheap compared with compiling, and a ThreadLocal adds complexity and memory held by every pool thread. We would only do it if a benchmark showed Matcher creation itself mattered.
What if the pattern comes from configuration and can change at runtime?
Then we compile it when the configuration is loaded or changes, and store the compiled Pattern in a volatile field or an immutable configuration object. The rule stays the same: compile on change, not on every request.
Is there another regex risk in a header filter?
Yes, catastrophic backtracking. A pattern with nested quantifiers, such as (a+)+, can take exponential time on a crafted input, and since headers are attacker-controlled this becomes a denial of service. We keep patterns simple, bound input length before matching, and test with long hostile inputs.
7Conclusion
In this answer, we saw that Pattern.compile parses a regex into an object tree, which costs far more than matching, so a filter that compiles on every request spends a large share of its CPU there. The compilation is often hidden in String.matches, replaceAll and split with a real regex. The fix is a static final Pattern shared by all threads, since Pattern is thread-safe, with a new Matcher per call, since Matcher is not. We verified it by profiling again under the same load and comparing CPU per request, and protected it with a JMH benchmark.
Open with
Thirty-five percent under Pattern.compile tells me the filter compiles a regular expression on every request. Usually it is hidden: String.matches, replaceAll and replaceFirst all compile their regex argument each time, and split does too unless it is a simple single character.
Then, if they want more
Compiling parses the expression into a tree of node objects, which is much more expensive than matching and creates garbage, so it also adds GC pressure. The fix is to compile each pattern once into a private static final Pattern and call PATTERN.matcher(value).matches() per request.
That is safe because Pattern is immutable and thread-safe, while Matcher holds mutable state, so I create a new Matcher each call and never share one. For plain text replacements I would use String.replace, which does not use regex at all. Then I search the code base for the same methods in other hot paths.
To verify, I run the same load again, profile with async-profiler in CPU mode, and compare CPU per request rather than total CPU, for example 0.8 milliseconds down to about 0.53, and check that Pattern.compile is gone from the flame graph and that allocation and p99 latency went down.
If the filter is critical, I would add a JMH benchmark comparing the old and new code.
About this answer
- Last updated
- 12 November 2026
- 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.
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 "An async-profiler CPU flame graph of a REST service shows 35 percent of samples under...": https://scrivio-interview-library.netlify.app/java/jvm-diagnostics/b1dccba824/