Foundations to Frontier
Tests
N. MLOps and AI Systems Engineering › N4 Monitoring and Maintenance

Cost and Latency Optimization

A model that is accurate but too slow or too expensive does not survive in production. Most of the cost and latency of a prediction service can be cut without retraining anything: by not computing the same answer twice, by sending easy requests to a cheap model, by sizing and choosing hardware for the actual load, and by finding which stage of the request really dominates. The exercises build a prediction service with Zipf-distributed item popularity, a cheap small model and an accurate large one, and compare five configurations (large model only, small model only, a cache, a confidence cascade, and both) on accuracy, cost per million requests, and median and tail latency. Practice problems cover fleet sizing with queueing theory, cache expiry and stale answers, CPU against GPU instances by traffic level, three-stage cascades under a budget, and latency profiling.

Level 0: Foundation

★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.

The help desk

A help desk that sends every question to its most senior expert is accurate, slow and expensive. Most questions repeat, so a page of frequent answers handles many of them at once; a junior colleague can answer the easy ones and pass on only those they are unsure of; and the number of staff on duty should follow the hours when questions arrive. A prediction service saves money and time in the same three ways: caching, cascades and right-sizing.

🎮 MLOps lab
large model only
$52.45 per million · acc 0.9082 · p50 41 / p99 129.4 ms
small model only
$0.11 per million · acc 0.7666 · p50 3 / p99 7.4 ms
cache + large model
$10.35 per million · acc 0.9063 · p50 1.5 / p99 91.6 ms
cascade (tau 1.0)
$28.69 per million · acc 0.8918 · p50 23.1 / p99 117.5 ms
cache + cascade (tau 1.0)
$5.67 per million · acc 0.8905 · p50 1.5 / p99 80.6 ms

With answers changing every 6 hours on average: hit rate 56.0%, accuracy 0.9035 (0.9067 without a cache), $23.07 per million. The cache cuts cost and the median, but the p99 still belongs to the misses.

Why engineers care

In Exercise 2, a cache of 10,000 answers cut the cost of the large model from $52 to $10 per million requests with no loss of accuracy; adding a cascade brought it to $5.67 for 1.8 points of accuracy.

📝 Quick check (Level 0)
0/3 answered
  1. 1. A result cache saves cost when…
  2. 2. A model cascade sends to the large model…
  3. 3. Tail latency (p99) is…

Level 1: Beginner

★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.

By hand

  • Latency percentiles: p50 (median), p95, p99; service-level objectives are usually stated on a tail percentile.
  • Cost per million requests: compute hours times price, divided by the target utilisation, plus fixed costs (caches, load balancers).
  • Result caching: store answers keyed by the request; an LRU cache evicts the least recently used entry; a time-to-live (TTL) bounds how outdated an answer can be.
  • Model cascade: a cheap model answers when it is confident (|margin| above a threshold τ); otherwise the request escalates to a more expensive model.
  • Capacity planning: queueing models (M/M/c, Erlang C) give the number of servers needed for a waiting-time target.
  • Hardware choice: CPUs are cheap per instance; GPUs are cheaper per request only when kept busy.
  • Profiling: measure each stage’s share of latency before optimising (Amdahl’s law).
📝 Quick check (Level 1)
0/3 answered
  1. 1. An LRU cache evicts…
  2. 2. A cache TTL limits…
  3. 3. Erlang C gives…

Level 2: Intermediate

★★★☆☆ Intermediate⏱ 25 minUndergraduate students and practising engineers.

A prediction service

Exercise 1.

  • 200,000 items with Zipf popularity (exponent 1.1): the top 1,000 items receive about 73% of requests.
  • Each request has a hidden signal; its label is the sign. A model’s margin is the signal plus noise: 0.9 for the small model (CPU, 2 ms median, $0.10 per hour) and 0.3 for the large model (GPU, 40 ms median, $2.50 per hour).
  • Compute times are log-normal with log-sd 0.5; 1 ms of network time per request; 0.5 ms for a cache hit.
  • An LRU cache replays the request stream.

Practice.

  • Cache what repeats, with a TTL that matches how fast answers change.
  • Cascade cheap and expensive models, tuning the threshold on the cost–accuracy curve.
  • Size fleets for the tail, with queueing models checked by load tests.
  • Match hardware to load: GPUs for heavy, steady traffic; CPUs or serverless for light traffic.
  • Profile before optimising, and track p99, not only the mean.
def serve(request):
    if request.key in cache and age(request.key) < TTL:
        return cache[request.key]                  # ~0.5 ms
    margin = small_model(request)                  # ~2 ms
    if abs(margin) <= tau:
        margin = large_model(request)              # ~40 ms
    cache[request.key] = sign(margin)
    return sign(margin)
🐍 Exercise 1: traffic, models and a cache
Generate Zipf-distributed requests, small and large models with log-normal compute times, and replay the traffic through LRU caches of different sizes.
📝 Quick check (Level 2)
0/3 answered
  1. 1. A cache barely improves p99 latency because…
  2. 2. Raising the cascade threshold τ…
  3. 3. A cache without expiry on changing answers…

Level 3: Advanced

★★★★☆ Advanced⏱ 25 minGraduate level, with full derivations and proofs.

Theory

Log-normal latency. If compute time is m·e^(σZ) with Z standard normal, the median is m, the mean m·e^(σ²/2) and the p99 m·e^(2.326σ). For m = 40 ms and σ = 0.5: mean 45.3 ms, p99 128 ms. Cost follows the mean; user experience follows the tail.

