Picture a support inbox that routes tickets with a function called route_ticket. It began as three regular expressions: one for "refund", one for "can't log in", one for "invoice". Four years later it holds 140 patterns, ordered by a priority nobody can explain, written by eleven people, six of whom have left. A customer writes "I was charged twice and now I cannot sign in to see the receipt". Pattern 12 sends it to billing. Pattern 87, which sits below it, would have sent it to account access, and the ticket really needs both. Nobody dares to reorder the list, because the last time someone did, password resets landed in the sales queue for a day.
The failure here is not that regular expressions are bad. They are exact, fast and auditable for the thing they were designed for: matching the shape of a string. The failure is that the team asked a string-shape tool to answer a meaning question ("what does this customer want?"). Every new phrasing, language, typo or product name adds another pattern, and every pattern interacts with the others through ordering. This article explains how to recognise that situation, how a small learned judgment model can take over the meaning part, and how to migrate without a flag-day rewrite.
1. Where regex and rule engines stop being the right tool
A pattern is a precise description of a set of strings. It works beautifully when the set you care about has a crisp boundary: an ISO date, an order number with a checksum, a UUID, a log line produced by code you control. It starts to hurt when the set you care about is defined by intent or meaning, because the set of strings that express one intent is open-ended. "Cancel my plan", "please stop billing me", "I want out", "how do I unsubscribe" and "end subscription pls" share an intent and almost no tokens.
Teams usually notice the problem through symptoms rather than theory:
- The pattern file grows monotonically. Nobody deletes a pattern because nobody knows what it still protects.
- Fixes are order-dependent. Moving a rule changes behaviour for inputs unrelated to the bug you were fixing.
- Precision and recall trade against each other inside a single expression: widen it to catch variants and it starts matching things it should not.
- Tests are mostly examples that someone happened to remember, so the suite proves the patterns still match the past, not that they handle the future.
- New languages or channels (voice transcripts, chat abbreviations) mean a second copy of the whole file.
There is also a security dimension. Patterns with nested quantifiers can backtrack catastrophically on adversarial input, a class of bug known as ReDoS. A backtracking engine can take time exponential in the input length on a pattern like (a+)+$ against a long run of a characters followed by a different character. A pattern that sits on a request path and looks harmless in review can turn into a denial-of-service vector. Engines with linear-time guarantees, such as RE2-style automata, remove that risk, but they do not fix the meaning problem.
The two jobs hiding inside one rule file
Read a mature rule file closely and you will find two different jobs mixed together. The first is extraction and validation: pulling an order id out of a line, checking a currency format, rejecting a malformed header. The second is judgment: deciding which queue, which severity, whether this is spam, whether two records describe the same customer. The first job should stay as code, usually as a regex or a parser. The second is what a model is for. Most successful migrations are really a separation of these two jobs, with the regexes that remain getting shorter and more honest.
2. What a "judgment model" is and why it can be fast
A judgment model, in the sense used here, is a small model with a narrow contract. It does not chat. It takes a bounded input and returns a typed decision: one choice out of a fixed set, a score in a range, or a structured extraction against a schema. Three shapes cover most of what rule engines do:
- Choice: pick one label from a closed list, with a confidence. Routing, intent, language, category.
- Score: return a number on a defined scale. Priority, risk, relevance, similarity.
- Extraction: fill a schema from free text, with a way to say "not present".
A typed-decision stack treats decisions this way: typed inputs, typed outputs, a closed set of outcomes and an explicit fallback. Whether the model behind a decision is hosted by a vendor, trained in-house, or an open-weights model you run yourself is an implementation detail behind that contract, and it should stay swappable.
The speed claim deserves care. Latency depends on model size, hardware, batching and where the call runs. As a rule of thumb, a classifier based on a small encoder (tens to low hundreds of millions of parameters) running on a CPU or a modest accelerator can answer in single-digit to tens of milliseconds for short inputs, while a call to a large generative model over the network is typically hundreds of milliseconds to seconds. A heavily optimised small model on suitable hardware can get below a millisecond for very short inputs, but you should treat "sub-millisecond" as a property to measure on your own inputs and hardware, not as a given. The architectural point is that a narrow model with a closed output set does not need to generate tokens autoregressively, so it avoids the main source of LLM latency.
3. Choosing the replacement: four options compared
A learned model is not the only way out of a rule swamp. Before reaching for one, compare the realistic options. The table below is qualitative on purpose: the actual numbers depend on your inputs and infrastructure.
| Approach | Handles paraphrase | Typical latency class | Explainability | Main failure mode | Best fit |
|---|---|---|---|---|---|
| Regex / parser | No | Microseconds | Exact (the match is the reason) | Rule rot, ordering bugs, ReDoS on backtracking engines | Formats with a crisp boundary |
| Keyword scoring / rule engine | Weakly | Microseconds to low milliseconds | High (weights are visible) | Hand-tuned weights drift as vocabulary changes | Small, stable vocabularies |
| Small trained classifier or judgment model | Yes, within its training distribution | Roughly milliseconds on CPU, less with acceleration | Medium (confidence, nearest examples) | Silent degradation on unseen inputs; needs labelled data | Closed-set decisions on short text at volume |
| Large generative model with a prompt | Yes, broadly | Hundreds of milliseconds to seconds | Medium (it can explain, the explanation may be wrong) | Variance, cost per call, format drift | Low volume, open-ended, high-value cases |
Two things stand out. First, nothing in the table dominates. The large model is the most flexible and the worst fit for a hot path. The regex is the best fit for a format and the worst for intent. Second, the small judgment model sits in the middle precisely because it gives up open-ended generation to gain speed and a typed contract. If your decision really is a closed set on short text, that trade is usually favourable. If your decision needs to read a ten-page contract and weigh clauses, it is not a classifier problem.
4. A worked migration: the shadow-mode harness
The safest way to replace a rule engine is to never replace it in one step. Run the model beside the rules, on live traffic, with the rules still making the decisions. Log both answers, compare, and only promote the model where it demonstrably agrees or wins. The harness below shows the skeleton in TypeScript. The Judge interface is deliberately generic: put whatever model or service you use behind it.
// Shadow-mode comparison of a legacy rule router against a model-backed judge.
type Queue = "billing" | "access" | "sales" | "other";
interface Decision {
label: Queue;
confidence: number; // 0..1; rules report 1 when they match, 0 when they fall through
}
interface Judge {
decide(text: string): Promise<Decision>;
}
const legacyRules: Array<[RegExp, Queue]> = [
[/refund|charged twice|invoice/i, "billing"],
[/can'?t (log ?in|sign ?in)|password/i, "access"],
[/pricing|quote|demo/i, "sales"],
];
function legacyRoute(text: string): Decision {
for (const [pattern, label] of legacyRules) {
if (pattern.test(text)) return { label, confidence: 1 };
}
return { label: "other", confidence: 0 };
}
export async function route(text: string, judge: Judge, log: (e: object) => void): Promise<Queue> {
const legacy = legacyRoute(text); // still authoritative
try {
const started = performance.now();
const model = await Promise.race([
judge.decide(text),
new Promise<never>((_, rej) => setTimeout(() => rej(new Error("judge timeout")), 50)),
]);
log({
kind: "shadow",
agree: model.label === legacy.label,
legacy: legacy.label,
model: model.label,
confidence: model.confidence,
ms: Math.round(performance.now() - started),
});
} catch (err) {
log({ kind: "shadow_error", message: String(err) }); // never affects the response
}
return legacy.label;
}
Three details in that code matter more than they look. The model call has a hard timeout, so a slow judge cannot slow the real path. Errors are logged and swallowed, so shadow mode cannot take the router down. And the function returns the legacy label no matter what: at this stage the model is only being observed.
Turning the log into a decision
After a few thousand real inputs you have a disagreement log. Do not read it as "the model is X percent accurate". Agreement with the legacy rules is not accuracy, because the rules are wrong some of the time. Instead, sample the disagreements and label them by hand. For each one decide who was right: the rule, the model, or neither. That sample gives you three useful things at once: an honest estimate of both systems' error on the cases where they differ, a set of failure categories (for example, "model confuses refund requests with refund policy questions"), and the beginning of a labelled evaluation set that you will keep using.
Also look at cases where the rules fell through to other. These are where the rule engine's recall problem is hiding, and they are often where a model adds the most value with the least risk, because the fallback bucket was already low quality.
5. Confidence, thresholds and the fallback path
A closed-set classifier will always return some label, even for an input unlike anything it saw. The defence is to treat confidence and abstention as first-class parts of the contract. A common promotion design has three zones:
- High confidence: accept the model's label.
- Middle band: fall back to the legacy rules, or to a stronger and slower model, or to a human queue.
- Low confidence: route to a safe default such as "needs triage", never to a specific team.
Choose thresholds from your labelled sample, not from intuition. For each candidate threshold, compute how many decisions the model would take, and what the error rate is on that subset. Raising the threshold reduces both coverage and errors; the right point is where the error rate on accepted decisions matches what your process can tolerate, and the coverage is still worth the engineering effort. Be aware that raw model confidence is often poorly calibrated, meaning that "0.9" does not mean "right nine times out of ten". Calibration techniques such as temperature scaling on a held-out set help, and so does simply checking a reliability table: bucket decisions by reported confidence and measure the real hit rate in each bucket.
Keep the fallback live even after the model takes over. A rule engine you can fall back to is cheap insurance, and it also gives you a way to detect drift: if the share of decisions where model and rules disagree rises steadily, something about the input distribution changed.
6. Failure modes you will meet
Models fail differently from rules, and the differences should be planned for rather than discovered.
Silent degradation
A regex that stops matching shows up as a rise in the fallback bucket. A model that stops fitting the data shows up as plausible-looking wrong answers. Monitor the distribution of predicted labels over time and the confidence histogram, and keep a small rolling sample of decisions labelled by a person.
Distribution shift
New product names, a marketing campaign, a new language, or a change in how a channel formats text can all move inputs away from the training set. Rules cope badly with this, but models can cope worse because they fail without a visible signal. Retrain or refresh on a schedule that matches how quickly your vocabulary changes, and add new categories as explicit labels instead of letting them land in the nearest existing one.
Label leakage and circular evaluation
If you train the model on the output of the old rules and then evaluate it against the same rules, you measure agreement with the rules, including their bugs. Build the evaluation set from human labels, and keep it separate from any data used to train or tune.
Adversarial and unusual input
Anything that reaches a model from outside, such as user text, is untrusted input. A narrow classifier with a closed output set is much harder to hijack than a generative assistant, because it has no instructions to override and no free-form output to abuse. It can still be fooled into a wrong label, so do not let a single classifier decision authorise something irreversible, such as deleting data or issuing a refund, without a separate check.
7. When not to replace the regex
Judgment is expensive in the ways that count: it needs data, labelling effort, monitoring and an owner. Leave the pattern alone in these cases:
- The input has a formal grammar. Parse it. A date, a semantic version, an IBAN, a cron expression and a URL are not machine-learning problems.
- The decision must be reproducible and explainable to an auditor in terms of a written rule, for example a legal or compliance cut-off.
- The volume is low and the cost of a wrong answer is tiny, so the maintenance cost of a model exceeds the pain it removes.
- You have no way to collect labels, and no way to observe outcomes. A model without feedback is a rule you cannot read.
- The rules are few, stable and well understood. A twelve-line routing function that nobody has touched in two years is a feature.
A practical middle path is to keep exact patterns for the exact things (ids, formats, hard blocklists) and use the model only for the fuzzy decision. This shrinks the regex file to the part that is genuinely about string shape, makes each remaining pattern easy to test, and moves the long tail of paraphrase to the component designed for it.
8. Decision checklist and common mistakes
Use this checklist before you start a migration:
- Can you name the decision as a closed set of outputs (or a score range) with a defined "none of these"?
- Do you have, or can you collect, a few hundred human-labelled examples per important class, drawn from real traffic?
- Do you know the latency budget of the call site, and have you measured the candidate on that hardware?
- Is there a safe default for low-confidence and error cases?
- Can you run in shadow mode for long enough to see a full weekly and monthly cycle of your traffic?
- Does someone own the model after launch: retraining, thresholds, label review?
- Is the rollback one configuration change?
The mistakes that show up most often:
- Replacing everything at once. Migrate one decision at a time, starting with the one where the rules perform worst.
- Measuring agreement instead of correctness. Agreement with a flawed baseline is not quality.
- Skipping abstention. A classifier that must always answer will answer wrongly with confidence.
- Using a generative model where a classifier fits. It works in the demo and costs more, runs slower and varies more in production.
- Deleting the old rules immediately. Keep them as a fallback and a drift detector for at least a full release cycle.
- Letting the model touch the contract. The output schema is the interface. Validate it on the way out; reject anything outside the closed set.
9. What to do on Monday
You do not need a platform to begin. A first useful week looks like this:
- Pick one rule file with a real pain history and add logging of input, matched rule and outcome, with personal data removed according to your policy.
- Pull a few hundred recent inputs, label them by hand into the closed set, and note how often the existing rules disagree with you. That number is your baseline.
- Implement the shadow harness above with any judge you can stand up quickly, even a stub that returns the legacy label, to prove the plumbing and the logging.
- Swap in a real candidate, run for a week, review the disagreements, and write down the failure categories.
- Decide on thresholds from the labelled sample, enable the model only for the high-confidence zone, and keep the rules as the fallback.
Short FAQ
Will the model make the regexes obsolete? No. It replaces the judgment parts of the file and leaves the format-matching parts alone, usually in cleaner form.
Do I need a large model? For closed-set decisions on short text, usually not. Start with the smallest model that clears your labelled evaluation set, and only move up if it fails on categories you care about.
How do I explain a decision to a customer or auditor? Log the input, the label, the confidence and the model version for every decision. For regulated decisions, keep an explicit rule as the decision of record and use the model only to prioritise or pre-fill.
What if I cannot get labels? Then start with the logging step. Collecting outcomes is the prerequisite, and some teams discover during that step that the rule file was simpler than it felt.