Making our secret scanner 50× faster without changing a single finding
Prism scans every request body for keys and personal data before it leaves your network. At 1.4 MB/s a 16 MiB request waited 12 seconds. Here is how we made it 50 times faster and proved it finds exactly the same things.
Prism is a self-hosted AI gateway. Every request your tools send to a model passes through it, and before it leaves your network the traffic guard looks through the body for credentials and personal data: API keys, bearer tokens, private keys, e-mail addresses, phone numbers. Depending on policy, it records, blocks or redacts what it finds.
In October we stopped truncating that scan. Before, the guard looked at the first part of a large body and let the rest through; that is exactly the part where a pasted log or an attached file hides a key. After the change it read every byte, and we measured what that cost: about 1.4 MB/s. A 16 MiB request, which a coding agent can produce by attaching a few files, waited 12 seconds on one core before it was even sent.
Two days later the same scan ran at about 70 MB/s, with the same findings on every input we could construct. This post is about how, and about the part that took most of the work: proving "the same findings".
Twenty regular expressions, one megabyte
The secret detector is a list of 20 rules. Each is a regular expression with a little post-processing: an entropy check, a digit-and-letter check, an allowlist. Some are specific (an AWS access key id starts with AKIA), some are not (password = ..., a generic high-entropy token). On top of those the traffic guard has its own rules for bearer tokens, e-mail, phone numbers and IPv4 addresses.
The obvious implementation runs every rule over the text with FindAllStringSubmatchIndex. Go's regexp is RE2: matching time is linear in the input, guaranteed, and nobody can hand it a body that takes exponential time. Linear is not the same as fast, though. An unanchored search tries to start a match almost everywhere, and in ordinary text almost every attempt fails within a few bytes. Twenty-odd rules means twenty-odd such passes over the whole body. Nothing is wrong with any single rule; there are just a lot of them, and almost all of the work finds nothing.
Every match contains a literal
Almost every rule has text that every match must contain. An Anthropic key contains sk-ant-. An AWS key id starts with AKIA. An e-mail address contains @. A bearer header contains bearer. If none of these literals occur in a body, none of those rules can match, and the expensive pass is wasted.
That is the classic prefilter, the idea behind tools like ripgrep and Hyperscan. The part that matters for correctness is where the literals come from. We do not write them down by hand next to each rule, where they would drift from the regex the first time someone edits it. At start-up Prism parses each rule with regexp/syntax and derives from the syntax tree:
- the set of literals every match must contain;
- how far from the start of the match each literal can sit (a minimum and a maximum).
Then the scan becomes two steps:
- One Aho-Corasick pass over the body finds every occurrence of every rule's literals at once, case-insensitively.
- Anchored matching. For each hit, the rule's regex runs anchored,
\A(?:re), only at the start positions the hit allows. Most rules allow one position or a short range, so the regex reads a few dozen bytes instead of the whole body.
One rule, a generic high-entropy token, has no literal at all: it is a single unbounded ASCII character class. That one becomes a plain byte-run scanner, because a match of such a pattern is just a maximal run of those bytes. A rule from which nothing usable can be derived keeps the old full pass. Today all 20 rules get a plan.
Where it almost broke
Deriving literals is easy to get almost right. The cases where "almost" would have meant a missed key were the interesting ones.
The Kelvin sign. Rules are case-insensitive: (?i)api_key must match API_KEY. The obvious prefilter lowercases ASCII and searches for api_key. But in Go, (?i)k also matches U+212A, the Kelvin sign K, and (?i)s matches U+017F, the long s ſ. Both are Unicode simple case folds of ASCII letters:
re := regexp.MustCompile(`(?i)api_key`)
re.MatchString("api_\u212Aey") // true: "api_Key" with a Kelvin signAn ASCII-only prefilter would never see that text as a candidate, so a rule that matched before would silently stop matching. Nobody types a Kelvin sign into an API key name. But a scanner that can be bypassed by one Unicode character in the key name is not a scanner. The literal set now expands each letter to all of its case folds, which gives k and s a second alternative. Rules also carry Russian key names, written as character classes such as [Пп][Аа][Рр][Оо][Лл][Ьь] for «пароль»; small classes like these are expanded into literals the same way.
Word boundaries. Many rules start with \b. Whether \b holds at a position depends on the byte before it, and an anchored regex run on a slice of the body does not see that byte. Run on the slice alone, \btoken would match inside mytoken. When the byte before the candidate is a word byte, the anchored attempt includes one byte of left context, \A(?s:.)(?:re), so \b gives the same answer as it does in the full text.
Hostile input. A prefilter has a worst case: text built to be full of literals. A body that is megabytes of repeated eyJ, the start of a base64-encoded JSON token, produces a hit every three bytes, and each hit starts an anchored attempt. To keep this linear, the anchored attempts read through a budgeted reader. Once a rule has read more than the length of the body plus 64 KiB, it gives up on the fast path and falls back to the full regex pass. That input is exactly as slow as before, not slower, and still linear.
Amdahl's law shows up
With the detector fixed, the profile moved. The traffic guard's own rules for e-mail, phone, IPv4 and bearer tokens were now most of the time, about 300 ms per MiB. They got the same machinery: e-mail has @, IPv4 has ., bearer has bearer, and for the rules that start with \b the boundary check comes first. Text normalisation, which strips zero-width and lookalike characters before the scan, now skips its per-rune table lookup unless a byte that can start such a character is present.
What remains in a full traffic guard pass is mostly JSON decoding, the two literal passes, and a couple of anchored attempts per line for phone and IPv4 rules in text that contains digits.
The numbers
Measured on one pinned core of an Intel Core i5-13500, the commit before the change against the commit after, with the repository's own Go benchmarks. The body is ordinary English text, wrapped in a chat completion request, with an AWS key id, an e-mail address, a phone number, an IP address, a bearer token and a password planted in the middle. Each figure is the median of three runs.
| Body size | Full traffic guard, before | After | Secret detector alone, before | After |
|---|---|---|---|---|
| 1 MiB | 0.68 s (1.5 MB/s) | 15 ms (68 MB/s) | 0.63 s (1.7 MB/s) | 2.8 ms (376 MB/s) |
| 4 MiB | 3.04 s (1.4 MB/s) | 63 ms (67 MB/s) | 2.48 s (1.7 MB/s) | 10.8 ms (388 MB/s) |
| 16 MiB | 12.9 s (1.3 MB/s) | 236 ms (71 MB/s) | 9.78 s (1.7 MB/s) | 42 ms (396 MB/s) |
The full traffic guard, which is what a request actually waits for, is about 50 times faster. The secret detector on its own is about 230 times faster. Bodies with no secrets at all give the same picture: 1.2 MB/s before, about 70 MB/s after.
We are not claiming this is the fastest scanner around. ripgrep and Hyperscan reach gigabytes per second with SIMD, and our remaining cost is mostly JSON decoding. The point is that a 16 MiB request no longer waits seconds to be checked, so there is no reason left to skip checking it.
"The same findings": proving it
A faster scanner that misses one key is worse than a slow one. Nobody notices the missed key until it is in a provider's log. So the old implementation did not go away. It stays in the test suite as an unexported reference, scanReference, and a differential test compares the two: the final findings and also the raw per-rule match lists before post-processing. The inputs are:
- every line of the shared golden set, raw and normalised;
- 6,000 random texts with planted secrets for every rule: case variants, Cyrillic keywords, the Kelvin sign and long s, mutated and truncated secrets, adjacent and overlapping candidates, invalid UTF-8, zero-width characters;
- every candidate at the very start and very end of the text, and next to long runs of word characters, where the
\bhandling matters; - flooding inputs that exhaust the budget and force the fallback;
- empty and very short inputs.
The traffic guard's PII and bearer rules have their own differential test against a regex-only reference, on 3,000 random texts.
To check that the tests can actually fail, we ran ten hand-made mutations of the fast path: off-by-one start offsets, a dropped case fold, a missing left-context byte, and so on. The tests caught eight. The other two did not change any result: one removed a narrowing that only saves work, and the other was dead code, which we then deleted.
What this does not fix
- Adversarial input is not faster. A body built to defeat the literal search falls back to the old full pass. It is linear but slow, as before.
- The rules are the same rules. This change makes the scanner faster. It does not make it smarter. A regex for
password = ...still cannot tell a real password from a placeholder. That is a separate project: Prism now runs a small local classifier in shadow mode next to the rules, to learn where they are wrong before it is allowed to decide anything. - JSON decoding is now the biggest cost of a full pass, and we have not touched it.
Where this runs in Prism
The traffic guard sits in front of every request Prism sends to a model provider:
- Credentials and personal data are checked in the whole body, not in a prefix. Recording, blocking or redacting is a policy you set per direction.
- It costs milliseconds, so large agent requests with attached files and logs are checked like small ones, and Prism does not need to skip anything to stay fast.
- It runs on your machine. The scan happens inside Prism, before the request leaves your network. Nothing is sent anywhere to be checked.
The change shipped in Prism v0.49.0. The benchmarks are in the repository: BenchmarkProtectLargeBody and BenchmarkProtectLargeBodySecrets for the traffic guard, and BenchmarkScan for the secret detector.
Questions and answers
How fast is Prism's traffic guard?
About 70 MB/s for a full check of a request body (credential and personal-data rules, including JSON decoding) on one core of an Intel Core i5-13500. A 16 MiB request is checked in about a quarter of a second. Before v0.49.0 the same check ran at about 1.4 MB/s.
Did the speed-up change what Prism detects?
No. The previous implementation stays in the test suite as a reference, and a differential test checks that both return the same findings and the same raw matches on the golden set, on 6,000 random texts with planted secrets, and on edge and flooding inputs.
What is a regex prefilter?
A cheap search for literal text that every match of a regular expression must contain. The expensive regex then runs only where that text occurs. Prism derives the literals automatically from each rule's syntax tree, finds all of them in one Aho-Corasick pass, and runs each rule anchored at the positions the hits allow.
Why does the Kelvin sign matter for case-insensitive matching?
In Go's regexp, (?i)k also matches the Kelvin sign U+212A, and (?i)s matches the long s U+017F. A prefilter that only lowercases ASCII would skip text the full regex matches, so a rule could stop matching. Prism's literal set includes every case fold of each letter.
Can someone slow the scanner down with crafted input?
They can make it as slow as it was before, but not slower. A rule whose anchored attempts read more than the body length plus 64 KiB falls back to the full regex pass. Go's regexp keeps every pass linear in the input size.