Pidoku

Cascades and Fallbacks

Module 21 Lesson 21.k 1h Difficulty 3/5

Prerequisites 21.g, 21.i, 23.c, 23.e


Before you start: words you need#

WordPlain meaning
CascadeSending each request to a cheap model first and escalating to an expensive one only when needed. A cost tool.
FallbackUsing an alternative (another replica, region, model or provider) when the normal path fails or is full. An availability tool.
Escalation rateThe share of requests that end up on the expensive model.
Model routerA component that picks a model per request, by rules or by a trained classifier. Not the replica router of 21.g.
CeilingThe share of requests the cheap model could answer acceptably, measured by running both models on a sample.
Degraded responseAn answer from a fallback that is worse than what the client asked for (a smaller model, for example).

1. What is it?#

Two mechanisms that use the same machinery and are often confused:

CASCADE     try a cheap model first; escalate to an expensive one only when needed
            → saves COST; must not lose quality

FALLBACK    when the primary path fails or is overloaded, use an alternative
            → protects AVAILABILITY; may accept lower quality, for a while

A cascade runs all the time and is judged on cost per acceptable answer. A fallback runs only when something is wrong and is judged on how many requests it saves from an error. Build both; know which one you are building, and measure each against its own goal.

Facts checked on 13 November 2026.


2. Why does it matter?#

Most queries are easy. “What is the capital of France?” does not need the largest model. If 65% of queries can be answered correctly by a model that costs a tenth as much:

cost = 0.65 × 0.1 + 0.35 × 1.0 = 0.415 × the cost of using the large model for everything

That is a 58% saving, if the routing decision is right. A cascade that escalates 80% of queries saves little; one that sends hard queries to the small model saves money by giving wrong answers.

Outages are certain. A replica crashes, a region degrades, a pool saturates. Without a fallback ladder every one of those becomes errors for users. With one, most become slightly slower or slightly worse answers.


3. Simple analogy#

A hospital. A cascade is triage: a nurse sees everyone first and sends only the hard cases to the specialist, which is cheap if the nurse’s judgement is good and dangerous if it is not. A fallback is the plan for when the specialist is off sick: a colleague from the next ward, then the hospital across town, and, if nothing else, an honest “come back tomorrow” rather than an endless wait.


4. Tiny example: what a cascade really saves#

Section 6 simulates 200,000 queries with a hidden difficulty. The small model is right on the easiest 65%, the large one on the easiest 95%; the small one costs 0.1:

always large                       cost 1.00   correct 95.0%   to large 100.0%
always small                       cost 0.10   correct 65.1%   to large  0.0%
perfect router (the ceiling)       cost 0.41   correct 95.0%   to large 34.9%
noisy router, threshold 0.65       cost 0.42   correct 89.3%   to large 35.1%
noisy router, threshold 0.45       cost 0.59   correct 94.4%   to large 54.9%
generate then check                cost 0.46   correct 90.5%   to large 36.2%
  • A real router is noisy. Set at the “obvious” threshold, it saves 58% and loses 5.7 points of accuracy. Shift the threshold towards the large model and it keeps almost all the quality (94.4%) while still saving 41%.
  • Generate-then-check pays for both models on every escalated query, and its checker misses some wrong answers.

5. Technical explanation#

Four ways to decide whether to escalate#

1. HEURISTICS (start here)
   prompt length, presence of code, task type known from the system prompt or the endpoint,
   tenant tier
   ✓ trivial, transparent, debuggable   ✗ coarse

2. ROUTE UP FRONT (a classifier decides before generating)
   a small model scores each query; below a threshold → small model
   ✓ no wasted generation, no extra latency   ✗ needs labelled data; wrong in both directions
   examples: RouteLLM (trained on preference data), vLLM Semantic Router (signals plus
   small classifier models, v0.4.0 September 2026), commercial routers

3. GENERATE, THEN CHECK
   the small model answers; a check (a verifier model, a test suite, a schema, a judge)
   decides whether to escalate
   ✓ judges the actual answer   ✗ escalated queries pay both costs and both latencies

4. CONFIDENCE
   the small model's own token log-probabilities or entropy
   ✓ free   ✗ poorly calibrated: a confident wrong answer looks confident
   → validate on your task before trusting it

Strategy 3 is strongest when a cheap, reliable check exists: code that must pass tests, output that must parse against a schema, an answer that must cite a retrieved document. Without one it is usually the most expensive way to route.

Go
// Heuristics first, in order of confidence; default to the large model.
func chooseModel(r *Request) string {
	switch {
	case r.Tenant.Tier == "premium":
		return "large"
	case len(r.TokenIDs) > 8000:
		return "large" // long context: likely complex
	case knownSimpleTask[r.Endpoint]: // classification, extraction, short Q&A endpoints
		return "small"
	}
	return "large"
}

Default to the large model and route down when confident. A cascade that defaults small and escalates on failure loses quality on every query it misjudges.

Measuring a cascade#

