Reliability and Cost Engineering

Michael BrenndoerferDecember 2, 202629 min read

Design reliable, cost-aware AI services with SLOs, retries, idempotency, Little's law, caching, and fault injection under real deadlines.

Language AI HandbookAll chapters
Part 64 of 67Compound AI System Design
Chapter 490Reliability and Cost Engineering
Reading the full chapter · 12 sections · 29 min12 sections · 29 min

All 12 sections · 29 min read

Reading settings

Definitions

Choose how many terms have tooltips.

Article links

Make inline references clickable

Notes & comments

Reliability and Cost Engineering

A support assistant can miss its two-second deadline even when every dependency eventually succeeds. A search call waits in a queue, the model has to retry, and the fallback arrives after the user has left. Those attempts still consumed capacity, and billable calls can incur charges even when the user never receives a useful answer.

For sequential calls, the mean of the sum equals the sum of the means. You generally cannot add the component medians or p99s to get the corresponding end-to-end percentile. Consider two independent steps, each taking one second on 60% of requests and nine seconds otherwise. Each has a one-second median, but together they finish in two seconds only 36% of the time. The end-to-end median is ten seconds. How long calls coincide on the same requests matters.

We'll define a service-level objective, look at when retrying helps, and use seeded examples to connect queueing, cache errors, and model spend. A final fault-injection example puts those decisions together under a shared outage.

Where this chapter sits

The earlier chapters in Compound AI System Design introduce routing and tracing. Production Systems covers their serving context, including autoscaling and caching.

What Reliability Engineering Buys You

Pick the request outcome users need before choosing a retry or cache policy. A service-level objective gives the team a target against which to measure the policy.

SLI, SLO, SLA

A service-level indicator (SLI) measures service behavior. Here it is the fraction of eligible requests that succeed within two seconds. A service-level objective (SLO) sets a target, such as 99.5% over a rolling 28-day window. A service-level agreement (SLA) specifies consequences of meeting or missing its objectives. A 99.5% request-based SLO allows 0.5% bad requests. A time-based availability SLO with the same target would allow 3.36 hours of unavailability in 28 days. Google SRE's SLO workbook uses the good-event ratio to derive a request error budget.

Suppose eight required calls succeed independently with probability 0.995 each. When every call must succeed and there is no recovery path, the request succeeds with probability 0.99580.995^8, about 96.1%. Adding eight more otherwise identical calls makes it 0.995160.995^{16}, about 92.3%. The products model actual success probabilities under independence. The end-to-end SLO is the target you select for the service.

Improving a component can improve end-to-end reliability. The remaining required steps still bound the gains. Look at which calls a request can avoid and whether a recovery path can finish within its deadline. Each extra attempt uses some of the capacity you are trying to protect.

Service Objectives and the Error Budget

For a single service, model latency TT in seconds and let SS equal one on success and zero on failure. The SLI counts successful requests that meet the deadline.

SLI=#{r:Sr=1 and Tr≤θ}#{r}\text{SLI} = \frac{\#\{r : S_r = 1 \text{ and } T_r \le \theta\}}{\#\{r\}}

Here rr ranges over eligible requests in the measurement window. SrS_r records success, TrT_r is end-to-end latency in seconds, and θ\theta is the deadline in seconds. A failure or a late success uses one bad event. The ratio is undefined when there are no eligible requests. With NN requests and target qq, the SLI meets the objective when SLI≥q\text{SLI} \ge q. Equivalently, at most ⌊(1−q)N⌋\lfloor(1-q)N\rfloor requests may be bad. The fixture stores the target as an exact fraction and takes the integer part of the nonnegative allowance.

The bad-event count lets you compare an incident with the window's allowance. A retry uses the error budget only if the logical request ultimately fails the SLI. A fast fallback counts as good only when it meets both the deadline and the service's success criteria, which may include a quality requirement.

A latency median alone describes the middle request and leaves the slower tail unspecified. Measure the fraction meeting the deadline and use request traces to find which calls and queues contributed to the misses.

The seeded example uses a lognormal latency distribution and independently assigns a failure flag to each request. These are illustrative assumptions.

PythonIn [3]
CollapseExpand
import numpy as np

rng = np.random.default_rng(7)

# Single service: 20,000 requests, lognormal latency in seconds.
N = 20_000
mu_log, sigma_log = np.log(0.4), 0.6  # median 0.4s
latency = rng.lognormal(mu_log, sigma_log, size=N)

# Independent per-request failure hazard (timeouts, 5xx, parse errors).
P_FAIL = 0.004
success = rng.random(N) >= P_FAIL

TAU = 2.0  # latency threshold in seconds

