Reliability and Cost Engineering
Design reliable, cost-aware AI services with SLOs, retries, idempotency, Little's law, caching, and fault injection under real deadlines.
Language AI HandbookAll chapters 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.
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.
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 , about 96.1%. Adding eight more otherwise identical calls makes it , 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 in seconds and let equal one on success and zero on failure. The SLI counts successful requests that meet the deadline.
Here ranges over eligible requests in the measurement window. records success, is end-to-end latency in seconds, and 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 requests and target , the SLI meets the objective when . Equivalently, at most 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]Expand
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 secondsIf the logarithm of latency has mean and standard deviation , the lognormal median is seconds. Its mean is seconds. Increasing at fixed spreads the distribution while leaving its median unchanged.
Now compute the SLI, the error budget, and the percentile structure.
ConsoleOut [4]Expand
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]Expand
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]Expand

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.
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 success. During a shared outage, failure on one attempt can make the next failure more likely.
With independent attempts and per-attempt success probability , all attempts fail with probability . The probability that at least one succeeds is its complement. In the second model, an outage with probability lasts for the entire retry sequence. Conditional on no outage, the attempts are independent with success probability , giving unconditional success .
PythonIn [7]Expand
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]Expand
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 , one attempt succeeds with probability . 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]Expand
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]Expand
--- 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]Expand
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]Expand

With failure probability and at most three independent attempts, the second attempt occurs with probability and the third with probability . The expected number of attempts is : 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 . The printed p99 includes both outcomes and can change when fast failures are replaced by successful calls that do more work.
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]Expand
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]Expand
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]Expand
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.
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.
Here is the long-run mean number of requests inside a boundary, is the rate of requests entering that boundary, and 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, for arrival rate below service rate . 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]Expand
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]Expand
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]Expand
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]Expand

The dashed curve adds mean waiting time to fixed service time seconds. If is utilization, the M/D/1 mean is . 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.
Here is the probability of a cache hit. Each is a conditional mean latency and each is a conditional mean cost, weighted by the probability of that path. For a semantic cache, if is the fraction of hits that give a wrong answer, the probability of a wrong cache hit per request is . That quantity says nothing about miss-path mistakes. The two operating points below are stipulated examples, not measured threshold performance.
PythonIn [18]Expand
# 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]Expand
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.
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 and output tokens by their respective prices per token, and .
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]Expand
# 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]Expand
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 . 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]Expand
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] += 1ConsoleOut [22]Expand
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: rejectThe 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 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]Expand
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, TrueUse 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]Expand
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.
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
Join the discussionAsk a question or share what you learned.
Keep exploring
Reference
Citation details
Cite or share this article.


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!