THE CEILING     run BOTH models on a sample of real queries (a few hundred to a few thousand);
                have a judge (people, or an LLM judge checked against people) mark which
                small-model answers are acceptable → the share that COULD go small
ROUTING ACCURACY how often the router sent a query small when small was acceptable,
                 and large when it was needed
COST            actual cost per request, from usage records (23.c)
QUALITY         per path AND for the mix, weighted by the real routing split
LATENCY         especially for escalated queries under strategy 3

Without the ceiling you cannot tell a good cascade from a quality regression that happens to be cheaper. It is the same discipline as validating quantization (13.b).

Escalation-rate drift#

A cascade’s quality depends on the router staying right as traffic changes. In section 6, a product change brings queries the classifier thinks are easier than they are: the escalation rate falls from 55% to 35%, cost falls, and accuracy drops from 94.4% to 89.2%. Nothing errors and the bill goes down. Alert on the escalation rate moving in either direction, and re-measure quality on a sample every week.

The fallback ladder#

1. RETRY ON ANOTHER REPLICA        same model, same quality
                                   (the Inference Extension lets the endpoint picker name
                                   a fallback endpoint for exactly this; 21.i)
2. ANOTHER REGION                  same model, more latency (23.f)
3. A SMALLER MODEL                 lower quality, but an answer
4. AN EXTERNAL PROVIDER            costly, and data leaves your infrastructure:
                                   needs a contract and a data decision IN ADVANCE
5. FAIL HONESTLY                   503 with Retry-After, not a timeout

AI gateways implement much of this as configuration: provider and model fallbacks, retries with backoff and circuit breakers exist in LiteLLM, Agent Router and SGLang Model Gateway, for example. What the gateway cannot decide for you is which errors deserve a fallback:

Go
func generateWithFallback(ctx context.Context, r *Request) (*Result, error) {
	for _, step := range fallbackChain {
		if !step.Enabled || !step.AllowedFor(r.Tenant) {
			continue
		}
		sctx, cancel := context.WithTimeout(ctx, step.Timeout)
		res, err := step.Execute(sctx, r)
		cancel()
		switch {
		case err == nil:
			if step.Degraded {
				res.Header.Set("X-Degraded", step.Name) // tell the client (see below)
			}
			return res, nil
		case errors.Is(err, ErrInvalidRequest):
			return nil, err // a client error fails everywhere: never fall back on it
		case errors.Is(err, ErrSaturated), errors.Is(err, ErrUnavailable),
			errors.Is(err, context.DeadlineExceeded):
			continue // a capacity or availability problem: try the next step
		default:
			return nil, err
		}
	}
	return nil, &ServiceUnavailable{RetryAfter: 30 * time.Second}
}

Never fall back on client errors. A malformed or over-long request fails at every step, consuming capacity at each one.

Telling the client#

Include the truth in response metadata, not as an error: X-Model-Served: chat-small-v2 when the client asked for chat-large, X-Degraded: capacity. Most clients will not look; those that care can act. If a tenant pays for a specific model, silently serving another is a contract problem, not just a technical one. Decide the policy per tenant and write it down.


6. Under the hood: simulating a cascade#

Go
// cascade.go — what do a router-up-front and a generate-then-check cascade really save,
// and what do they cost in quality? Each query has a hidden difficulty d in [0,1):
// the small model answers it correctly if d < 0.65, the large one if d < 0.95.
package main

import (
	"fmt"
	"math/rand/v2"
)

const (
	costSmall, costLarge = 0.1, 1.0 // relative cost per query
	smallLimit           = 0.65     // small model is right below this difficulty
	largeLimit           = 0.95     // large model is right below this difficulty
	queries              = 200000
)

type result struct{ cost, correct, escalated float64 }

func (r result) print(name string) {
	n := float64(queries)
	fmt.Printf("%-34s cost %4.2f   correct %4.1f%%   to large %4.1f%%\n",
		name, r.cost/n, 100*r.correct/n, 100*r.escalated/n)
}

func right(d, limit float64) float64 {
	if d < limit {
		return 1
	}
	return 0
}

// routeUpFront: a classifier estimates difficulty (with noise and a bias);
// below the threshold → small model, otherwise → large model.
func routeUpFront(diffs []float64, noise, bias, threshold float64, rng *rand.Rand) result {
	var r result
	for _, d := range diffs {
		est := d + bias + rng.NormFloat64()*noise
		if est < threshold {
			r.cost += costSmall
			r.correct += right(d, smallLimit)
		} else {
			r.cost += costLarge
			r.correct += right(d, largeLimit)
			r.escalated++
		}
	}
	return r
}

// generateThenCheck: the small model always answers; a checker flags a wrong answer with
// probability recall, and a right one with probability falseAlarm; flagged → the large model too.
func generateThenCheck(diffs []float64, recall, falseAlarm float64, rng *rand.Rand) result {
	var r result
	for _, d := range diffs {
		r.cost += costSmall
		ok := d < smallLimit
		flag := (!ok && rng.Float64() < recall) || (ok && rng.Float64() < falseAlarm)
		if flag {
			r.cost += costLarge // escalated queries pay for both models
			r.correct += right(d, largeLimit)
			r.escalated++
		} else {
			r.correct += right(d, smallLimit)
		}
	}
	return r
}