If the logarithm of latency has mean μ=ln⁡(0.4)\mu=\ln(0.4) and standard deviation σ=0.6\sigma=0.6, the lognormal median is eμ=0.4e^\mu=0.4 seconds. Its mean is eμ+σ2/2≈0.48e^{\mu+\sigma^2/2}\approx0.48 seconds. Increasing σ\sigma at fixed μ\mu spreads the distribution while leaving its median unchanged.

Now compute the SLI, the error budget, and the percentile structure.

ConsoleOut [4]
CollapseExpand
Observed SLI (success & <= 2.0s): 0.9932
SLO target:                        0.9950
Error budget (fraction):           0.0050  -> 100 reqs / window
Bad requests observed:             135
Budget remaining:                  -35 reqs

p50   : 0.397s
p90   : 0.854s
p95   : 1.064s
p99   : 1.591s
p99.9 : 2.446s

The histogram shows the deadline against the latency distribution. It does not show which requests failed independently of latency.

PythonIn [5]
CollapseExpand
lat_mean = float(latency.mean())
lat_p99 = float(np.percentile(latency, 99))
hist_edges = np.geomspace(latency.min(), latency.max(), 50)
hist_counts, _ = np.histogram(latency, bins=hist_edges)
hist_widths = np.diff(hist_edges)
VisualizationOut [6]
CollapseExpand
A latency histogram on a logarithmic x-axis with mean and 99th percentile to the left of the two-second deadline.
Simulated request counts in equal intervals of log latency. The dashed line marks the two-second deadline. Requests to its right are late. The SLI also counts failures, including any left of the line.

The 99.5% SLO allows 100 bad requests in this 20,000-request window. Compare that allowance with the bad count. The mean is under half a second, and some requests still miss the two-second deadline. The percentiles show how far the tail extends.

The measurement boundary problem

Specify where the clock starts and stops. For this example, success means a complete usable response by the deadline, with errors and timeouts in the eligible request denominator. Time to first token is a separate measure for streaming. Check what any provider timing includes. Your end-to-end clock can include queueing even when you cannot break out its provider-side share.

Retries, Redundancy, and the Independent-Failure Assumption

If an operation has a 99.5% success probability independently on each attempt, three attempts give 1−0.0053=99.9999875%1-0.005^3=99.9999875\% success. During a shared outage, failure on one attempt can make the next failure more likely.

With kk independent attempts and per-attempt success probability pp, all attempts fail with probability (1−p)k(1-p)^k. The probability that at least one succeeds is its complement. In the second model, an outage with probability rr lasts for the entire retry sequence. Conditional on no outage, the attempts are independent with success probability pp, giving unconditional success (1−r)[1−(1−p)k](1-r)[1-(1-p)^k].

PythonIn [7]
CollapseExpand
def success_independent(p, k):
    return 1 - (1 - p) ** k


def success_correlated(p, k, r):
    # r = probability of correlated outage where EVERY attempt fails.
    # otherwise (1-r) of the time the attempts are iid with success p.
    return (1 - r) * success_independent(p, k)


p = 0.995
for k in (1, 2, 3):
    ind = success_independent(p, k)
    print(f"k={k} independent: {ind * 100:.7f}%")

print()
for r in (0.0, 0.001, 0.005):
    row = [success_correlated(p, k, r) * 100 for k in (1, 2, 3)]
    print(
        f"correlated outage r={r:g}: "
        + "  ".join(f"k={k}:{v:.7f}%" for k, v in zip((1, 2, 3), row))
    )
ConsoleOut [7]
CollapseExpand
k=1 independent: 99.5000000%
k=2 independent: 99.9975000%
k=3 independent: 99.9999875%

correlated outage r=0: k=1:99.5000000%  k=2:99.9975000%  k=3:99.9999875%
correlated outage r=0.001: k=1:99.4005000%  k=2:99.8975025%  k=3:99.8999875%
correlated outage r=0.005: k=1:99.0025000%  k=2:99.4975125%  k=3:99.4999876%

With r=0.001r=0.001, one attempt succeeds with probability 0.999⋅0.995=0.9940050.999\cdot0.995=0.994005. Three attempts raise that to about 99.9%, the outage-imposed ceiling. During the all-fail outage, a policy that uses all three attempts sends three times as many calls as the one-attempt policy. Across the entire window, most healthy requests still finish on the first attempt.

A retry can recover from a transient failure. During sustained overload, the added work can prevent the dependency from recovering. The retry policy also needs to respect the original request's deadline.

  • Distinguish failure classes. The example marks a few response codes as retryable. In production, check the dependency's contract, the request's remaining deadline, and whether repeating the operation is safe. A timeout alone cannot tell you whether a write took effect.
  • Cap attempts and add jitter. A cap limits calls per operation. Randomized delays reduce the chance that clients retry in sync. The half-fixed, half-random delay in the example is equal jitter.
  • Budget retries. Track total downstream attempts divided by original requests to see the load multiplier. Its excess over one is extra attempts per request when every request starts with one call.
  • Shed load when retries cannot help. When evidence indicates a dependency is unavailable, a circuit breaker can skip that dependency and fail fast or route to a viable fallback.

