Choosing a model between cost, latency and quality: the Pareto front, the cost of an error and a bandit that can count money
You have five candidate models and none is the best at everything: one is cheap but gets more wrong, one answers quickly but costs three times as much, one is accurate and slow. Choosing "by eye" means choosing by the last demo you saw. This article builds the method in five steps, each with an executed listing: discard the candidates that another one beats on everything (the Pareto front), distrust that dominance when quality is measured on few examples, turn quality into euros with the cost of an error, see how much a multi-criteria ranking depends on its weights, and let real traffic decide with a bandit. The data are invented and declared as such; the models are names on a table row, and none is called.
I do not repeat here what the series has already covered. Routing by complexity and the power of an A/B test are in the article on caching, compression and routing; the non-inferiority test for replacing a model with a smaller one is in the article on techniques by layer. The problem here comes earlier: when there are more than two candidates and more than one objective, how do you reduce the choice to a few defensible options.
The matrix and the Pareto front: discarding what is beaten on everything
The matrix is a table with one row per candidate and one column per objective: euros per thousand requests, 95th-percentile latency, share of cases passed on an evaluation set. All the rest of the reasoning starts there, and from the fact that the columns cannot be added up: euros, milliseconds and percentages have no unit in common. A candidate dominates another if it is better or equal on every column and strictly better on at least one. The candidates that nobody dominates form the Pareto front, and only among those does it make sense to discuss trade-offs.
The listing uses five candidates with invented numbers and a set of 200 cases. The comparison is written with the standard library: quality enters with its sign flipped, so that all objectives are to be minimized and the dominance function stays one line. Discarded alternative: a multi-objective optimization package such as pymoo, which implements NSGA-II, an evolutionary algorithm that is useful when the options are not five rows but a continuous space of parameters (batch size, cache threshold). I did not run it: with five discrete candidates the double loop is enough and is readable.
# INVENTED data: five candidates and an evaluation set of 200 cases.
# cost = euros per 1000 requests; p95 = latency in milliseconds; passed = cases out of 200.
CANDIDATI = [
("A small", 0.40, 2400, 128),
("B medium", 1.80, 3100, 160),
("C budget", 0.90, 1300, 150),
("D premium", 6.50, 1800, 184),
("E legacy", 2.50, 2000, 148),
]
N = 200
def vettore(c):
nome, costo, p95, ok = c
# all to be MINIMIZED: quality enters with its sign changed
return (costo, p95, -ok / N)
def domina(x, y):
"""x dominates y if it is better or equal on everything and better on at least one objective."""
return all(a <= b for a, b in zip(x, y)) and any(a < b for a, b in zip(x, y))
for c in CANDIDATI:
dominatori = [d[0] for d in CANDIDATI if d is not c and domina(vettore(d), vettore(c))]
stato = "dominated by " + ", ".join(dominatori) if dominatori else "on the front"
print(f"{c[0]:<10} cost {c[1]:>5.2f} p95 {c[2]:>4} quality {c[3]/N:.0%} -> {stato}")
# Output:
# A small cost 0.40 p95 2400 quality 64% -> on the front
# B medium cost 1.80 p95 3100 quality 80% -> on the front
# C budget cost 0.90 p95 1300 quality 75% -> on the front
# D premium cost 6.50 p95 1800 quality 92% -> on the front
# E legacy cost 2.50 p95 2000 quality 74% -> dominated by C budget
Four candidates out of five stay on the front, and this is the normal case: the front does not choose, it narrows. Candidate E is discarded because C costs less, answers sooner and has a measured quality just above it (75% against 74%). The front also tells you what you are buying: from the lowest cost to the highest the quality rises, but not smoothly, and the latency of B (the worst) is the price of a quality better than C's at double the cost. Where it can hurt: the front is computed on measured values, and one of the three has a measurement error that the other two do not.
Dominance only holds if quality is measured well enough
Cost and latency are, at list price and at steady state, nearly exact numbers. Quality, instead, is a proportion estimated on 200 cases, and 148 against 150 successes does not prove that E is worse than C. To say so you need confidence intervals. I use the Wilson interval for a proportion, which holds up better than the normal interval when the proportion is far from 50% or the sample is small, and I declare a dominance "certain" only if the lower end of the dominant's quality exceeds the upper end of the dominated one's.
# Same INVENTED data as a_pareto.py. 95% Wilson interval on the measured quality.
from math import sqrt
Z = 1.96
N = 200
CANDIDATI = [
("A small", 0.40, 2400, 128),
("B medium", 1.80, 3100, 160),
("C budget", 0.90, 1300, 150),
("D premium", 6.50, 1800, 184),
("E legacy", 2.50, 2000, 148),
]
def wilson(k, n, z=Z):
p = k / n
centro = (p + z * z / (2 * n)) / (1 + z * z / n)
metà = z * sqrt(p * (1 - p) / n + z * z / (4 * n * n)) / (1 + z * z / n)
return centro - metà, centro + metà
intervalli = {c[0]: wilson(c[3], N) for c in CANDIDATI}
for nome, (lo, hi) in intervalli.items():
print(f"{nome:<10} measured quality with interval [{lo:.3f}, {hi:.3f}]")
def dominanza_sicura(x, y):
"""x dominates y CERTAINLY if cost and latency are better or equal
(they are known) and the lower end of x's quality exceeds the upper end of y's."""
cx, cy = next(c for c in CANDIDATI if c[0] == x), next(c for c in CANDIDATI if c[0] == y)
return cx[1] <= cy[1] and cx[2] <= cy[2] and intervalli[x][0] > intervalli[y][1]
print()
for x in CANDIDATI:
for y in CANDIDATI:
if x is not y and x[1] <= y[1] and x[2] <= y[2] and x[3] >= y[3]:
esito = "certain" if dominanza_sicura(x[0], y[0]) else "NOT proven"
print(f"{x[0]} dominates {y[0]} on the measured points: dominance {esito}")
# Output:
# A small measured quality with interval [0.571, 0.703]
# B medium measured quality with interval [0.739, 0.850]
# C budget measured quality with interval [0.686, 0.805]
# D premium measured quality with interval [0.874, 0.950]
# E legacy measured quality with interval [0.675, 0.796]
#
# C budget dominates E legacy on the measured points: dominance NOT proven
The dominance of C over E holds on the measured points, but the intervals overlap almost completely: from 0.686 to 0.805 against 0.675 to 0.796. The practical consequence is that E should not be eliminated for this reason: it should be eliminated for another one, if there is one (for example because it costs more and answers slower, and the quality is indistinguishable anyway). With 200 cases, three points of difference are noise. The same logic applies to B against C: B looks five points better, but the intervals overlap, and it is the 3,100 ms of latency that puts it outside a limit of 2,500. If you need to tell two close candidates apart you have to enlarge the evaluation set; the calculation of how many examples you need is in the routing article cited above.
From quality to euros: the cost of an error
The problem remains of choosing a point on the front. The simplest method is an SLA with thresholds: 95th-percentile latency within 2,500 ms and quality of at least 70%; among the admissible candidates you take the cheapest. It is the criterion that the FinOps Foundation describes for model selection: the least expensive one that meets the requirements. It works, but it treats the cost of the call as the only cost, and a cheaper model that gets more wrong moves the cost elsewhere: into the work of whoever corrects, into tickets, into refunds.
The next step is to put a price on the error. The listing adds to the cost of the calls the product of the number of wrong answers and the cost of one error, a parameter that no price list gives you: you have to estimate it yourself, for example from the time of a person who corrects. I try it with two values and compute the break-even between C and D, that is, the error cost above which the expensive model becomes the most convenient.
# INVENTED data (the same as the previous listings). The cost of an error is YOUR assumption:
# here it is the cost of having a person correct a wrong answer.
N = 200
CANDIDATI = [
("A small", 0.40, 2400, 128),
("B medium", 1.80, 3100, 160),
("C budget", 0.90, 1300, 150),
("D premium", 6.50, 1800, 184),
("E legacy", 2.50, 2000, 148),
]
SLA_P95_MS = 2500
SLA_QUALITA = 0.70
RICHIESTE = 1000
def ammissibile(c):
return c[2] <= SLA_P95_MS and c[3] / N >= SLA_QUALITA
def costo_totale(c, costo_errore):
"""euros per 1000 requests: call + correction of the errors."""
errori = (1 - c[3] / N) * RICHIESTE
return c[1] + errori * costo_errore
for costo_errore in (0.02, 0.05):
print(f"cost of an error: {costo_errore:.2f} euro")
righe = sorted(CANDIDATI, key=lambda c: costo_totale(c, costo_errore))
for c in righe:
marca = "SLA ok" if ammissibile(c) else "outside SLA"
print(f" {c[0]:<10} calls {c[1]:>5.2f} total {costo_totale(c, costo_errore):>6.2f} {marca}")
migliore = next(c for c in righe if ammissibile(c))
print(f" choice among the admissible: {migliore[0]}")
# Break-even between C and D: the error cost beyond which the more expensive model pays off.
C, D = CANDIDATI[2], CANDIDATI[3]
errori_C = (1 - C[3] / N) * RICHIESTE
errori_D = (1 - D[3] / N) * RICHIESTE
pareggio = (D[1] - C[1]) / (errori_C - errori_D)
print(f"break-even C/D: {pareggio:.4f} euro per error")
# Output:
# cost of an error: 0.02 euro
# B medium calls 1.80 total 5.80 outside SLA
# C budget calls 0.90 total 5.90 SLA ok
# A small calls 0.40 total 7.60 outside SLA
# E legacy calls 2.50 total 7.70 SLA ok
# D premium calls 6.50 total 8.10 SLA ok
# choice among the admissible: C budget
# cost of an error: 0.05 euro
# D premium calls 6.50 total 10.50 SLA ok
# B medium calls 1.80 total 11.80 outside SLA
# C budget calls 0.90 total 13.40 SLA ok
# E legacy calls 2.50 total 15.50 SLA ok
# A small calls 0.40 total 18.40 outside SLA
# choice among the admissible: D premium
# break-even C/D: 0.0329 euro per error
With an error at 0.02 euro C wins; with 0.05 D wins, which costs seven times as much per call. The break-even is at about 0.033 euro per error, and it is the number to bring to the meeting: instead of arguing whether "we need the premium model", you argue whether an error is worth more or less than three cents. Note B as well: outside the SLA because of latency, it would come out best at the first value and second at the second. That tells you whether it is worth renegotiating the latency limit, not whether to violate it. The limit of the method: the cost of an error is uniform in the example, while in reality an error on an important request costs far more than one on a trivial request, and that is where routing by complexity becomes a natural extension.
A ranking with weights: TOPSIS and how much it depends on who chooses the weights
When you cannot put a price on the error, the weighted ranking remains. TOPSIS normalizes each column, applies the weights, and orders the candidates by closeness to the ideal solution (the best value of each column) and distance from the worst. The listing implements it in a few lines and runs it varying the weight of quality from 0 to 1, with the rest split between cost and latency. In a second pass it removes candidate E, to see whether a dominated candidate affects the ranking.
# TOPSIS with the standard library, on the INVENTED data. Criteria: cost (min), p95 (min), quality (max).
from math import sqrt
DATI = {
"A small": (0.40, 2400, 0.64),
"B medium": (1.80, 3100, 0.80),
"C budget": (0.90, 1300, 0.75),
"D premium": (6.50, 1800, 0.92),
"E legacy": (2.50, 2000, 0.74),
}
VERSO = ("min", "min", "max")
def topsis(dati, pesi):
nomi = list(dati)
col = list(zip(*dati.values()))
norme = [sqrt(sum(v * v for v in c)) for c in col]
pesata = {n: [dati[n][j] / norme[j] * pesi[j] for j in range(3)] for n in nomi}
ideale = [(max if VERSO[j] == "max" else min)(pesata[n][j] for n in nomi) for j in range(3)]
peggio = [(min if VERSO[j] == "max" else max)(pesata[n][j] for n in nomi) for j in range(3)]
punteggi = {}
for n in nomi:
dp = sqrt(sum((pesata[n][j] - ideale[j]) ** 2 for j in range(3)))
dn = sqrt(sum((pesata[n][j] - peggio[j]) ** 2 for j in range(3)))
punteggi[n] = dn / (dp + dn)
return punteggi
# Quality weight from 0 to 1; the rest is split evenly between cost and latency.
# Second column: same calculation WITHOUT candidate E, which is dominated by C.
SENZA_E = {n: v for n, v in DATI.items() if n != "E legacy"}
precedente = None
for passo in range(0, 11):
w = passo / 10
pesi = ((1 - w) / 2, (1 - w) / 2, w)
p = topsis(DATI, pesi)
q = topsis(SENZA_E, pesi)
v1, v2 = max(p, key=p.get), max(q, key=q.get)
segno = " <- changes" if v1 != precedente else ""
diverso = " (without E the winner is " + v2 + ")" if v2 != v1 else ""
print(f"quality weight {w:.1f}: winner {v1:<10}{segno}{diverso}")
precedente = v1
# Output:
# quality weight 0.0: winner C budget <- changes
# quality weight 0.1: winner C budget
# quality weight 0.2: winner C budget
# quality weight 0.3: winner C budget
# quality weight 0.4: winner C budget
# quality weight 0.5: winner C budget
# quality weight 0.6: winner C budget
# quality weight 0.7: winner C budget
# quality weight 0.8: winner D premium <- changes
# quality weight 0.9: winner D premium
# quality weight 1.0: winner D premium
The winner changes only once, between weight 0.7 and 0.8: below it C wins, above it D wins. No row carries the note "without E the winner is", so in this example removing the dominated candidate changes nothing. The useful result is not who wins, but where it changes: the choice of model depends on a threshold on the weight, and it is worth discussing with whoever pays. Two caveats. The weights are declared preferences, not measurements: whoever chooses 0.6 instead of 0.8 chooses the model. And TOPSIS does not know the euro: the same problem solved with the cost of the error gave you the break-even in units of money, which is easier to discuss than a dimensionless weight.
Letting traffic decide: Thompson sampling with a reward that includes cost
If quality cannot be estimated beforehand, for example because real traffic differs from the evaluation set, you can estimate it during operation. Thompson sampling is an algorithm for sequential decision problems that balances exploitation and exploration (Russo and others give a tutorial). For each candidate you keep a Beta distribution on the success rate, at each request you draw one sample per candidate and send the request to the one with the highest sample, then you update successes and failures. The listing uses candidates C and D of the example, a generator with a fixed seed, and compares four policies over 2,000 requests: a fixed 50/50 split, the bandit that looks only at quality, and two bandits that include the cost with the two values of the cost of an error.
# Thompson sampling on two candidates admitted by the SLA, with SCRIPTED fake models:
# the probability of an acceptable answer is an invented figure, no model is called.
import random
VERA = {"C budget": 0.75, "D premium": 0.92} # unknown to the bandit
COSTO_1000 = {"C budget": 0.90, "D premium": 6.50}
ROUND = 2000
def esegui(politica, seme, costo_errore=None):
rng = random.Random(seme)
alfa = {n: 1 for n in VERA} # successes + 1 (uniform prior)
beta = {n: 1 for n in VERA} # failures + 1
conta = {n: 0 for n in VERA}
fallimenti = 0
for t in range(ROUND):
if politica == "fixed 50/50":
scelto = list(VERA)[t % 2]
else:
campioni = {n: rng.betavariate(alfa[n], beta[n]) for n in VERA}
if costo_errore is not None:
# net expected value: sampled success probability x cost avoided - price of the call
campioni = {n: campioni[n] * costo_errore - COSTO_1000[n] / 1000 for n in VERA}
scelto = max(campioni, key=campioni.get)
ok = rng.random() < VERA[scelto]
conta[scelto] += 1
if ok:
alfa[scelto] += 1
else:
beta[scelto] += 1
fallimenti += 1
costo = sum(conta[n] * COSTO_1000[n] / 1000 for n in VERA)
return conta, fallimenti, costo
PROVE = [("fixed 50/50", None), ("thompson, quality only", None),
("thompson, error 0.02", 0.02), ("thompson, error 0.05", 0.05)]
for nome, ce in PROVE:
pol = "fixed 50/50" if nome.startswith("fixed") else "thompson"
conta, fall, costo = esegui(pol, 7, ce)
quote = ", ".join(f"{n} {conta[n]}" for n in VERA)
print(f"{nome:<24} requests: {quote}; wrong {fall}; calls {costo:.2f} euro")
print(f"{'':<24} total with errors at 0.02: {costo + fall * 0.02:.2f} euro, at 0.05: {costo + fall * 0.05:.2f} euro")
# One seed is not enough: mean over 20 seeds of the total (calls + errors at 0.05).
for nome, pol, ce in (("quality only", "thompson", None), ("error 0.05", "thompson", 0.05)):
tot = []
for seme in range(20):
_, fall, costo = esegui(pol, seme, ce)
tot.append(costo + fall * 0.05)
print(f"mean over 20 seeds, thompson {nome}: {sum(tot)/20:.2f} euro (from {min(tot):.2f} to {max(tot):.2f})")
# Output:
# fixed 50/50 requests: C budget 1000, D premium 1000; wrong 327; calls 7.40 euro
# total with errors at 0.02: 13.94 euro, at 0.05: 23.75 euro
# thompson, quality only requests: C budget 28, D premium 1972; wrong 172; calls 12.84 euro
# total with errors at 0.02: 16.28 euro, at 0.05: 21.44 euro
# thompson, error 0.02 requests: C budget 1995, D premium 5; wrong 506; calls 1.83 euro
# total with errors at 0.02: 11.95 euro, at 0.05: 27.13 euro
# thompson, error 0.05 requests: C budget 255, D premium 1745; wrong 221; calls 11.57 euro
# total with errors at 0.02: 15.99 euro, at 0.05: 22.62 euro
# mean over 20 seeds, thompson quality only: 21.23 euro (from 19.91 to 22.16)
# mean over 20 seeds, thompson error 0.05: 21.75 euro (from 20.60 to 23.36)
The "quality only" bandit makes about half the errors of the fixed split (172 against 327), but sends almost everything to D and spends 12.84 euro on calls against 7.40: if your goal is cost, it has optimized the wrong thing. In the two variants with the cost of an error, the bandit finds the right answer for each value: with 0.02 it sends almost everything to C (1,995 requests), with 0.05 most of it to D (1,745 requests). On the run with seed 7, at 0.05 the variant with cost spent more than the quality-only one (22.62 against 21.44); the mean over 20 seeds confirms it (21.75 against 21.23). The explanation is that at 0.05 the two candidates are almost level in net expected value: the bandit keeps exploring and pays for the exploration. Had you known in advance that D is the best, the expected cost over 2,000 requests would be 2,000 × 6.50 / 1,000 = 13.00 of calls plus 2,000 × 0.08 × 0.05 = 8.00 of errors, that is 21.00: better than both, but only because in this example the truth is known.
So the bandit is not a free optimization: it pays off when quality is really uncertain and traffic is plentiful, because exploration has a cost that is amortized over many requests. It does not pay off with little traffic, with nearly equivalent candidates, or when a wrong answer has consequences that you cannot repay with an average cost: there you need a test done beforehand, with an evaluation set.
Which tool, when
The five methods answer different questions, and the list below lines them up.
- Pareto front: which candidates are not even worth discussing. It needs only the matrix; it does not choose.
- Intervals on quality: whether the dominance found is real or sample noise. It needs the number of cases in the evaluation set.
- Total cost with the cost of an error: which candidate costs less, and where the break-even lies. It needs an estimate of the error in euros.
- TOPSIS: how the ranking changes with the weights. It is useful when the error cannot be priced; the threshold of change is the result.
- Thompson sampling: which candidate is best on real traffic. It needs plentiful traffic and an objective written in euros.
The order is not a hierarchy of quality but an order of work: the first two methods reduce the candidates and cost a spreadsheet, the third and the fourth choose with explicit assumptions, the last requires a system in operation. If you changed the order of the methods, the meaning would change: the bandit before the front wastes traffic on candidates that are already beaten.
Frequently asked questions
What does it mean for a model to be on the Pareto front?
That no other candidate is better or equal on all objectives and strictly better on at least one. The front does not tell you which model to use: it reduces the choice to the candidates among which a real trade-off exists.
How do I estimate the cost of an error?
Start from whoever pays for it: the time of a person who corrects the answer, the cost of a ticket or of a refund. There is no universal value, and that is why the listing computes the break-even: it tells you at which error cost the choice changes, and you only need to compare it with your estimate.
Is a bandit better than an A/B test?
Not in general. The bandit reduces the requests sent to the worse candidate during the trial, but it pays for exploration and does not produce a confidence interval as simple as a fixed-sample test. With nearly equivalent candidates, in the example, it spent more than a policy that looked only at quality.
What you can do now
You can reduce a choice among five models to the Pareto front, and you know when the dominance found is only noise in the evaluation set. You can turn quality into euros with the cost of an error and find the break-even between two candidates, you can see at which point a weighted ranking changes winner, and you can set up a bandit with a reward that includes cost, knowing the price of exploration. All the numbers in the listings are invented: replace them with your own. If your choices concern the GPUs the models run on, start again from the article on GPU planning; to attribute cost to teams and budgets, continue with the article on cost accountability per team.
Sources
- FinOps for AI Overview (FinOps Foundation) - choosing the least expensive model that meets the required accuracy, latency and reliability; accessed 2026-11-13
- A Tutorial on Thompson Sampling (Russo et al., abstract) - algorithm for sequential decisions that balances exploitation and exploration; accessed 2026-11-13
- NSGA-II: Non-dominated Sorting Genetic Algorithm (pymoo documentation) - page of the algorithm cited as an alternative that was not run; accessed 2026-11-13
- random: generate pseudo-random numbers (Python documentation) - seeded generator and Beta distribution used in the bandit listing; accessed 2026-11-13
- Runs executed locally:
python3 -Ion the five listings (standard library, Python 3.14.4), each twice with identical output; candidates, quality, costs and error costs invented for the example. No model run; the Wilson interval formula and TOPSIS are textbook, not verified against an open source here

Commenti
Caricamento commenti...
Sign in to comment