func traffic(rng *rand.Rand) []float64 {
	diffs := make([]float64, queries)
	for i := range diffs {
		diffs[i] = rng.Float64()
	}
	return diffs
}

func main() {
	rng := rand.New(rand.NewPCG(5, 8))
	diffs := traffic(rng)

	routeUpFront(diffs, 0, 0, -1, rng).print("always large")
	routeUpFront(diffs, 0, 0, 2, rng).print("always small")
	routeUpFront(diffs, 0, 0, smallLimit, rng).print("perfect router (the ceiling)")
	routeUpFront(diffs, 0.15, 0, 0.65, rng).print("noisy router, threshold 0.65")
	routeUpFront(diffs, 0.15, 0, 0.45, rng).print("noisy router, threshold 0.45")
	generateThenCheck(diffs, 0.85, 0.10, rng).print("generate then check")

	fmt.Println("\na product change: new queries the classifier finds 0.2 easier than they are")
	routeUpFront(diffs, 0.15, -0.2, 0.45, rng).print("noisy router, threshold 0.45")
}

Output:

always large                       cost 1.00   correct 95.0%   to large 100.0%
always small                       cost 0.10   correct 65.1%   to large  0.0%
perfect router (the ceiling)       cost 0.41   correct 95.0%   to large 34.9%
noisy router, threshold 0.65       cost 0.42   correct 89.3%   to large 35.1%
noisy router, threshold 0.45       cost 0.59   correct 94.4%   to large 54.9%
generate then check                cost 0.46   correct 90.5%   to large 36.2%

a product change: new queries the classifier finds 0.2 easier than they are
noisy router, threshold 0.45       cost 0.42   correct 89.2%   to large 35.0%

The model is crude: real difficulty is not one number, and the two models do not fail on a neat line. The lessons survive: a noisy router needs its threshold biased towards quality; the ceiling bounds the saving; and a classifier that drifts makes the system cheaper and worse at the same time.


7. Performance implications#

  • Route-up-front adds the classifier’s latency (milliseconds for a small encoder model) to every request; generate-then-check adds the whole small-model generation to every escalated one.
  • Two models means two pools to size, keep warm and scale (21.e). A cascade that sends 35% of traffic to the large model still needs the large pool sized for its peak share, which moves when the escalation rate drifts.
  • Fallback traffic is a surge. When a region or pool fails, the next rung receives its traffic at once. Size it, or rate-limit the fallback, so one failure does not cause a second (23.e).

8. Production implications#

  • Start with heuristics and default to the larger model.
  • Measure the ceiling before building a classifier, and re-measure quality on a sample weekly.
  • Alert on escalation-rate drift in both directions.
  • Evaluate the cascade as a system, not each model alone; the quality SLO applies to the mix.
  • Keep cascades and fallbacks separate in code and in dashboards: one is about cost, the other about availability.
  • Never fall back on client errors.
  • Expose the served model in response metadata.
  • Decide the external-provider fallback in advance, including what data may leave.

9. Common mistakes#

  1. Cascading without measuring quality. A saving that is really a regression.
  2. Defaulting to the small model.
  3. Trusting model confidence without validating it on your task.
  4. Generate-then-check without counting the double cost of escalated queries.
  5. Falling back on client errors.
  6. Silent model substitution for a paying customer.
  7. No alert on escalation rate. Drift goes unnoticed while the bill looks good.
  8. A fallback rung sized for normal traffic that collapses under a failover surge.

10. Hands-on exercise#

  1. Run cascade.go. Sweep the threshold from 0.35 to 0.7. Plot cost against accuracy. Where would you set it if the quality SLO is 94%?
  2. Make the router better. Halve the noise. How much closer to the ceiling do you get? That is what better training data is worth.
  3. Make the checker cheaper. In generate-then-check, what recall and false-alarm rate does the checker need to beat the noisy router at threshold 0.45?
  4. Measure a real ceiling. Take 300 real queries, run a small and a large model on each, and judge which small answers are acceptable.
  5. Test the ladder. Implement the fallback chain against two local servers. Kill the first, then saturate it, then send a malformed request. Check that only the first two fall back.

11. Interview questions#

  1. What is the difference between a cascade and a fallback, and how do you judge each?
  2. What are the ways to decide whether to escalate, and when is each right?
  3. Why default to the large model?
  4. How do you measure whether a cascade is working? What is the ceiling?
  5. How can a cascade get cheaper and worse at the same time, and how would you catch it?
  6. Why must you never fall back on client errors?
  7. Should the client know it got a degraded response?

12. Further reading#

Checked on 13 November 2026.

↑↓ navigate↵ openesc close

100% drag to pan · scroll or pinch to zoom · double-click to zoom in