This retry simulator uses capped exponential backoff with jitter. It records latency and counts how many calls an original request generates.

PythonIn [8]
CollapseExpand
def classify(outcome_code):
    # Map a synthetic outcome to retry policy.
    if outcome_code == "ok":
        return "success", False
    if outcome_code in ("429", "500", "503", "timeout"):
        return "transient", True
    return "hard", False  # 400, 401, 422, policy refusal -> do not retry


def backoff_delay(attempt, rng, base=0.05, cap=2.0):
    # attempt is 1-indexed (after first try, attempt=1 for the first retry).
    raw = min(cap, base * (2 ** (attempt - 1)))
    return raw * (0.5 + rng.random() * 0.5)  # equal jitter


def simulate_request(server_transient, rng, max_attempts=3):
    """One logical request. Returns (success, total_latency, n_attempts)."""
    total_lat = 0.0
    attempts = 0
    while attempts < max_attempts:
        attempts += 1
        # Base call latency ~ lognormal; a "down" server returns 503 fast.
        if rng.random() < server_transient:
            code = "503"
            total_lat += rng.lognormal(np.log(0.02), 0.2)
        else:
            code = "ok"
            total_lat += rng.lognormal(np.log(0.4), 0.6)
        kind, retryable = classify(code)
        if kind == "success":
            return True, total_lat, attempts
        if not retryable:
            return False, total_lat, attempts
        if attempts < max_attempts:
            total_lat += backoff_delay(attempts, rng=rng)
    return False, total_lat, attempts


def run_batch(server_transient, max_attempts, n=20_000, seed=11):
    rng = np.random.default_rng(seed)
    succ, lats, atts = [], [], []
    for _ in range(n):
        s, l, a = simulate_request(
            server_transient, rng, max_attempts=max_attempts
        )
        succ.append(s)
        lats.append(l)
        atts.append(a)
    succ = np.array(succ)
    lats = np.array(lats)
    atts = np.array(atts)
    return dict(
        success=succ.mean(),
        p99=float(np.percentile(lats, 99)),
        mean_att=atts.mean(),
        max_att=int(atts.max()),
        amplification=atts.sum() / n,
    )

Compare a 1% per-attempt failure probability with a 40% probability. Both regimes draw independently on every attempt. The second models frequent failures, distinct from the shared outage in the previous table.

ConsoleOut [9]
CollapseExpand
--- healthy  (1% transient) ---
  no-retry : success=0.9899  p99=1.63s  attempts/req=1.00
  retry(3) : success=1.0000  p99=1.58s  attempts/req=1.01  max_att=3
  amplification on retry: 1.01x  (total attempts / original requests)

--- impaired (40% transient) ---
  no-retry : success=0.5964  p99=1.45s  attempts/req=1.00
  retry(3) : success=0.9381  p99=1.63s  attempts/req=1.56  max_att=3
  amplification on retry: 1.56x  (total attempts / original requests)

The next cell reruns the two three-attempt settings with the same seeds and plots their mean attempts per original request. Use the earlier table for p99 latency, which this figure does not show.

PythonIn [10]
CollapseExpand
regime_names = ["1% failure", "40% failure"]
measured = [run_batch(rate, max_attempts=3) for rate in (0.01, 0.40)]
amp_vals = [batch["amplification"] for batch in measured]
bar_x = np.arange(len(regime_names))
VisualizationOut [11]
CollapseExpand
Bars near 1.01 and 1.56 attempts per request for simulated failure probabilities of one and forty percent respectively.
Simulated attempts per request with up to three tries. Both settings use independent per-attempt failures. The dashed baseline is one call per original request.

With failure probability ff and at most three independent attempts, the second attempt occurs with probability ff and the third with probability f2f^2. The expected number of attempts is 1+f+f21+f+f^2: about 1.01 in the healthy setting and 1.56 at 40% failures. In the latter setting the theoretical success probability rises from 60% to 1−0.43=93.6%1-0.4^3=93.6\%. The printed p99 includes both outcomes and can change when fast failures are replaced by successful calls that do more work.

Retries are a load multiplier, not free availability

Three attempts can triple volume during an outage if every request exhausts its attempts. Monitor the attempts-per-request ratio and use the routing controls to stop sending work down a path that cannot recover within the deadline.

Idempotency: Making Retries and Replays Safe

An operation is idempotent if repeated identical requests have the same intended effect as one request. HTTP specifies that GET is idempotent. A charge endpoint can apply the same payment again unless it deduplicates the logical operation. Hidden mutations matter too, such as an email send or a write to conversation memory.

A repeated generation may produce different text and incur a second charge. Persist and replay the accepted result when your application requires the same answer.

