Skip to main content

08 - Guardrail cost-benefit: latency added, LLM cost, when the guardrail pays for itself

Latency is read on the tail, cost has a break-even point and return is expressed as a probability threshold: three calculations run on the guardrail.

What do you think about this article?

08 - Guardrail cost-benefit: latency added, LLM cost, when the guardrail pays for itself
AI SafetyPhoto:Tara WinsteadPexels

At a Glance

Latency is read on the tail, cost has a break-even point and return is expressed as a probability threshold: three calculations run on the guardrail.

Latency, cost and expected value: three different measures for the same question

You built the guardrail and it works. Then comes the question from whoever pays: «this check adds half a second to every response and costs something on every call, is it worth it?». There is no answer that holds for everyone, because the question contains three different quantities that are measured in different ways: how much it slows things down (latency, which you read on the tail and not on the average), how much it costs per call (pay-per-use or fixed cost, with a break-even point that you can compute) and how much it is worth to avoid an incident (a probability and a cost that nobody knows precisely).

That is why this article does not give you a number to carry back to your manager: it gives you three calculations, each with a listing that has been run. All the cost, probability and effectiveness inputs are assumptions made up for the example, and say so; the outputs are just arithmetic, reproducible. The latencies in the first listing are synthetic: they describe no real guardrail. No model is run or called.

Latency is read on the tail

The first mistake is summarizing latency with the average. In the chapter on monitoring in Google's Site Reliability Engineering book the example is this: a service with an average latency of 100 ms at 1,000 requests per second can easily have 1% of requests taking 5 seconds. The average hides precisely the requests the user remembers. For an inline guardrail, which sits in front of the response, it matters even more: that tail is added to every response that suffers it.

The file percentili.py generates ten thousand synthetic latencies with a fixed seed: 98% sit between 15 and 25 ms and 2% take 5,000 ms. The function percentile uses the «nearest rank» method: it sorts the values and takes the one at position ceil(p/100 · n). It is one definition among many possible ones, and that is why it has to be written in the code: two libraries can give different percentiles on the same data.

# percentili.py - mean versus percentiles on SYNTHETIC latencies (no real guardrail measured).
import math
import random

def campioni_sintetici(n=10_000, seme=7):
    """98% of requests in 15-25 ms, 2% in the tail at 5000 ms: the shape of the 'few very slow requests' case."""
    rng = random.Random(seme)
    return [5000.0 if rng.random() < 0.02 else 15 + 10 * rng.random() for _ in range(n)]

def percentile(valori, p):
    """Nearest rank: the value at position ceil(p/100 * n) of the sorted list."""
    ordinati = sorted(valori)
    return ordinati[math.ceil(p / 100 * len(ordinati)) - 1]

lat = campioni_sintetici()
print(f"samples: {len(lat)}")
print(f"mean: {sum(lat) / len(lat):.1f} ms")
for p in (50, 95, 99):
    print(f"p{p}: {percentile(lat, p):.1f} ms")
print(f"maximum: {max(lat):.1f} ms")

# Output:
# samples: 10000
# mean: 118.1 ms
# p50: 20.1 ms
# p95: 24.7 ms
# p99: 5000.0 ms
# maximum: 5000.0 ms

The mean is 118.1 ms, while the median (p50) is 20.1 ms and p95 is 24.7: whoever looks at the mean sees a slow guardrail without understanding why, whoever looks at p50 and p95 sees it fast without noticing the tail. The p99 tells the truth, 5,000 ms. Another property to remember: percentiles do not add up. The p99 of a three-layer pipeline is not the sum of the three p99s, because the tails of the individual layers almost never fall on the same requests. You measure the whole pipeline, with the same function.

For each layer of the pipeline it is worth recording a few things, always the same ones:

  • the number of requests evaluated, to know how much the sample is worth;
  • the latency distribution, preferably as counts per bucket (a histogram) and not as averages;
  • how many times the layer blocked and how many times it let through;
  • the version of the rules or of the model in use, to be able to compare before and after a change.

The chapter of the SRE book recommends exactly this: collecting counts per latency bucket instead of raw latencies, with boundaries laid out roughly in geometric progression. The four items together let you answer all the questions in this article; if one is missing, it is usually the fourth, and without it a deterioration can no longer be tied to a change.

Cost per call: pay-per-use or fixed cost

If a layer of the guardrail is a judge based on a model, its cost depends on how you run it. With a paid service you pay for each call based on tokens; with a model on a machine of your own you pay a fixed monthly cost, whatever the traffic. The two curves cross at one point, and that point can be computed. The file costi.py defines two immutable classes, ACosumo and CostoFisso, and compares the two ways for growing volumes. The prices per million tokens, the tokens per call and the 40 euros a month are assumptions of yours to replace: the listing shows the shape of the reasoning.

