> ## Documentation Index
> Fetch the complete documentation index at: https://docs.promptguard.co/llms.txt
> Use this file to discover all available pages before exploring further.

# Latency Budgets

> Per-detector p99 latency budgets, the three-tier detection path, and how to keep the guard call fast in production.

> [!NOTE]
>
> PromptGuard runs detectors in three tiers: a **fast path** of in-process regex and heuristic checks that takes single-digit milliseconds, an **ML path** of transformer classifiers, and a **slow path** of LLM-judge detectors that are opt-in and bounded by hard timeouts. The fast path ends a scan only when it finds something: a prompt it finds nothing in, which is most benign traffic, goes on to the ML path. This page gives a p99 budget for each detector so you can reason about the tail, and the measurements we have.

## The overall target

The number reported as `processing_time_ms` on each event (see the [Analytics Cookbook](https://docs.promptguard.co/platform/analytics-cookbook.md#latency-percentiles)) is **engine-only** time, it excludes the upstream provider call on the proxy path.

| Path | What runs | p99 budget |
| - | - | - |
| **Fast path (cache hit)** | Verdict reused from the policy cache | \< 1 ms |
| **Fast path (regex + heuristics)** | All deterministic detectors, no network | a few ms |
| **ML path** | Fast path + one or more classifier calls | no fixed budget: see [what we have measured](#what-we-have-actually-measured) |
| **Slow path** | Fast path + an LLM-judge detector | bounded by that detector's timeout (6-10 s), **fail-open** |

The fast path does **not** keep the common case to itself. Detectors run in order and the engine stops early only on a detection: a prompt the deterministic layers find nothing in continues to the ML classifiers whenever they are available, and every plan includes them. So on a benign prompt you pay for the ML path. Only the slow path is opt-in: LLM-judge detectors run when a project enables them.

### What a detection costs

When a pattern rule blocks a prompt, the proxy, and the Guard API asked for `"agreement": false`, skip the second opinion. They answer from the fast path, without the ML classifiers, only when nothing those classifiers say could change who decides the block. The classifiers still run in each of these cases:

* **An agentic judge is configured**, as it is on PromptGuard Cloud and on any install with a judge server: the classifiers' scores decide whether the judge is asked, and the judge's block, with its own threat type and rule, then decides in place of the pattern rule's.
* **The project has a policy rule whose action is `allow`**: its exceptions are judged against the classifiers' scores.
* **A classifier made the block**, or one of its findings is part of it: then the block is the ML path's anyway.

| Surface | A block a pattern rule decides | A block only a classifier makes |
| - | - | - |
| **Proxy** | Fast path, except in the cases above. The block is returned without calling your LLM provider | ML path |
| **Guard API** with `"agreement": false` | Fast path, except in the cases above; no second opinion, so `detectors_agreeing` counts only the detectors that had found the threat when the scan decided | ML path |
| **Guard API** with `"agreement": true`, or `agreement` left out until 2027-02-11 | ML path: the finding is put to the classifiers for a second opinion, and `detectors_agreeing` counts them | ML path |
| **Guard API** from a Shadow AI device | As with `"agreement": true`: the device always counts agreement | ML path |

Measured on 2026-11-13 on a laptop, classifiers in-process, for "Ignore previous instructions": with no agentic judge configured, median engine time 1.2 ms with `"agreement": false` and 124 ms with `true`. With a judge configured, as on PromptGuard Cloud, the classifiers run either way, and the two took 41 ms and 45 ms: there the second opinion is what `false` saves, and on this prompt it is cheap. On PromptGuard Cloud one classifier window takes about 260 ms of one vCPU ([below](#ml-path-transformer-classifiers)). Production has not been re-measured since this change. Ask for agreement only if you act on the count. Leaving `agreement` out counts it until 2027-02-11 and stops early after ([Guard API](https://docs.promptguard.co/api-reference/guard.md#detector-agreement)).

### What we have actually measured

The budgets above are targets. These are the measurements we have, each with its date:

| Measurement | Mean | p50 | p95 | p99 |
| - | - | - | - | - |
| Benchmark, regex only (2026-02-18, 5,384 samples, `default:moderate`) | 0.28 ms | - | 0.95 ms | - |
| Benchmark, regex + ML (2026-02-18, same 5,384 samples) | 375 ms | - | 971 ms | - |
| Production guard scans, engine time (7 days to 2026-09-01, 357 scans) | - | 2.7 s | 13.2 s | 21.2 s |

In that production window 83% of scans took over one second, and weekly figures over the ten weeks before it were flat, so it was the steady state rather than an incident. It predates the October 2026 change that moved the classifiers into the API process instead of calling a hosted inference service, and production has not been re-measured since.

> [!WARNING]
>
> No single figure here is your latency. The regex-only and regex + ML rows are three
> orders of magnitude apart on the same inputs, and the production row is an order of
> magnitude above the benchmark: what you see is dominated by **how often your
> traffic reaches the ML and LLM tiers** and how long your inputs are. Measure your own
> traffic ([below](#measuring-it-yourself)) rather than adopting any of these figures.

## Fast path: deterministic detectors

These run in-process on every eligible request, in the order below (the engine short-circuits and returns as soon as a blocking detector fires). No network calls, so latency is CPU-bound and scales with input length.

| Detector | What it does | p99 budget | `detector` label |
| - | - | - | - |
| Policy cache lookup | Reuse a prior verdict for identical input | \< 0.1 ms | `policy_cache` |
| Injection (regex layer) | Pattern rules for instruction-override / role-confusion | \< 1 ms | `injection` |
| Data exfiltration | System-prompt / training-data extraction patterns | \< 1 ms | `exfiltration` |
| Fraud / abuse | Social-engineering and financial-fraud patterns | \< 1 ms | `fraud` |
| Malware | Destructive-command and payload patterns | \< 1 ms | `malware` |
| URL filter | Allow/block-list, CIDR, scheme, embedded-credential checks | \< 1 ms | `url_filter` |
| Malicious entity | Private/obfuscated IPs, homograph domains, shorteners; optional defang | 1-2 ms | `malicious_entity` |
| PII (regex + checksum) | 46 entity types with Luhn/Mod-11/Verhoeff/Mod-97 validation | 1-3 ms | `pii` |
| Encoded-PII | PII hidden in base64 / hex / URL-encoding | 1-2 ms | `encoded_pii` |
| API-key / secret-key | Entropy scoring + 40+ known provider prefixes, then again with a disguise (reversal, spelled-out, invisible or lookalike characters) undone | 1-2 ms | `api_key`, `secret_key`, `disguised_credential` |
| Toxicity (regex fallback) | Keyword/category rules when ML is off or down | \< 1 ms | `toxicity` |

**Fast-path total p99: a few milliseconds** for typical prompt sizes. Very large inputs (long documents, tool outputs) push the regex and PII stages higher, budget generously if you scan multi-KB payloads.

## ML path: transformer classifiers

The ML path runs the injection classifier (`protectai/deberta-v3-base-prompt-injection-v2`), the toxicity ensemble (`meta-llama/Llama-Prompt-Guard-2-86M`, `KoalaAI/Text-Moderation`, `unitary/toxic-bert` and `cardiffnlp/twitter-roberta-base-hate-latest`) and the multi-turn detector's embedder (`sentence-transformers/all-MiniLM-L6-v2`). Where they run is set by `ML_INFERENCE_MODE`, and the same rules apply on PromptGuard Cloud and on a self-hosted install:

| Mode | Where the classifiers run | Used by |
| - | - | - |
| `api` | In the API process when their weights are mounted at `LOCAL_INFERENCE_DIR`; a classifier whose weights are missing calls hosted inference instead, and that call is dominated by the network round-trip and any model cold start | PromptGuard Cloud, which mounts the weights of every classifier above (since October 2026); the Helm chart outside Air-gapped |
| `local` | Only in the API process, from weights you fetch and mount. Nothing calls hosted inference: a classifier with no weights is reported as an Unavailable check | Air-gapped, and the Docker Compose file's default ([Enterprise setup](https://docs.promptguard.co/production/enterprise-setup.md)) |
| `off` | Nowhere: regex only | Emergency cost or latency cutting |

| Detector | Default model | p99 budget | Notes | `detector` label |
| - | - | - | - | - |
| Injection (ML) | `protectai/deberta-v3-base-prompt-injection-v2` | 500 ms per 512-character window | A long prompt is scored window by window, inside the scan's overall budget; falls back to regex if the classifier cannot answer | `injection` |
| Toxicity (ML) | The four-model ensemble above | 500 ms per 512-character window | Regex fallback if the ensemble cannot answer | `toxicity` |

In-process, the injection classifier scores one 512-character window in about 260 ms on one Cloud Run vCPU, and a long prompt is scored in windows: a 16-window prompt takes about 2.0 s on the 4 vCPUs PromptGuard Cloud gives the API. Production has not been re-measured since the move ([above](#what-we-have-actually-measured)).

> [!NOTE]
>
> The ML path **fails open to regex**. If a classifier cannot answer, the request still gets the deterministic verdict: you lose recall, not availability. On a self-hosted install you fetch the weights yourself with your own Hugging Face token and mount them at `LOCAL_INFERENCE_DIR` ([Third-Party Models](https://docs.promptguard.co/security/third-party-models.md)); PromptGuard does not ship them.

## Slow path: LLM-judge detectors

These call a generative LLM to reason about context. Each is **opt-in per project or plan tier** and guarded by a hard timeout; on timeout the detector **falls open** and the request proceeds on the fast/ML verdict. Treat the timeout as the p99 ceiling, the budget is "as fast as the model answers, never longer than this."

| Detector | Default model | Timeout (p99 ceiling) | Env override | `detector` label |
| - | - | - | - | - |
| LLM Guard (custom NL rules) | `openai/gpt-oss-20b` | 8 s | `LLM_GUARD_TIMEOUT` | `llm_guard` |
| Agentic evaluator | `openai/gpt-oss-safeguard-20b` | 8 s | - | `agentic` |
| LLM PII redactor (context-aware pass) | instruct model | 6 s | `LLM_REDACTOR_TIMEOUT` | `llm_pii_redactor` |
| Multi-turn escalation | LLM judge | 8 s | - | `multi_turn` |
| Hallucination / groundedness (RAG) | LLM judge | 10 s | - | `hallucination` |
| Multimodal OCR extraction | OCR subprocess | 8 s | - | `ocr` |

> [!WARNING]
>
> A model that writes a long reasoning trace before answering can blow the budget on the LLM-guard slow path: it spends its token allowance (`LLM_GUARD_MAX_TOKENS`, default 512) "thinking" and is cut off before emitting the verdict JSON, which then fails open. The default, `openai/gpt-oss-20b`, was chosen because it returned a correct, parseable verdict on every case of our August 2026 evaluation, with a median response of 1.5 s. If you override `LLM_GUARD_MODEL`, check the model answers within the budget, and raise `LLM_GUARD_MAX_TOKENS` for one that reasons at length.

## The per-request ceiling

Every timeout above bounds a **call**. `DETECTION_BUDGET_MS` (default **5000**) bounds the **request**.

It exists because long input is split into overlapping windows and each one is classified separately, so a provider that is slow on every chunk multiplies its per-call timeout by the number of windows, up to 16 of them. Bounding one call does not bound what you wait for.

When a scan spends the budget it stops classifying further windows. The leading windows are always classified, so you never lose detection entirely, but the scan did not finish, and PromptGuard does not decide on your behalf what that means:

* **`fail_mode: open`**: the request is served on the partial verdict, the skip is counted, and the event carries `detection_incomplete` so a provider outage stays distinguishable from a period with no threats.
* **`fail_mode: closed`**: the request is refused with `503 detection_unavailable`, exactly as it would be for a detector that errored. Content we did not finish evaluating is not forwarded.

A partial scan that **did** find something still blocks. The finding is not weakened by the windows that were skipped.

Your own custom patterns are not skipped because the budget ran out. Like the built-in fast path, they still run, within a further 1 s shared by all of them, so a scan that spent its budget can take up to that much longer to answer. A pattern that cannot finish in that time is reported as `detection_incomplete`, and `fail_mode` decides the request.

Raise the budget if you routinely scan multi-KB documents through a high-latency inference endpoint and prefer the wait to the truncation. Lower it if you would rather cap the tail hard and let `fail_mode` handle the remainder.

## Keeping the tail small

* **Lean on the cache.** Identical inputs reuse the prior verdict in \< 0.1 ms. High cache-hit rates are the single biggest lever on p99.
* **Only enable the slow path where it earns its keep.** LLM-judge detectors are for ambiguous, high-stakes surfaces (agentic tool calls, custom NL policies, RAG grounding), not every endpoint.
* **Right-size `ML_INFERENCE_MODE`.** `api` for recall, `off` for the lowest, most predictable latency, `local` for the classifiers in-process with no call to hosted inference.
* **Set `fail_mode` deliberately.** `open` favors availability (allow on engine error); `closed` favors safety (block on error). Zero-trust projects should run `closed` and accept that a slow/unreachable detector then blocks rather than falls open. Set it per project at creation, or later via `PATCH /dashboard/projects/{project_id}/settings` with `{"fail_mode": "closed"}`; a project that has never set it is `open`.
* **Measure, don't guess.** These are budgets. Read your actual percentiles per detector from the [detector latency histogram](#per-detector-latency-self-hosted) when you self-host, or from `processing_time_ms` through the [Analytics Cookbook](https://docs.promptguard.co/platform/analytics-cookbook.md#latency-percentiles) on any deployment. An event records the engine's total time, not each detector's.

## Per-detector latency (self-hosted)

A self-hosted API exports how long each detector takes as the Prometheus histogram `promptguard_detector_latency_seconds`, at `/metrics` ([how to reach it](https://docs.promptguard.co/production/self-host-vs-cloud.md#monitoring-a-self-hosted-instance)). Its one label, `detector`, takes the values in the **`detector` label** column of the tables above, so every row has a series, and its size is fixed by the engine, not by your traffic. Rows that share a value are one series: the regex and ML layers of injection are both `injection`, for example.

Also exported, with no budget row: `gibberish`, `language`, `code_vuln`.

Each run of a detector adds one observation. A detector that did not run adds none: one skipped because an earlier detector already blocked, one your plan does not include, or everything after the policy cache on a cache hit.

Each detector's p99 over five minutes:

```promql theme={"system"}
histogram_quantile(0.99, sum by (le, detector) (rate(promptguard_detector_latency_seconds_bucket[5m])))
```

Every budget figure in the tables above is a bucket edge, so a p99 against its budget is read off the histogram rather than estimated between two edges. On Cloud this endpoint is not open to customers; use `processing_time_ms` instead.

## Measuring it yourself

The budgets above are **engine-only**. What your users feel is engine time plus the network hop
to PromptGuard, so measure from the client to get the number that matters to them:

```python Python theme={"system"}
import os
import statistics
import time

from promptguard import GuardClient

client = GuardClient(api_key=os.environ["PROMPTGUARD_API_KEY"])
samples = []

for i in range(200):
    # Vary the input so you measure detectors, not the policy cache.
    messages = [{"role": "user", "content": f"Summarize support ticket {i}"}]
    start = time.perf_counter()
    client.scan(messages, direction="input")
    samples.append((time.perf_counter() - start) * 1000)

samples.sort()
p = lambda q: samples[int(len(samples) * q) - 1]
print(f"n={len(samples)}")
print(f"p50 {p(0.50):6.1f} ms")
print(f"p95 {p(0.95):6.1f} ms")
print(f"p99 {p(0.99):6.1f} ms")
print(f"max {samples[-1]:6.1f} ms   mean {statistics.mean(samples):.1f} ms")
```

```typescript Node.js theme={"system"}
import { GuardClient } from 'promptguard-sdk/guard'

const guard = new GuardClient({ apiKey: process.env.PROMPTGUARD_API_KEY! })
const samples: number[] = []

for (let i = 0; i < 200; i++) {
  // Vary the input so you measure detectors, not the policy cache.
  const messages = [{ role: 'user' as const, content: `Summarize support ticket ${i}` }]
  const start = performance.now()
  await guard.scan(messages, 'input')
  samples.push(performance.now() - start)
}

samples.sort((a, b) => a - b)
const p = (q: number) => samples[Math.ceil(samples.length * q) - 1]
console.log(`n=${samples.length}`)
console.log(`p50 ${p(0.5).toFixed(1)} ms`)
console.log(`p95 ${p(0.95).toFixed(1)} ms`)
console.log(`p99 ${p(0.99).toFixed(1)} ms`)
```

> [!NOTE]
>
> Two things that will otherwise confuse the result. **Warm the cache first**: identical inputs
> reuse the prior verdict in under 0.1 ms, so a loop over one string measures your cache, not your
> detectors. Vary the input to measure the real path. And **run this from where your app runs**:
> from a laptop you are largely measuring your own internet connection, not PromptGuard.

To compare against the engine-only budgets in the tables above, query `processing_time_ms` from
your event telemetry instead, that field excludes both the network hop and any upstream provider
call. The [Analytics Cookbook](https://docs.promptguard.co/platform/analytics-cookbook.md#latency-percentiles) has the SQL.

## Next steps

> [card] [Analytics Cookbook](https://docs.promptguard.co/platform/analytics-cookbook.md)
>
> Measure your real p50/p95/p99 by detector and surface

> [card] [Threat Detection](https://docs.promptguard.co/security/threat-detection.md)
>
> What each detector catches

> [card] [Reliability](https://docs.promptguard.co/production/reliability.md)
>
> Fail-open vs fail-closed and graceful degradation

> [card] [Rate Limits](https://docs.promptguard.co/production/rate-limits.md)
>
> Throughput and quota behavior


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.