An idempotency key identifies a logical operation. Use the same key for each retry, scope it to the caller, and check that a reused key carries the same operation parameters. While a valid record is retained, the service can replay the stored result.

The one-process demonstration below serializes duplicate calls using a per-key lock. Its guarantee is limited to callbacks that complete and whose result is recorded in the live process.

PythonIn [12]
CollapseExpand
import threading


class IdempotentExecutor:
    """Deduplicates side effects by idempotency key.
    Concurrent duplicate keys block on a per-key lock so the
    first recorded result is reused."""

    def __init__(self):
        self._results = {}  # key -> result
        self._locks = {}  # key -> Lock
        self._guard = threading.Lock()
        self.executions = 0  # count of successfully recorded callbacks

    def _lock_for(self, key):
        with self._guard:
            if key not in self._locks:
                self._locks[key] = threading.Lock()
            return self._locks[key]

    def run(self, key, side_effect):
        lock = self._lock_for(key)
        with lock:
            if key in self._results:
                return self._results[key], "cached"
            result = side_effect()  # the thing we must not repeat
            self._results[key] = result
            with self._guard:
                self.executions += 1
            return result, "executed"

The per-key lock keeps two calls from observing a missing result for the same key at once. The short guard protects the lock registry. Different keys can execute their callbacks concurrently.

PythonIn [13]
CollapseExpand
executor = IdempotentExecutor()
side_effect_calls = {"n": 0}
counter_lock = threading.Lock()


def charge_once():
    with counter_lock:
        side_effect_calls["n"] += 1
    return {"charged": True, "amount_cents": 4200}


# 16 concurrent attempts, all with the SAME logical key.
key = "ord-77123-charge"
threads = [
    threading.Thread(target=lambda: executor.run(key, charge_once))
    for _ in range(16)
]
for t in threads:
    t.start()
for t in threads:
    t.join()

print(f"threads: 16, same key")
print(f"side effects actually executed: {side_effect_calls['n']}")
print(f"executor.executions:            {executor.executions}")
print(f"stored result:                  {executor._results[key]}")
ConsoleOut [13]
CollapseExpand
threads: 16, same key
side effects actually executed: 1
executor.executions:            1
stored result:                  {'charged': True, 'amount_cents': 4200}

The sixteen submitted threads share one key and produce one recorded execution. The other calls replay that result.

Idempotency keys are not a silver bullet

A process crash can erase the in-memory record after the outside operation commits. A callback can also fail after committing its effect. Use a durable idempotency record and make local mutations atomic with that record. For an external charge, reuse the key at the provider if its API supports it and reconcile uncertain outcomes. A local lock cannot make the provider commit and local record write atomic. The Amazon Builders' Library walks through this failure boundary.

Concurrency, Capacity, and Little's Law

The retry simulator changes the number of calls without tracking a queue. Little's law relates time in a queueing system to its occupancy.

L=λ WL = \lambda \, W

Here LL is the long-run mean number of requests inside a boundary, λ\lambda is the rate of requests entering that boundary, and WW is the mean time those requests spend inside it. For a stable system with finite long-run averages, requests per second times seconds per request gives mean occupancy in requests. The identity includes queued work if the boundary includes the queue. Little's original proof states the conditions on the stochastic process and its means.

At 50 requests per second and a mean time in the system of 1.2 seconds, mean occupancy is 60 requests. Use a load test to decide how many active slots or how much headroom a latency target needs. In the idealized M/M/1 queue with Poisson arrivals and exponential service times, W=1/(μ−λ)W=1/(\mu-\lambda) for arrival rate λ\lambda below service rate μ\mu. It grows as the arrival rate approaches capacity. The next example keeps service time fixed, so its curve is for a different queue.

The simulation is a continuous-time single-server FIFO queue with exponential interarrival gaps and deterministic service. It starts empty and drops the first 5,000 jobs from the latency measurement.

PythonIn [14]
CollapseExpand
def simulate_queue(arrival_rate, service_time, n_slots=200_000, seed=3):
    """Single-server FIFO queue with continuous event times.
    arrival_rate: Poisson arrivals per second.
    service_time: deterministic service time per request.
    Returns average latency W over the run (excluding warmup)."""
    rng = np.random.default_rng(seed)
    # Exponential gaps generate the Poisson arrival times.
    gaps = rng.exponential(1.0 / arrival_rate, size=n_slots)
    arrival_times = np.cumsum(gaps)
    # Single server: each job starts at max(arrival, previous_finish).
    finish = np.empty(n_slots)
    prev_finish = 0.0
    for i in range(n_slots):
        start = max(arrival_times[i], prev_finish)
        finish[i] = start + service_time
        prev_finish = finish[i]
    warm = 5_000
    latency = finish[warm:] - arrival_times[warm:]
    return latency.mean(), latency