Caching under Zipf traffic. With popularity proportional to 1/k^a, a cache of the C most popular items catches a share H(C, a)/H(N, a) of requests, where H is the generalized harmonic number. For a near 1 this grows like log C, so the first entries help most and the hit rate saturates. A cache hit costs almost nothing, so cost scales with the miss rate; the p99 of all requests is set by the misses once misses exceed 1% of traffic.

Cascades. If a share s of requests escalate, the cost is c_small + s·c_large and the latency of an escalated request is the sum of both models. Accuracy is that of the large model on escalated requests and of the small model on confident ones; a threshold on a well-calibrated margin escalates exactly the requests where the small model is most likely wrong.

Queues. In an M/M/c queue with offered load a = λ/μ, the probability of waiting is Erlang C, C(c, a), and P(W > t) = C(c, a)·e^(−(cμ − λ)t). For a fixed waiting target the spare capacity needed grows like √a, so utilisation rises with scale: small services pay for idle servers.

📝 Quick check (Level 3)
0/3 answered
  1. 1. The mean of a log-normal latency with median m and log-sd σ is…
  2. 2. Under Zipf traffic, doubling the cache size…
  3. 3. Larger fleets can run at higher utilisation because…

Level 4: Expert

★★★★★ Expert⏱ 30 minResearchers: original papers and open problems.

How much do caching and a model cascade save in cost and latency, and what do they cost in accuracy?

History.

  • A. K. Erlang (1909, 1917) founded queueing theory to size telephone exchanges; his formulas still size server fleets.
  • L. Belady (1966) analysed cache replacement policies; LRU became the default in operating systems and web caches.
  • P. Viola and M. Jones (2001) made cascades famous with a face detector that rejected most image windows with a few cheap features.
  • J. Dean and L. A. Barroso (2013), “The tail at scale,” made the p99 the target of large web services.
  • Inference serving systems such as Clipper (D. Crankshaw and colleagues, 2017) combined caching, batching and model selection.

Exercise 2.

  • 200,000 requests; costs at 60% target utilisation; a cache server at $0.50 per hour at 2,000 requests per second.
  • Configurations: large model only; small model only; a 10,000-entry LRU cache with the large model; a cascade with τ = 1.0; and the cache with the cascade.

Seed 0:

configuration accuracy $ per million p50 ms p99 ms cache hit rate
large model only 0.9082 52.45 41.0 129.4 0%
small model only 0.7666 0.11 3.0 7.4 0%
cache + large model 0.9063 10.35 1.5 91.6 80.3%
cascade (τ 1.0) 0.8918 28.69 23.1 117.5 0%
cache + cascade (τ 1.0) 0.8905 5.67 1.5 80.6 80.3%

Cascade thresholds without a cache (accuracy, $ per million): τ 0.25: 0.8156, 7.77; τ 0.5: 0.8506, 15.29; τ 1.0: 0.8903, 28.60; τ 1.5: 0.9040, 38.66; τ 2.0: 0.9067, 45.35.

Seeds 1 and 2: large model only 0.9073 and 0.9065 at $52.43 and $52.47; cache + large model $10.50 and $10.54 with p99 91.9 and 92.6 ms; cache + cascade $5.77 and $5.79 at accuracy 0.8902 and 0.8891.

Findings.

  • The cache cut cost about five-fold and the median to 1.5 ms at no loss of accuracy, because 80% of requests repeat recent ones.
  • The p99 fell only from about 129 to 92 ms: the slowest 1% of requests are cache misses served by the large model.
  • The cascade traded accuracy for cost smoothly: τ 1.5 kept accuracy within half a point of the large model at 74% of its cost; τ 0.25 cost 15% for 9 points less accuracy.
🐍 Exercise 2 (research): how much do caching and a model cascade save in cost and latency, and what do they cost in accuracy?
Compare five serving configurations on accuracy, cost per million requests, and p50 and p99 latency, and sweep the cascade threshold.

Cost and latency in practice

  • Caches sit at several levels: CDN and API caches for whole responses, embedding and feature caches, and key–value caches inside large language models (prefix caching).
  • Cascades and routing send queries to small or large models by confidence or predicted difficulty (FrugalGPT, LLM routers), and early-exit networks stop computing when an intermediate layer is confident.
  • Capacity planning combines queueing models with load tests and autoscaling; cost dashboards attribute spend per model and per team (FinOps).
  • Hardware choices include CPUs, GPUs, inference accelerators (Inferentia, TPUs) and serverless inference for spiky low traffic.
  • Onboard and ground segments of satellite missions apply the same ideas: cheap screening models flag the few scenes worth full processing or downlink.

References

  1. A. K. Erlang (1917). “Solution of some problems in the theory of probabilities of significance in automatic telephone exchanges.” Elektroteknikeren.
  2. L. A. Belady (1966). “A study of replacement algorithms for a virtual-storage computer.” IBM Systems Journal.
  3. P. Viola and M. Jones (2001). “Rapid object detection using a boosted cascade of simple features.” CVPR.
  4. J. Dean and L. A. Barroso (2013). “The tail at scale.” Communications of the ACM.
  5. D. Crankshaw and colleagues (2017). “Clipper: a low-latency online prediction serving system.” NSDI.
  6. L. Chen, M. Zaharia and J. Zou (2023). “FrugalGPT: how to use large language models while reducing cost and improving performance.” arXiv.