Routing, Fallbacks, and Graceful Degradation › Implementing a Routing Harness

Michael BrenndoerferDecember 2, 202610 min read
Language AI HandbookAll chapters
Part 64 of 67Compound AI System Design
Chapter 486Routing, Fallbacks, and Graceful Degradation › Implementing a Routing Harness
Reading section 4 of 10 · Implementing a Routing Harness · 10 minSection 4 of 10 · 10 min

Section 4 of 10 · 10 min read

Reading settings

Definitions

Choose how many terms have tooltips.

Article links

Make inline references clickable

Notes & comments

Simulating the Routing Problem

The benchmark builds one candidate for each request and tier. The request includes a synthetic difficulty dd between 0 and 1. For each tier, the simulator samples whether its candidate is correct using probability pp. The function p = easy - drop * d uses the tier's easy-case correctness easy and its full-range decrease drop. The score is drawn around 0.82 for a correct candidate and around 0.43 for a wrong one, with uniform noise from −0.25 to 0.25, then clipped to the unit interval. The score distributions overlap, so the gate can reject a correct response or accept a wrong one.

The simulation uses the hidden label to construct a noisy score on purpose. A real scorer would have to infer quality at decision time. The benchmark uses a local pseudorandom generator and seed 27. The same materialized rows feed every policy. Results are synthetic policy checks.

PythonIn [3]
CollapseExpand
from dataclasses import dataclass
from random import Random


@dataclass(frozen=True)
class Tier:
    name: str
    cost: int
    easy: float
    drop: float


@dataclass(frozen=True)
class Candidate:
    score: float
    correct: bool

Modeling Model Tiers

The three tiers in this simulation have different intercepts and slopes in the difficulty model. Small starts at 0.88 on the easiest requests and falls to 0.38 at difficulty 1. Middle falls from 0.94 to 0.59. Large falls from 0.98 to 0.78. These differences are choices in the fixture. The purpose of the rates is to reveal what the router does with different candidates, while the benchmark makes no claim that real providers have those rates.

PythonIn [4]
CollapseExpand
TIERS = (
    Tier("Small", 1, 0.88, 0.50),
    Tier("Middle", 4, 0.94, 0.35),
    Tier("Large", 12, 0.98, 0.20),
)
PythonIn [5]
CollapseExpand
def make_rows(seed: int, count: int) -> tuple[tuple[Candidate, ...], ...]:
    rng = Random(seed)
    rows = []
    for _ in range(count):
        d = rng.random()
        candidates = []
        for tier in TIERS:
            correct = rng.random() < tier.easy - tier.drop * d
            center = 0.82 if correct else 0.43
            score = min(1.0, max(0.0, center + rng.uniform(-0.25, 0.25)))
            candidates.append(Candidate(score, correct))
        rows.append(tuple(candidates))
    return tuple(rows)

The curve below evaluates the assumed probability function directly. It records the expected behavior at a given difficulty before any correctness or score draws. The larger tier is assigned a higher probability throughout the plotted range. That assumption makes this a useful comparison fixture, and it does not follow mechanically from the fact that its attempt price is higher.

PythonIn [6]
CollapseExpand
difficulty_grid = tuple(step / 20 for step in range(21))
tier_rates = {
    tier.name: tuple(tier.easy - tier.drop * d for d in difficulty_grid)
    for tier in TIERS
}
VisualizationOut [7]
CollapseExpand
Three declining correctness-probability lines over synthetic difficulty.
The simulator assigns each tier a linearly declining probability of a correct candidate as difficulty increases. These rates are assumed.

The Acceptance Function

The correctness rates say how often each model gets its request right. They do not, by themselves, say which answer the router should accept. We model that separate signal with synthetic scores. Take the same candidate rows that will enter the comparison and collect their scores by correctness. All three tiers are pooled in this figure. The histogram is evidence about the simulated scorer and can illustrate where threshold mistakes come from without assuming a particular tier's score distribution in real traffic.