mu = 1.0 / 0.05  # server capacity = 20 jobs/second
results = {}
for frac in (0.3, 0.6, 0.8, 0.9, 0.95):
    lam = frac * mu
    W, _ = simulate_queue(lam, service_time=0.05)
    results[frac] = (lam, W)
ConsoleOut [15]
CollapseExpand
server capacity mu = 20.0 jobs/s, service time = 0.05 s
 util   lambda   W(measured)  L=lambda*W
 0.30     6.00         0.061        0.36
 0.60    12.00         0.087        1.05
 0.80    16.00         0.149        2.38
 0.90    18.00         0.272        4.89
 0.95    19.00         0.510        9.69

At 95% utilization, a 10% relative increase in arrival rate raises offered load to 104.5% of capacity. If that rate persists in this unbounded model, a finite steady-state queue cannot be maintained. In a real service, test admission limits and burst headroom against the measured tail rather than relying on a fixed utilization target.

PythonIn [16]
CollapseExpand
utilizations = np.linspace(0.1, 0.98, 60)
service_time = 0.05
drawn_latencies = np.array(
    [
        simulate_queue(
            rho / service_time, service_time, n_slots=35_000, seed=5
        )[0]
        for rho in utilizations
    ]
)
# M/D/1 mean waiting time plus the fixed service time.
modeled_latencies = service_time * (1 + utilizations / (2 * (1 - utilizations)))
VisualizationOut [17]
CollapseExpand
Simulated and analytical mean latency rise sharply at high utilization. They are close until the highest loads near full capacity.
Simulated mean total latency in a single-server queue with Poisson arrivals and fixed 50 ms service. The dashed line is the steady-state M/D/1 mean. The finite simulation is least stable close to capacity.

The dashed curve adds mean waiting time to fixed service time s=0.05s=0.05 seconds. If ρ=λs<1\rho=\lambda s<1 is utilization, the M/D/1 mean is s[1+ρ/(2(1−ρ))]s[1+\rho/(2(1-\rho))]. The waiting term grows as utilization approaches one. The sample mean varies with the seed, especially close to capacity. Use the table and Little's law to connect time in the queue to mean in-flight work. A system that scales after a planning window can still queue during a short burst. Load-test the headroom and scaling delay around the operating point you intend to use.

Caching and Its Discontents

A cache can skip a retrieval or generation call. That saves work on a hit, but a response retained under an outdated policy can still look plausible. Confirm what a cache is allowed to reuse before evaluating its hit rate.

A response cache can sit alongside a provider's cache of model state.

  • Exact-match response cache. Reuse a previous answer only when request semantics, dependency versions, and current authorization allow it. Include the inputs and relevant state in the key or invalidate entries when that state changes.
  • Provider prompt cache. A provider may reuse model prefill state for an eligible matching prefix. Some pricing distinguishes cached and uncached input, as in OpenAI's prompt-caching documentation. This mechanism saves prefix processing while generation still runs.
  • Semantic cache. A match may reuse a response when a query embedding is close enough to the stored one. A weaker threshold can admit more candidates on a fixed workload. The share of wrong hits depends on which candidates it admits.

Use the hit rate to account for how often each path is taken.

E[T]=h Thit+(1−h) Tmiss,E[C]=h chit+(1−h) cmiss\mathbb{E}[T] = h \, T_{\text{hit}} + (1-h)\, T_{\text{miss}}, \qquad \mathbb{E}[C] = h\,c_{\text{hit}} + (1-h)\, c_{\text{miss}}

Here hh is the probability of a cache hit. Each TT is a conditional mean latency and each cc is a conditional mean cost, weighted by the probability of that path. For a semantic cache, if ff is the fraction of hits that give a wrong answer, the probability of a wrong cache hit per request is hfhf. That quantity says nothing about miss-path mistakes. The two operating points below are stipulated examples, not measured threshold performance.

PythonIn [18]
CollapseExpand
# Cost/latency model for a retrieval + generation step.
T_HIT, T_MISS = 0.03, 0.9  # seconds
C_HIT, C_MISS = 0.0, 0.012  # dollars per request


def cache_expected(
    hit_rate, t_hit=T_HIT, t_miss=T_MISS, c_hit=C_HIT, c_miss=C_MISS
):
    t = hit_rate * t_hit + (1 - hit_rate) * t_miss
    c = hit_rate * c_hit + (1 - hit_rate) * c_miss
    return t, c


# Two operating points for a SEMANTIC cache with a similarity threshold.
# Illustrative hit and wrong-hit fractions, not fitted to a workload.
settings = {
    "conservative (sim>=0.95)": dict(hit_rate=0.20, false_positive=0.002),
    "aggressive   (sim>=0.85)": dict(hit_rate=0.55, false_positive=0.060),
}