# costi.py - cost per call of an LLM judge: pay-per-use versus fixed cost.
# Every INPUT number is an assumption to replace with your own price list; the output is just arithmetic.
from dataclasses import dataclass

@dataclass(frozen=True)
class ACosumo:
    eur_per_milione_token_in: float
    eur_per_milione_token_out: float
    token_in: int
    token_out: int

    def eur_per_chiamata(self):
        return (self.token_in * self.eur_per_milione_token_in
                + self.token_out * self.eur_per_milione_token_out) / 1_000_000

@dataclass(frozen=True)
class CostoFisso:
    eur_al_mese: float

    def eur_per_chiamata(self, chiamate_al_mese):
        return self.eur_al_mese / chiamate_al_mese

api = ACosumo(eur_per_milione_token_in=1.0, eur_per_milione_token_out=4.0, token_in=300, token_out=40)
fisso = CostoFisso(eur_al_mese=40.0)

print(f"pay-per-use: {api.eur_per_chiamata() * 1000:.3f} EUR per 1000 calls (independent of volume)")
for volume in (10_000, 50_000, 200_000, 1_000_000):
    print(f"fixed at {volume:>9,} calls/month: {fisso.eur_per_chiamata(volume) * 1000:.3f} EUR per 1000 calls")
pareggio = fisso.eur_al_mese / api.eur_per_chiamata()
print(f"break-even: above {pareggio:,.0f} calls/month the fixed cost wins")

# Output:
# pay-per-use: 0.460 EUR per 1000 calls (independent of volume)
# fixed at    10,000 calls/month: 4.000 EUR per 1000 calls
# fixed at    50,000 calls/month: 0.800 EUR per 1000 calls
# fixed at   200,000 calls/month: 0.200 EUR per 1000 calls
# fixed at 1,000,000 calls/month: 0.040 EUR per 1000 calls
# break-even: above 86,957 calls/month the fixed cost wins

With pay-per-use the cost per thousand calls is constant (0.46 euros with the assumptions of the example); with a fixed cost it collapses as volume grows, from 4 euros to 0.04. The break-even, given by eur_al_mese / eur_per_chiamata, falls at about 86,957 calls a month: below that volume the pay-per-use service costs less, above it a machine of your own wins. The comparison is not only about price, though. The fixed cost requires you to manage the machine, and its capacity has a ceiling: beyond a certain traffic level requests queue up and the tail latency gets worse, which is the problem of the previous section.

Pay-per-use carries a risk that does not appear in the break-even calculation: the traffic is decided by whoever writes to you. The OWASP 2025 list calls it Denial of Wallet, inside the category LLM10 «Unbounded Consumption»: a high volume of operations exploits the pay-per-use cost model until it produces unsustainable costs. A spending cap and a per-user request limit are part of the guardrail's design, not an extra.

Does the guardrail pay for itself? Compute the threshold, do not guess the probability

The value of a guardrail is an avoided expected loss: the probability that an incident happens in a month, times the cost of the incident, times the share of incidents the guardrail intercepts. The problem is that none of these three quantities has a public source that lets you cite it for your case. Instead of inventing a probability, the file soglia.py leaves it unknown and solves the equation backwards: at what monthly probability does the guardrail stop costing more than it avoids? The function p_di_pareggio is a single division, costo_guardrail / (costo_incidente * efficacia).

# soglia.py - not "how much is the guardrail worth", but "at what incident probability does it pay for itself".
# Costs and probabilities are declared ASSUMPTIONS: the exercise lies in the reasoning, not in the figures.

def valore_atteso_mensile(p_incidente, costo_incidente, efficacia, costo_guardrail):
    """Expected loss avoided by the guardrail, minus what it costs to keep it on."""
    evitata = p_incidente * costo_incidente * efficacia
    return evitata - costo_guardrail

def p_di_pareggio(costo_incidente, efficacia, costo_guardrail):
    """Monthly incident probability below which the guardrail costs more than it avoids."""
    return costo_guardrail / (costo_incidente * efficacia)

