Quick revision
The short answer
I would stop compiling expressions on every evaluation and cache compiled XPathExpression objects per thread, validate and restrict expressions when users save them (length, functions, no // on large documents, no extension functions with secure processing on), and evaluate them in a bounded executor with time budgets so one bad rule cannot starve the rest. For very large documents I would pre-extract fields or use a streaming processor such as Saxon, and I would monitor latency per rule and automatically disable slow rules while notifying their owner.
What to remember
In this answer, we separated the two causes of CPU spikes: compiling expressions on every call and a few rules with explosive cost. We cached compiled XPathExpression objects per thread, validated and restricted expressions at save time with secure processing blocking extension functions, ran evaluation in a bounded executor with time budgets while remembering that XPath evaluation ignores interruption, pre-extracted fields or streamed with Saxon for large documents, and monitored latency per rule to disable slow ones automatically and notify their owners.
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.
I would stop compiling expressions on every evaluation and cache compiled XPathExpression objects per thread, validate and restrict expressions when users save them (length, functions, no // on large documents, no extension functions with secure processing on), and evaluate them in a bounded executor with time budgets so one bad rule cannot starve the rest. For very large documents I would pre-extract fields or use a streaming processor such as Saxon, and I would monitor latency per rule and automatically disable slow rules while notifying their owner.
Why this question is asked
A rules engine that lets users write their own XPath is powerful: business analysts can add a check on a partner document without a release. It also means that code written by thousands of people, with no review, runs on every document inside our service. Interviewers use this scenario to see whether we can find the real causes of the CPU spikes and design guard rails that keep the engine both fast and safe. In this answer, we will look at where the time goes, fix the compile cost, restrict expressions at save time, isolate evaluation, handle big documents, and add monitoring that removes bad rules automatically.
1Where the CPU Goes
There are usually two separate problems hiding behind one symptom. The first is a constant cost: if the engine calls xpath.evaluate(String, ...) for every rule on every document, each call parses and compiles the expression again. With 5,000 rules and 200 documents a minute, that is a million compilations a minute, which alone can keep several cores busy.
The second is the few expensive rules. XPath 1.0 lets anyone write expressions whose cost grows quickly with document size. //item scans every node. //item[. = //order/item] compares every item with every order item, which is quadratic: on a document with 10,000 items that is 100 million comparisons, and that is the rule that takes seconds. Because the expressions are user-provided, we cannot fix them one by one; we need a system that keeps them cheap.
2Fix 1: Compile Once, Reuse per Thread
An XPathExpression is the compiled form of an expression. Compiling once and reusing it removes the constant cost. The catch is that XPath and XPathExpression objects are not thread-safe, so we cannot share a single compiled object across request threads. We keep compiled expressions per thread, for example a ThreadLocal map keyed by rule id and version, or a small pool per rule.
Keying by rule version means an edited rule gets a fresh compilation automatically. With a fixed-size worker pool, the number of copies per rule is bounded by the number of worker threads, so memory stays predictable.
3Fix 2: Validate and Restrict at Save Time
The cheapest bad rule is the one we never accept. When a user saves an expression, we compile it to catch syntax errors, and then apply limits that reflect our documents. A maximum length, for example 500 characters, keeps expressions understandable. An allowlist of functions (count, sum, contains, starts-with, normalize-space and a few more) blocks surprises. Disallowing // for document types known to be large, or requiring an absolute path from the root, avoids full scans. Nested predicates that refer back to the document with // are a strong sign of quadratic cost and can be rejected or flagged for review.
With FEATURE_SECURE_PROCESSING enabled on the XPathFactory, the JDK refuses extension functions, the mechanism by which an XPath can call Java methods, which would otherwise be a remote code execution risk. We also run each new rule against a set of the largest real sample documents at save time and reject it if it exceeds a budget such as 20 ms. The user gets the feedback immediately, while they still remember what they wrote.
- Compile the expressionsyntax errors rejected
- Within length and function allowlist?YesContinueNoReject with the reason
- Uses // or back-references on a large doc type?YesReject or send for reviewNoContinue
- Run on the largest sample documentstime each evaluation
- Under the 20 ms budget?YesSave as activeNoReject, show the measured time
5 steps in order. Play them, or step through them one at a time.
4Fix 3: Isolate Evaluation With Time Budgets
Even with validation, some rules will be slow on some documents. We do not want one of them to delay all others. We run evaluation on a bounded executor, a fixed pool of worker threads with a bounded queue, and give each document a time budget. If a rule exceeds its budget, the caller stops waiting, records the timeout and continues with the remaining rules.
But there is a catch worth saying out loud in an interview: the JDK's XPath evaluation does not check for interruption, so cancel(true) does not stop a running evaluation; the worker thread keeps burning CPU until the expression finishes. The timeout protects the caller's latency, not the CPU. That is why validation at save time and automatic disabling matter so much: they keep the slow rules from running at all. Where we need a hard stop, we can run untrusted rules in a separate worker process with its own CPU limit, which we can kill.
5Large Documents: Pre-Extract or Stream
When documents are large, say 100 MB, even simple rules cost a lot because XPath needs the whole DOM in memory, and each rule walks it. Two approaches help. We can pre-extract: most rules look at a few dozen well-known fields (order total, country, currency, item count), so we stream the document once with StAX, extract those fields into a small map or a small DOM, and let rules run on that. Thousands of rules then evaluate against a tiny tree.
Alternatively, for rules that must see the whole document, a streaming processor such as Saxon with XSLT 3.0 streaming can evaluate a restricted set of expressions in one pass without building a full tree. Streaming imposes rules on which expressions are allowed, which fits nicely with our save-time validation; check the Saxon edition and version for streaming support.
6Monitor Each Rule and Disable Slow Ones
Finally, we record latency per rule as a metric, for example a histogram tagged by rule id, and keep a rolling count of timeouts. A rule whose 99th percentile exceeds its budget, or that times out three times in ten minutes, is automatically disabled, and its owner gets a notification with the rule, the measured times and a sample document id. A dashboard of the slowest rules lets the platform team spot patterns and improve the validation, for example by adding a new forbidden construct.
This closes the loop: users can still write their own rules, but the system protects itself without waiting for someone to notice a CPU graph at three in the morning.
7Follow-up questions
Why not just give the service more CPU?
Because the cost of a quadratic rule grows with the square of the document size, so more cores only buy time until the next large document or the next careless rule. The compile fix gives a constant-factor saving for free, and validation plus disabling removes the unbounded cases.
Could we translate the rules into Java code instead?
For a fixed set of common checks, generating Java predicates or using a rules engine with its own safe language can be faster and safer. But it takes away the flexibility users rely on. A common compromise is to offer a library of predefined checks for the frequent cases and keep restricted XPath for the rest.
How do namespaces fit into user-provided expressions?
Each rule stores its prefix to URI mappings alongside the expression, and we set a NamespaceContext from them when compiling. Validation checks that every prefix used in the expression is declared, which turns a silent empty result into a save-time error.
8Conclusion
In this answer, we separated the two causes of CPU spikes: compiling expressions on every call and a few rules with explosive cost. We cached compiled XPathExpression objects per thread, validated and restricted expressions at save time with secure processing blocking extension functions, ran evaluation in a bounded executor with time budgets while remembering that XPath evaluation ignores interruption, pre-extracted fields or streamed with Saxon for large documents, and monitored latency per rule to disable slow ones automatically and notify their owners.
Open with
I would look at two causes. First, if we call evaluate with the expression string, every evaluation recompiles it, and with thousands of rules on every document that is a big constant cost.
Then, if they want more
So I would compile each rule once into an XPathExpression and cache it. XPath objects are not thread-safe, so the cache is per thread, keyed by rule id and version. Second, a few rules are expensive by nature, things like double slash scans or predicates that compare every node with every other node, which is quadratic on large documents.
For those, I would validate at save time: compile, enforce a length limit and a function allowlist, forbid double slash on large document types, enable secure processing so extension functions are rejected, and run the rule against our biggest sample documents with a budget like 20 milliseconds, rejecting it with the measured time if it is slower.
At runtime I would evaluate in a bounded thread pool with a timeout per rule, so one rule cannot hold up the others, while being honest that the JDK's XPath ignores interruption, so the timeout protects latency, not CPU; a separate process is the hard stop.
For very large documents I would pre-extract the commonly used fields with StAX or use Saxon streaming. And I would track latency per rule, automatically disable rules that keep exceeding their budget, and notify the owner.
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 official documentation for the version you use. 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 "A rules engine stores thousands of user-provided XPath expressions applied to partner...": https://scrivio-interview-library.netlify.app/java/xml-processing/3a91f025fd/