for name, s in settings.items():
    t, c = cache_expected(s["hit_rate"])
    # Probability a served response is WRONG due to a bad cache hit:
    # wrong only on hits, and only the false-positive fraction of those.
    p_wrong = s["hit_rate"] * s["false_positive"]
    print(f"{name}")
    print(
        f"   hit_rate={s['hit_rate']:.2f}  E[T]={t:.4f}s  "
        f"E[cost]=${c:.4f}  P(wrong via cache)={p_wrong:.4f}"
    )
ConsoleOut [18]
CollapseExpand
conservative (sim>=0.95)
   hit_rate=0.20  E[T]=0.7260s  E[cost]=$0.0096  P(wrong via cache)=0.0004
aggressive   (sim>=0.85)
   hit_rate=0.55  E[T]=0.4215s  E[cost]=$0.0054  P(wrong via cache)=0.0330

The two settings give mean latencies of 0.726 and 0.4215 seconds and mean costs of $0.0096 and $0.0054 per request. Wrong cache hits rise from 0.0004 to 0.033 per request: 40 versus 3,300 per 100,000 requests in expectation. Sample and label cache hits; a hit-rate dashboard alone cannot tell you whether that trade is acceptable.

Cache keys are a correctness specification

Bind reuse to the authorized tenant and current permissions. Include model and prompt versions, retrieval context or its version, and locale when they affect the answer. A TTL can limit the lifetime of a stale entry but does not replace access checks or invalidation when permissions or source data change.

Cost Budgets and Forecasting

Estimate typical spend and the cost of the expensive requests separately. Longer model inputs and outputs can move per-request spend even before you count retries and tool calls.

For one generation in the simple two-price model below, multiply the number of billed input tokens ninn_{\text{in}} and output tokens noutn_{\text{out}} by their respective prices per token, pinp_{\text{in}} and poutp_{\text{out}}.

c=pin nin+pout nout.c = p_{\text{in}} \, n_{\text{in}} + p_{\text{out}} \, n_{\text{out}}.

The sum is measured in dollars. In a provider bill, use billed token classes and the actual model rates, and include tool charges or cache-write fees when they apply. For a logical request with multiple attempts, sum the charges over the attempts. The rates below are illustrative.

PythonIn [19]
CollapseExpand
# Illustrative prices (dollars per token). Replace with a provider's
# current published rates; do not hardcode stale prices in policy code.
P_IN = 3.00 / 1_000_000
P_OUT = 15.00 / 1_000_000

rng = np.random.default_rng(21)
N = 50_000

# Input tokens: fairly tight around 800, but sometimes a long RAG context.
n_in = np.where(
    rng.random(N) < 0.05,
    rng.lognormal(np.log(6000), 0.4, N),
    rng.lognormal(np.log(800), 0.3, N),
)

# Output tokens: lognormal; a small fraction run very long (reasoning).
n_out = np.where(
    rng.random(N) < 0.03,
    rng.lognormal(np.log(2000), 0.5, N),
    rng.lognormal(np.log(250), 0.4, N),
)

n_in = np.rint(n_in).astype(int)
n_out = np.rint(n_out).astype(int)
cost = P_IN * n_in + P_OUT * n_out
mean_cost = cost.mean()
ConsoleOut [20]
CollapseExpand
mean cost/request: $0.0083
p50  cost/request: $0.0065
p99  cost/request: $0.0451
p99.9 cost/request: $0.0816

1M req/mo @ mean:      $8,338
1M req/mo @ p99 each:  $45,141  (stress / mean 5.4x)
share of total cost from top 1% requests: 7.32%

Multiplying the mean by one million forecasts spend if volume and the cost mix match this example. Pricing all one million requests at the per-request p99 is a stress scenario. It is neither a 99% upper bound nor the p99 of monthly spend. For a budget at a stated risk level, model volume, request mix, and shared high-cost periods across entire billing windows.

A spend burn rate compares the fraction of a budget used with the fraction of the window elapsed. At day 3 of a 30-day window, spending 20% of the budget gives 0.20/(3/30)=20.20/(3/30)=2. At that constant pace the budget runs out on day 15. The admission example below uses a separate one-day scope to demonstrate a soft warning and a hard limit on modeled reservations.

PythonIn [21]
CollapseExpand
from decimal import Decimal


class BudgetGate:
    """Sequential gate for nonnegative estimates in decimal dollars."""

    def __init__(self, soft_cap_usd, hard_cap_usd):
        self.soft = Decimal(str(soft_cap_usd))
        self.hard = Decimal(str(hard_cap_usd))
        if not self.soft.is_finite() or not self.hard.is_finite():
            raise ValueError("Caps must be finite.")
        if not 0 <= self.soft <= self.hard:
            raise ValueError("Caps must satisfy 0 <= soft <= hard.")
        self.reserved = Decimal("0")

    def check_and_reserve(self, est_cost):
        estimate = Decimal(str(est_cost))
        if not estimate.is_finite() or estimate < 0:
            raise ValueError("Reserve a finite nonnegative estimate.")
        projected = self.reserved + estimate
        if projected > self.hard:
            return "reject"
        self.reserved = projected
        return "allow_warn" if projected > self.soft else "allow"