SCENARI = [
    # name, cost of one incident (EUR), assumed effectiveness, monthly cost of the guardrail (EUR)
    ("Public FAQ", 2_000, 0.80, 5),
    ("Internal HR assistant", 50_000, 0.90, 400),
    ("Regulated domain", 200_000, 0.95, 3_000),
]
for nome, costo_inc, efficacia, costo_g in SCENARI:
    p = p_di_pareggio(costo_inc, efficacia, costo_g)
    ev_1 = valore_atteso_mensile(0.01, costo_inc, efficacia, costo_g)
    print(f"{nome:<22} break-even at p={p:.2%} per month | with p=1%: expected value {ev_1:+,.0f} EUR/month")

# Output:
# Public FAQ             break-even at p=0.31% per month | with p=1%: expected value +11 EUR/month
# Internal HR assistant  break-even at p=0.89% per month | with p=1%: expected value +50 EUR/month
# Regulated domain       break-even at p=1.58% per month | with p=1%: expected value -1,100 EUR/month

The result reads as a question put to whoever knows the domain. A frequently-asked-questions service with a guardrail costing 5 euros a month pays for itself if the monthly probability of a 2,000-euro incident exceeds 0.31%: a very low threshold, so almost certainly yes. The internal assistant with a 400-euro-a-month control demands 0.89%. The regulated domain with a 3,000-euro-a-month pipeline demands 1.58%, and if the real probability were 1% the expected value would be negative, minus 1,100 euros a month. It is an important result: a very expensive guardrail does not always pay for itself, not even where incidents are costly.

Scenario (assumptions of the example) Cost of an incident Assumed effectiveness Monthly cost of the guardrail Monthly break-even probability
Public FAQ2,000 euros80%5 euros0.31%
Internal HR assistant50,000 euros90%400 euros0.89%
Regulated domain200,000 euros95%3,000 euros1.58%

For the systems that the European regulation classifies as high-risk, the economic calculation is not the only criterion. Articles 9 and 15 of the AI Act require a risk management system and appropriate levels of accuracy, robustness and cybersecurity throughout the lifecycle: they are obligations, not items to set against the budget. The threshold calculation serves to choose how to meet them, and to explain why a two-level pipeline costs less than a single-level one.

Sampled checking: what it really sees

For lower-risk services an asynchronous check on part of the traffic is often used, for example 10% of sessions, while the rest passes only through the fast filter. The sample must be chosen in a stable way: the same session must always fall inside or always outside. The file campionamento.py uses SHA-256 of the session identifier, because Python's hash() function for strings is «salted» with a random value that differs at each start of the process, as the data model documentation states. With hashlib the choice is the same on every machine and on every run.

# campionamento.py - how much a sampled check really sees.
import hashlib
import math

def nel_campione(id_sessione, quota):
    """SHA-256 hash of the id: stable across runs and machines (Python's hash() is not)."""
    cifra = int(hashlib.sha256(id_sessione.encode()).hexdigest(), 16)
    return (cifra % 10_000) / 10_000 < quota

sessioni = [f"session-{i}" for i in range(10_000)]
scelte = sum(nel_campione(s, 0.10) for s in sessioni)
print(f"sessions in the 10% sample: {scelte} out of {len(sessioni)}")
print(f"same session, two calls: {nel_campione('session-42', 0.10) == nel_campione('session-42', 0.10)}")

# If an abuse produces k requests, with sample q at least one is seen with probability 1-(1-q)^k.
for q in (0.10, 0.30):
    for k in (1, 5, 10, 30):
        print(f"q={q:.0%} k={k:>2}: probability of seeing at least one = {1 - (1 - q) ** k:.1%}")
k95 = math.ceil(math.log(0.05) / math.log(0.90))
print(f"with q=10% you need {k95} anomalous requests to see one with probability >= 95%")

# Output:
# sessions in the 10% sample: 982 out of 10000
# same session, two calls: True
# q=10% k= 1: probability of seeing at least one = 10.0%
# q=10% k= 5: probability of seeing at least one = 41.0%
# q=10% k=10: probability of seeing at least one = 65.1%
# q=10% k=30: probability of seeing at least one = 95.8%
# q=30% k= 1: probability of seeing at least one = 30.0%
# q=30% k= 5: probability of seeing at least one = 83.2%
# q=30% k=10: probability of seeing at least one = 97.2%
# q=30% k=30: probability of seeing at least one = 100.0%
# with q=10% you need 29 anomalous requests to see one with probability >= 95%

With ten thousand sessions the 10% sample contains 982 of them, not 1,000: a sample by hash is approximate, not exact. The rest of the listing answers the question that matters. An abuse that produces k anomalous requests is seen at least once with probability 1 - (1 - q)^k. With q = 10% and an abuse of 5 requests you have a 41% chance of seeing it; to reach 95% you need 29. A sampled check is therefore a detection tool, suited to repeated phenomena, and not a barrier: a single serious event on a system sampled at 10% almost always goes unnoticed.