PythonIn [8]
CollapseExpand
from collections import Counter

rows = make_rows(seed=27, count=2_000)
score_bins = Counter(
    (candidate.correct, min(9, int(10 * candidate.score)))
    for row in rows
    for candidate in row
)
score_left = tuple(i / 10 for i in range(10))
score_correct = tuple(score_bins[True, i] for i in range(10))
score_incorrect = tuple(score_bins[False, i] for i in range(10))
assert sum(score_correct) + sum(score_incorrect) == 3 * len(rows)
VisualizationOut [9]
CollapseExpand
Overlapping synthetic score counts by correct and incorrect candidate.
Counts of synthetic scores pooled across all three tiers. The classes overlap, including in the bins nearest the example gate's threshold.

Baseline: Always Use the Large Model

The small-only and large-only baselines accept every candidate from one tier. The cascade accepts the first score greater than or equal to 0.65 and abstains if every tier misses. The benchmark assumes all tiers are eligible and available. We will vary those conditions separately so the comparison measures policy choice under a common workload.

For binary correctness, coverage is the fraction of all requests answered. Accuracy on answered requests divides correct delivered answers by the number answered. If that denominator is zero, conditional accuracy is undefined. The distinction is the same one that motivates the risk–coverage tradeoff in selective classification. We also report correct delivered answers divided by all requests so a policy that abstains often cannot appear to solve more requests merely by reducing its denominator.

PythonIn [10]
CollapseExpand
def choose(
    row: tuple[Candidate, ...], order: tuple[int, ...], threshold: float
) -> tuple[int | None, int]:
    cost = 0
    for index in order:
        cost += TIERS[index].cost
        if row[index].score >= threshold:
            return index, cost
    return None, cost

The denominator choices are encoded directly in the measurements. measure is pure when rows, order, and threshold are fixed. That lets us compare policies on an identical workload and keep the scoring model unchanged across comparisons.

PythonIn [11]
CollapseExpand
@dataclass(frozen=True)
class Benchmark:
    coverage: float
    answered_accuracy: float | None
    correct_fraction: float
    mean_cost: float


def measure(
    rows: tuple[tuple[Candidate, ...], ...],
    order: tuple[int, ...],
    threshold: float,
) -> Benchmark:
    if not rows:
        raise ValueError("measurement requires at least one request")
    answered = correct = total_cost = 0
    for row in rows:
        index, cost = choose(row, order, threshold)
        total_cost += cost
        if index is not None:
            answered += 1
            correct += row[index].correct
    n = len(rows)
    return Benchmark(
        answered / n,
        correct / answered if answered else None,
        correct / n,
        total_cost / n,
    )
PythonIn [12]
CollapseExpand
comparison = {
    "Small only": measure(rows, (0,), 0.0),
    "Gated cascade": measure(rows, (0, 1, 2), 0.65),
    "Large only": measure(rows, (2,), 0.0),
}
PythonIn [13]
CollapseExpand
def format_benchmark(name: str, metric: Benchmark) -> str:
    answered = (
        "undefined"
        if metric.answered_accuracy is None
        else f"{metric.answered_accuracy:.1%}"
    )
    return (
        f"{name:14} coverage={metric.coverage:.1%}, answered accuracy={answered}, "
        f"correct per request={metric.correct_fraction:.1%}, "
        f"mean cost={metric.mean_cost:.2f} credits"
    )


for name, metric in comparison.items():
    print(format_benchmark(name, metric))
ConsoleOut [13]
CollapseExpand
Small only     coverage=100.0%, answered accuracy=62.7%, correct per request=62.7%, mean cost=1.00 credits
Gated cascade  coverage=96.1%, answered accuracy=96.4%, correct per request=92.7%, mean cost=4.84 credits
Large only     coverage=100.0%, answered accuracy=87.8%, correct per request=87.8%, mean cost=12.00 credits