def burn_rate(spent, elapsed_days, total_days, budget):
    """Projected budget multiple at the observed constant pace."""
    projected = spent / elapsed_days * total_days
    return projected / budget


gate = BudgetGate(soft_cap_usd="800.00", hard_cap_usd="1000.00")
estimated_request_cost = Decimal(str(mean_cost))
decisions = {"allow": 0, "allow_warn": 0, "reject": 0}
for _ in range(120_000):
    decision = gate.check_and_reserve(estimated_request_cost)
    decisions[decision] += 1
ConsoleOut [22]
CollapseExpand
daily decisions: {'allow': 95946, 'allow_warn': 23986, 'reject': 68}
reserved in modeled day: $1000.00  (hard cap $1000.00)
day 3 monthly burn rate: 2.00x  (>1 means you will exhaust before the window closes)
pre-flight on near-full scope: reject

The modeled gate warns above the soft cap and rejects estimates that would exceed the hard cap. It uses decimal dollars so that reserving $0.10 and then $0.20 against a $0.30 cap reaches the limit exactly. The second example offers a $0.10 reservation with only $0.05 remaining and rejects it. An actual hard cap requires atomic reservations across callers, a conservative bound on the cost of each admitted request, and reconciliation against usage. An estimate based on the sample mean can understate realized charges.

Monitor spend against the forecast during the window. If demand or the workload mix changes, recalculate the forecast and decide whether to cap output, reduce scope, or shift to a cheaper route.

Failure Testing: Independent vs. Correlated Failure

Test the dependencies that share a provider, quota, or network path. A failure that appears independent when you test each stage in isolation can affect several stages of the same live request.

Ten independent components with 1% failure probability per component give 1−0.9910≈9.56%1-0.99^{10}\approx9.56\% probability that at least one fails. A shared outage with probability 1% and no other failure mode gives a 1% chance that all ten fail together. Both models average 0.1 failed components per request. Recovery differs because replicas in the same failure domain can fail together.

Use fault injection to test a hypothesis about degraded behavior. Start in a bounded environment. Set your stop conditions and limits on scope before a production experiment, in keeping with the Principles of Chaos Engineering.

A synthetic retrieve-and-generate pipeline tests how a shared outage affects retries and fallback. Compare the same failure schedule with and without an outage gate. Primary and fallback model attempts each have a fixed charge and duration, including on failure. Retrieval on a cache miss is charged only when it succeeds. The outcome counts as good only when it succeeds by one second. For this trial of 20,000 requests, compare with a 99.5% good-request target and a modeled spend limit of $210. The toy policy permits three primary attempts. It still charges for scripted work after the deadline. The one-second threshold scores the result at completion and never cancels an in-flight call or stops the fallback from starting. The gate gets the outage flag as input, which stands in for an already established health signal.

PythonIn [23]
CollapseExpand
def compound_request(fixture, gate_on, cache, deadline=1.0):
    """Run one simulated retrieval and generation request."""
    outage, context, primary_draws, fallback_draw = fixture
    latency = 0.015
    cost = 0.0
    if context not in cache:
        latency += 0.07
        if outage:
            return False, latency, cost, 0, False
        cache.add(context)
        cost += 0.0002

    attempts = 0
    if not (gate_on and outage):
        for i, draw in enumerate(primary_draws):
            if i:
                latency += 0.05 * 2 ** (i - 1)
            attempts += 1
            latency += 0.28
            cost += 0.010
            if not outage and draw >= 0.02:
                return latency <= deadline, latency, cost, attempts, False

    # For this scenario both models share the same outage.
    latency += 0.22
    cost += 0.003
    fallback_ok = not outage and fallback_draw >= 0.05
    return fallback_ok and latency <= deadline, latency, cost, attempts, True

Use the same seeded request fixtures in all variants. The baseline has independent attempt failures; the shared-outage variants reuse a fixed 1% outage flag per request. The primary and fallback share this failure domain.

ConsoleOut [24]
CollapseExpand
Independent attempt failures
  Good by the one-second deadline: 99.965%
  p99 latency: 0.625 s
  Modeled cost: $204.67
  Primary attempts per request: 1.019
  Fallback used: 0.000%
  Meets 99.5% SLO and $210 scenario budget: True
Shared outage, no gate
  Good by the one-second deadline: 99.140%
  p99 latency: 0.695 s
  Modeled cost: $207.42
  Primary attempts per request: 1.031
  Fallback used: 0.670%
  Meets 99.5% SLO and $210 scenario budget: False