Fast path and deferred blocking

The last technique for saving latency is to answer immediately and check afterwards: if the asynchronous check finds a violation, the session is blocked on the following requests. The file eventual_block.py simulates the mechanism with a logical clock of integers, with no threads and no real waits, so that the output is always identical. The audit takes 3 ticks; the actions listed in AZIONI_IRREVERSIBILI skip the shortcut and are always checked synchronously.

# eventual_block.py - the asynchronous check with a logical clock (integers), to see the exposure window.
LATENZA_AUDIT = 3            # ticks the audit takes to conclude
AZIONI_IRREVERSIBILI = {"send_email"}

blocchi = {}                 # session -> tick from which it is blocked
audit_in_corso = []          # (audit end tick, session, outcome)

def richiesta(tick, sessione, azione, testo_ok):
    for fine, sess, esito in list(audit_in_corso):
        if fine <= tick:
            audit_in_corso.remove((fine, sess, esito))
            if esito == "violation":
                blocchi[sess] = fine
    if azione in AZIONI_IRREVERSIBILI:
        return "synchronous check (no shortcut)"
    if sessione in blocchi:
        return f"BLOCKED (from tick {blocchi[sessione]})"
    audit_in_corso.append((tick + LATENZA_AUDIT, sessione, "ok" if testo_ok else "violation"))
    return "passed on the fast path"

for tick, azione, ok in [(0, "reply", False), (2, "reply", True), (4, "reply", True), (5, "send_email", True)]:
    print(f"tick {tick}: s1 {azione:<12} -> {richiesta(tick, 's1', azione, ok)}")

# Output:
# tick 0: s1 reply        -> passed on the fast path
# tick 2: s1 reply        -> passed on the fast path
# tick 4: s1 reply        -> BLOCKED (from tick 3)
# tick 5: s1 send_email   -> synchronous check (no shortcut)

The first request (tick 0) contains a violation and passes, because the audit has not finished yet. The second one passes too, at tick 2. From tick 3 the session is blocked, and the one at tick 4 is stopped. The exposure window is exactly the duration of the audit, and in that window every response goes out unchecked. That is why the email sent at tick 5 cannot use the fast path: an irreversible action cannot be undone afterwards. The OWASP list, in describing excessive agency (LLM06), also recommends requiring human approval for high-impact actions before they are executed.

The same reasoning holds for streamed responses. If the text is shown while it is being generated, the check on the output can happen only once the response is complete, or on portions at intervals: what the user has already read cannot be taken back. The alternative is to present the text as provisional until the check confirms it, accepting a higher perceived latency. It is a product choice with a cost, and the LLM05 category of the OWASP list (improper output handling) is a reminder that output must be treated as no more trusted than input.

What you can do now

You can measure the latency of a guardrail on the tail instead of the average, and you know that the percentiles of a pipeline are measured on the whole pipeline. You can compute where a pay-per-use cost and a fixed one cross, and what is left out of the calculation (capacity and Denial of Wallet). You can turn the question about economic return into a probability threshold to put to whoever knows the domain, and you know how much a sampled check really sees. For the rest of the picture you can continue with the test bench of episode 07 and with the incident response playbook of episode 09; the three starting architectures are in episode 01.

The same series also includes updating a guardrail's rules.

Frequently asked questions

How do I measure the latency of a guardrail in operation?

Count the requests per duration bucket (a histogram) for each layer and for the whole pipeline, and read the p50, p95 and p99 percentiles from those counts. Avoid the mean as the only indicator: it hides the tail, which is what the user perceives.

Is a judge based on a pay-per-use service or on a model on a machine of my own better?

It depends on volume and capacity. The break-even is computed by dividing the fixed monthly cost by the cost of one pay-per-use call; above that volume the fixed cost wins, provided the machine holds the peak without lengthening the latency tail.

Is a sampled check enough for a low-risk system?

It is enough to discover abuses that repeat, not to stop a single serious event. With a 10% sample you need about 29 anomalous requests for at least one to be seen with 95% probability. If a single case is already unacceptable, the check must be synchronous.

Sources

The listings were run with Python 3.14 and the standard library only; every output is identical across two consecutive runs. The latencies are synthetic and all the costs, probabilities and effectiveness figures are assumptions of the example: replace them with your own before drawing conclusions.

Commenti

Caricamento commenti...

Sign in to comment

New articles and tools on Telegram too

The Telegram channel flags the site's new articles and tools.

Did you like this article?

Explore other content on the blog or discover my projects