Here, the gated cascade answers fewer requests than large-only but returns more correct answers per request. It also spends fewer synthetic credits. The simulator builds an informative score from the correctness label, so this comparison shows how that score shapes selection on these fixtures. An abstention is excluded from answered accuracy, but remains in the denominator of correct answers per request. Whether that trade is acceptable depends on the cost of returning an incorrect answer and what happens after an abstention.

Reading the policy comparison

The left panel reports coverage and correct answers per request on the same denominator. The right panel reports mean cost in synthetic credits per request. The two views use the same request rows, so the differences come from replaying different selection rules on those rows.

PythonIn [14]
CollapseExpand
plot_names = tuple(comparison)
plot_coverage = tuple(comparison[name].coverage for name in plot_names)
plot_correct = tuple(comparison[name].correct_fraction for name in plot_names)
plot_cost = tuple(comparison[name].mean_cost for name in plot_names)
VisualizationOut [15]
CollapseExpand
Side-by-side bar charts for small only, gated cascade, and large only. The left compares answer coverage and correct answers per request. The right compares mean synthetic credits.
On fixed synthetic requests, the gated cascade answers fewer requests than either single-tier baseline and costs fewer credits per request than always using the large tier. The left panel counts answered and correctly answered cases over all requests.

Choosing a threshold

The next cell sweeps a different synthetic sample for development. The comparison above keeps its predefined threshold. When you tune a real gate, select a policy on validation data and report outcomes on separate data. Evaluate coverage and errors by request type where the cost of bad answers varies.

Holding the candidate rows and tier order fixed, increasing the threshold never causes an earlier acceptance. Coverage is nonincreasing, and mean cost is nondecreasing for these positive fixed per-attempt costs. Accuracy on the answers that survive can go either way. A stricter gate changes both the set of answered requests and which tier answers them.

PythonIn [16]
CollapseExpand
development_rows = make_rows(seed=12, count=800)
sweep = [
    (threshold, measure(development_rows, (0, 1, 2), threshold))
    for threshold in (0.40, 0.55, 0.65, 0.75, 0.90)
]
for threshold, metric in sweep:
    print(
        f"{threshold:.2f}: coverage={metric.coverage:.1%}, "
        f"mean cost={metric.mean_cost:.2f} credits"
    )
assert all(
    a.coverage >= b.coverage and a.mean_cost <= b.mean_cost
    for (_, a), (_, b) in zip(sweep, sweep[1:])
)
ConsoleOut [16]
CollapseExpand
0.40: coverage=100.0%, mean cost=1.95 credits
0.55: coverage=99.9%, mean cost=2.71 credits
0.65: coverage=96.1%, mean cost=4.75 credits
0.75: coverage=85.4%, mean cost=7.25 credits
0.90: coverage=59.0%, mean cost=11.23 credits

A two-axis decision can conceal where the price of additional attempts is paid. The development sweep prints separate columns for service coverage and mean cost. The following plot adds conditional accuracy as a third curve on the same percentage panel as coverage, while keeping currency-free cost in its own panel. Look for points where a policy serves fewer requests despite spending more. That pattern can occur when a higher threshold produces rejections after earlier tiers have already run.

PythonIn [17]
CollapseExpand
sweep_threshold = tuple(threshold for threshold, _ in sweep)
sweep_coverage = tuple(metric.coverage for _, metric in sweep)
sweep_accuracy = tuple(metric.answered_accuracy for _, metric in sweep)
sweep_cost = tuple(metric.mean_cost for _, metric in sweep)
VisualizationOut [18]
CollapseExpand
Threshold sweep with coverage and answered accuracy at left and cost at right.
On the development rows, raising the gate threshold lowers coverage and increases attempt cost. Accuracy is conditional on requests answered at each threshold.

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!

Newsletter

Stay up to date

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

Unsubscribe at any time. Privacy policy