Shared outage, with gate
  Good by the one-second deadline: 99.140%
  p99 latency: 0.625 s
  Modeled cost: $203.40
  Primary attempts per request: 1.011
  Fallback used: 0.670%
  Meets 99.5% SLO and $210 scenario budget: False

An open outage gate stops primary calls, saving attempts. A fallback in the same outage domain still fails. Compare the total spend and the SLI across the policies. Which policy costs more depends on what is billed on failed paths, what gets skipped, and which requests are recovered. An independently available fallback would need its own fault schedule and evaluation.

Test the failure you're afraid of

Exercise the operations and failure classes the service uses, such as timeouts and unusable responses. Include a shared failure mode, set the success and latency criterion before the run, and check whether spend stays within the chosen scenario budget.

Measuring the Whole Thing: Which Numbers to Trust

Use the same measurement choices for the load test and the live dashboard.

  • Eligible requests. Count timeouts and errors in the denominator for the request SLI defined here.
  • Latency. Measure through completion for this SLI. Report first-token latency separately for streaming.
  • Cost. Reconcile provider usage and subsequent invoice records. Include any billed attempts and tools.
  • Cache hits. Sample reused answers and estimate the share that is wrong.
  • Retry load. Track total attempts per original request alongside success and latency.
  • Latency distribution. Report percentiles as well as the mean so deadline misses remain visible.

Summary

Evaluate the policy with the same service boundary, workload, and billing assumptions you plan to use.

  • Define good requests and count the failed or late ones against a request-based error budget.
  • Cap and pace retries, and check whether they recover more qualifying requests within the deadline.
  • Reuse one key per logical operation and coordinate deduplication with the mutation it protects.
  • Apply Little's law to a consistent boundary, then measure latency and set headroom with load tests.
  • Set cache reuse rules and measure both hit rate and wrong-hit rate.
  • Forecast window spend, then bound and reconcile admission reservations when you need a hard cap.
  • Inject independent and shared failures. Check successful completion, added work, and cost.

Quiz

Ready to test your understanding? Take this quick quiz to reinforce what you've learned about reliability and cost engineering.

Reliability and Cost Engineering

Question 1 of 80 of 8 completed
A service records 20,000 eligible requests in a window and uses a 99.5% request-based SLO. How many bad requests does the error budget allow?
Join the discussionAsk a question or share what you learned.

Comments

Add to the conversation

A question, a correction, or an example from your own work.

No comments yet. Be the first to share your thoughts!

A different angle
All writing
Language AI Handbook · Vol. 20

Evaluation-Driven Development

Build an offline evaluation harness for language systems: versioned task suites, traces, slice scores, and regression gates that block hidden drops.

27 min read
Language AI Handbook · Vol. 20

Versioning Models, Prompts, Data, and Tools

Version AI systems with typed manifests, compatibility checks, canary rollouts, and lineage records that connect requests to their recorded configurations.

28 min read
Language AI Handbook · Vol. 20

Models, Retrieval, Tools, and Control Flow

Build a compound AI assistant with models, retrieval, tools, and explicit control flow. Learn to separate catalog data from inventory and degrade gracefully.

22 min read

About the author

Reference

Citation details

Cite or share this article.

BIBTEXAcademic
@misc{brenndoerfer2026reliabilitycost, author = {Michael Brenndoerfer}, title = {Reliability and Cost Engineering}, year = {2026}, url = {https://mbrenndoerfer.com/writing/reliability-cost-engineering-ai-slo-retries-caching}, organization = {mbrenndoerfer.com}, note = {Accessed: 2026-12-03} }
APAAcademic
Michael Brenndoerfer (2026). Reliability and Cost Engineering. Retrieved from https://mbrenndoerfer.com/writing/reliability-cost-engineering-ai-slo-retries-caching
MLAAcademic
Michael Brenndoerfer. "Reliability and Cost Engineering." 2026. Web. December 3, 2026. <https://mbrenndoerfer.com/writing/reliability-cost-engineering-ai-slo-retries-caching>.
CHICAGOAcademic
Michael Brenndoerfer. "Reliability and Cost Engineering." Accessed December 3, 2026. https://mbrenndoerfer.com/writing/reliability-cost-engineering-ai-slo-retries-caching.
HARVARDAcademic
Michael Brenndoerfer (2026) 'Reliability and Cost Engineering'. Available at: https://mbrenndoerfer.com/writing/reliability-cost-engineering-ai-slo-retries-caching (Accessed: December 3, 2026).
SimpleBasic
Michael Brenndoerfer (2026). Reliability and Cost Engineering. https://mbrenndoerfer.com/writing/reliability-cost-engineering-ai-slo-retries-caching
Newsletter

Stay up to date

Get new articles, book updates, and notes on AI and technology.

Unsubscribe at any time. Privacy policy