[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M757MM778D96E3VBA2BZA9N0":3,"skill-same:01M757MM778D96E3VBA2BZA9N0":52},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":9,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":15,"categories":16,"keywords":17,"publishedAt":18,"linkOnly":19,"markdownContent":20,"markdownBody":21,"frontMatter":22,"refName":28,"commitSha":29,"skillDirectory":30,"forksCount":31,"repositoryHtmlUrl":32,"repositoryHomepageUrl":33,"ownerHtmlUrl":34,"ownerBlogUrl":35,"ownerDescription":36,"updatedAt":37,"install":38,"resources":51},"01M757MM778D96E3VBA2BZA9N0","model-routing-and-fallback",null,"Reference-grade guide to routing LLM requests across models by cost\u002Flatency\u002Fquality, escalating hard tasks, and surviving provider failures with multi-provider fallback, circuit breakers, hedging, and honest degraded-mode UX. Use when choosing which model serves a request, building a router\u002Fcascade, adding fallback for outages\u002Fratelimits\u002Ftimeouts, or designing what the user sees when you degrade.","jpoindexter\u002FVanta","jpoindexter","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F2729617?v=4","01M72VRRYY1CP7RPF3B7GHH0CR","01M757GWDBT6RD147ZZ79N4MEX",4,"MIT","https:\u002F\u002Fgithub.com\u002Fjpoindexter\u002FVanta\u002Fblob\u002Fmain\u002Fai-engineering-skills\u002Fmodel-routing-and-fallback\u002FSKILL.md",[],[],"2026-11-12 13:55:43",false,"---\nname: model-routing-and-fallback\ndescription: Reference-grade guide to routing LLM requests across models by cost\u002Flatency\u002Fquality, escalating hard tasks, and surviving provider failures with multi-provider fallback, circuit breakers, hedging, and honest degraded-mode UX. Use when choosing which model serves a request, building a router\u002Fcascade, adding fallback for outages\u002Fratelimits\u002Ftimeouts, or designing what the user sees when you degrade.\ntags: [ai-engineering, routing, fallback, reliability]\n---\n\n# Model Routing, Fallback & Degraded Mode\n\nTwo problems share this skill. **Routing** = picking the cheapest model that still meets the quality\nbar for *this* request (a value decision). **Fallback** = surviving when the chosen model is\nunavailable (a reliability decision). Build both — routing without fallback is a single point of\nfailure; fallback without routing burns money on easy work.\n\nTiers, not model IDs, are the durable unit: **frontier** (most capable, slowest, ~10–30× cost),\n**mid** (workhorse), **small** (fast, cheap, weak). Names shift quarterly; the tier logic does not.\n\n---\n\n## 1. Why route — don't send everything to the frontier model\n\nThe frontier model is the wrong default. ~70–90% of production traffic is easy (classification,\nextraction, short rewrites, routine Q&A) and a small model handles it at a fraction of the cost and\nlatency. Routing trades three axes:\n\n| Axis | Frontier tier | Mid tier | Small tier |\n|---|---|---|---|\n| Cost \u002F 1M tok | $$$ (10–60×) | $$ (3–8×) | $ (1×) |\n| Latency (p50 TTFT) | high | medium | low |\n| Quality ceiling | highest | good | adequate-on-easy |\n| Best for | reasoning, ambiguity, long-horizon agents | most tasks | classify, extract, format |\n\nThe win is asymmetric: routing 80% of easy traffic to a small model can cut spend 60–80% with near-\nzero quality delta — *if* you escalate the hard 20% correctly. The risk is asymmetric too: route a\nhard task to a weak model and the failure is silent (a confident wrong answer), worse than a catchable\nerror.\n\n**Do** measure your difficulty distribution before picking a default tier. **Don't** pick by gut —\n\"use the best model\" is a budget decision in disguise.\n\n---\n\n## 2. Routing strategies\n\n### Task-kind \u002F complexity routing (start here)\nMap known task types to tiers with a static table. Highest ROI, zero added latency, fully debuggable.\n\n```\nROUTE_TABLE = {\n  \"classify\":        small,\n  \"extract\":         small,\n  \"summarize_short\": small,\n  \"rewrite\":         mid,\n  \"rag_answer\":      mid,\n  \"code_gen\":        mid,\n  \"multi_step_plan\": frontier,\n  \"ambiguous\":       frontier,\n}\ndef route(task_kind, signals):\n    tier = ROUTE_TABLE.get(task_kind, mid)         # safe default = mid, never small\n    if signals.input_tokens > LONG_CTX_THRESHOLD:  # capability override (§ below)\n        tier = max(tier, mid)\n    return tier\n```\n\n### Difficulty estimation\nWhen task-kind is unknown, estimate difficulty from cheap signals *before* the expensive call: input\nlength, question-word count, code\u002Fmath presence, retrieval-score spread, constraint count,\nconversation depth. Combine into a 0–1 score; threshold into tiers. Keep it a few features — an\nover-fit difficulty model is its own maintenance burden.\n\n### Classifier \u002F router model\nA tiny model (or embedding + logistic head) reads the request and outputs a tier label. More accurate\nthan heuristics on messy input; adds one cheap hop of latency. Train on labeled\n(request → tier-that-succeeded) pairs from your own traffic.\n\n### Cascade (try cheap → verify → escalate on low confidence)\nRun the small model first; accept if a verifier passes, else escalate. Pays the cheap cost on the easy\nmajority, the full cost only on the hard minority. **The verifier is the whole game** — a weak one\npasses bad cheap answers (silent degradation); a paranoid one escalates everything (cascade *plus*\nfrontier cost).\n\n```\ndef cascade(request):\n    cheap = small.run(request)\n    if verify(cheap, request) >= CONF_THRESHOLD:   # self-grade, logprob, judge, or schema check\n        return cheap, {\"tier\": \"small\", \"escalated\": False}\n    strong = frontier.run(request)                 # bounded: ONE escalation, not a ladder to infinity\n    return strong, {\"tier\": \"frontier\", \"escalated\": True}\n```\n\n### LLM-as-router vs heuristic vs learned\n| Approach | Accuracy | Latency cost | Maintenance | Use when |\n|---|---|---|---|---|\n| Heuristic (rules\u002Ftable) | medium | none | low | known task types, hot path |\n| LLM-as-router | high | +1 call | low | varied\u002Funstructured input |\n| Learned (RouteLLM-style) | highest | tiny (classifier) | high (needs labeled data + retrain) | high volume, stable distribution, cost-critical |\n\n**RouteLLM** trains a binary router on preference data to send each query strong-or-weak at a target\nstrong-call rate, recovering most frontier quality while routing a large share to the cheap model.\nStart heuristic; graduate to learned when volume justifies the labeling pipeline.\n\n### Capability-based routing (a gate, not a preference)\nSome requests *require* a capability — route to a model that has it regardless of cost:\n- **Vision** → a multimodal model (text-only model can't see the image).\n- **Long context** → a long-context model when input exceeds others' windows.\n- **Tool\u002Ffunction calling** → a model with reliable structured tool use.\n- **Strict JSON \u002F schema** → a model supporting constrained decoding or JSON mode.\n\nThis intersects the capability matrix (§6): never route to a model that lacks the required\ncapability or that silently ignores the param you depend on.\n\n### Cost-aware and latency-aware routing\n- **Cost-aware:** track $\u002Frequest per route; enforce a per-tenant\u002Frequest budget cap; downgrade a tier\n  when a budget threshold is hit (with a degraded-mode signal, §5).\n- **Latency-aware:** under a tight SLA (interactive UI, voice), bias toward the lower-latency tier even\n  at some quality cost; reserve the slow frontier tier for async\u002Fbatch work. **Don't** optimize one\n  axis blind: cheapest-always tanks quality; fastest-always overpays.\n\n---\n\n## 3. Escalation\n\nEscalation = routing *up* a tier after a first attempt gave evidence it was insufficient. Escalate on:\n\n| Trigger | Signal |\n|---|---|\n| Low confidence | verifier\u002Fjudge score below threshold, low token logprobs, model hedging (\"I'm not sure\") |\n| Validation failure | output fails schema\u002FZod parse, fails tests, fails a business rule |\n| Refusal \u002F safety stop | model refused a legitimate task, or truncated |\n| Retrieval gap | RAG context thin or off-topic, model says \"not in the provided context\" |\n| Empty \u002F degenerate | blank, repetition loop, wrong language, wrong format |\n\n**Bounded escalation is non-negotiable.** Cap escalations per request (typically **one**: small →\nfrontier, stop). An unbounded ladder retries forever, multiplies cost, and stacks latency. After the\ncap, return the best attempt with a degraded-mode signal (§5) — don't loop.\n\n```\ndef with_escalation(request, max_escalations=1):\n    tier, escalations = small, 0\n    while True:\n        out = tier.run(request)\n        if accept(out) or escalations >= max_escalations:\n            return out, {\"escalations\": escalations, \"final_tier\": tier.name}\n        tier = next_tier_up(tier); escalations += 1   # bounded: terminates\n```\n\n**Do** log every escalation with its trigger — escalation rate is a routing-quality KPI (§6). **Don't**\nescalate on transient infra errors (timeout, 5xx); that's a *fallback* concern (§4), not a difficulty\nsignal — escalating a tier won't fix a network blip.\n\n---\n\n## 4. Graceful fallback for failures\n\nFailures are operational, not quality: outage, 429 rate limit, timeout, 5xx, connection reset, region\ndown. Classify the error, then act — they don't all warrant the same response.\n\n| Error class | Retryable? | Action |\n|---|---|---|\n| 429 rate limit | yes, after `Retry-After`\u002Fbackoff | backoff+jitter, then fall over to next provider |\n| 500\u002F502\u002F503 | yes, bounded | retry once, then fall over |\n| Timeout | maybe | respect timeout budget; hedge or fall over, don't blind-retry |\n| 400 \u002F invalid request | **no** | fix the request (e.g. unsupported param, §6); retrying repeats the error |\n| 401\u002F403 auth | **no** | alert; never retry a bad key |\n| Content filter | **no** | surface to user; not a model-availability problem |\n\n### Retry with backoff + jitter\nRetry only retryable classes. Exponential backoff with **full jitter** spreads retries so a recovering\nprovider isn't hammered by a synchronized herd. Cap attempts (2–3).\n\n```\ndef backoff_delay(attempt, base=0.5, cap=8.0):\n    return random.uniform(0, min(cap, base * 2 ** attempt))   # full jitter\n```\n\n### Multi-provider abstraction (prerequisite for fallback)\nFallback requires a uniform interface so the caller doesn't know which provider answered. Normalize\nrequest and response shapes; map each provider's params\u002Ferrors to a common vocabulary.\n\n```\nclass Provider(Protocol):\n    def run(self, req: ChatRequest, timeout: float) -> ChatResponse: ...\n    capabilities: Capabilities      # drives the capability matrix (§6)\n```\n\n### Fallback ORDER\nOrder is policy, not an afterthought. Default: same-quality alternate first (preserve UX), cheaper\u002F\nweaker last (preserve availability).\n\n```\nFALLBACK_ORDER = [\n    primary_frontier,         # 1. intended quality\n    alt_provider_frontier,    # 2. same tier, different provider — best UX preservation\n    same_provider_mid,        # 3. degrade tier, same vendor\n    alt_provider_mid,         # 4. degrade tier + vendor\n    cached_or_static,         # 5. last resort — never fail hard (§5)\n]\n```\nSkip any candidate that fails the request's **capability gate** (a vision request on a text-only model\n\"succeeds\" blind). Stop at the first success; emit a degraded signal if the answering tier is below\nintended.\n\n### Circuit breaker\nDon't retry into a provider you know is down — that wastes the timeout budget on every request. Per\nprovider: **closed** (normal) → **open** after N consecutive failures (fail fast, skip straight to\nfallback) → **half-open** after a cooldown (one probe; success closes it, failure re-opens).\n\n```\nclass Breaker:\n    state, fails = \"closed\", 0\n    def allow(self): return self.state != \"open\" or self.cooled_down()\n    def record(self, ok):\n        if ok: self.state, self.fails = \"closed\", 0\n        else:\n            self.fails += 1\n            if self.fails >= THRESHOLD: self.state = \"open\"; self.opened_at = now()\n```\n\n### Hedged requests\nTail-latency-sensitive paths: if the primary hasn't responded by p95, fire a second request to an\nalternate, take whichever returns first, cancel the loser. Cuts tail latency at the cost of duplicate\nspend — cap the hedge rate (e.g. ≤5%) so a slow provider doesn't double your bill.\n\n### Timeout budgets\nSet a **total** per-request budget and subtract elapsed time before each fallback hop; never let\nretries + fallbacks blow the user-facing deadline. A 30s budget allots 8s primary, 8s alternate, then\na cached\u002Fpartial response — not three sequential 30s waits totaling 90s.\n\n---\n\n## 5. Degraded-mode UX — never fail hard, never lie\n\nWhen you fall back or downgrade, the user is getting something different from the ideal. The cardinal\nrule: **degrade honestly — never silently, never to a hard error.**\n\n| Degradation | What the user sees |\n|---|---|\n| Fell to slower\u002Fcheaper model | answer + subtle \"responding in limited mode\" note if quality may differ |\n| Served cached answer | answer + \"showing a recent result\" \u002F timestamp |\n| Partial result | what completed + \"couldn't finish X\" + retry affordance |\n| Feature flagged off | the capability hidden\u002Fdisabled, not a crash |\n| Fully unavailable | graceful message + ETA\u002Fretry, queue position if queued |\n\n- **Honest vs silent:** silently serving a weak model as if it were the frontier one is the most\n  dangerous failure mode — users trust a wrong answer they can't tell is degraded. Surface it, subtly.\n- **Don't over-apologize either:** a banner on every minor fallback trains users to ignore it. Signal\n  proportionally — quiet note for a same-tier provider swap, explicit banner for a real quality drop.\n- **Feature-flag down:** under load or partial outage, disable the most expensive optional features\n  (e.g. agentic multi-step, long-context summarization) and keep the core path alive.\n- **Queue \u002F backpressure:** when capacity is exhausted, queue with a visible position\u002FETA or shed load\n  with a clear \"try again shortly\" — bounded waiting beats an opaque hang or a 500.\n- **Never-fail-hard:** the final fallback is always *something* — cached result, static response, or a\n  clear actionable error. A blank screen or stack trace is never acceptable.\n\n**Do:** make degraded mode a designed state with its own copy and telemetry.\n**Don't:** let degraded mode be \"whatever the exception handler happens to render.\"\n\n---\n\n## 6. Capability matrix & observability\n\nMaintain a per-model capability table so the router never sends an unsupported param — a top source of\nsilent 400s and ignored-parameter bugs:\n\n| Model (tier) | Vision | Tools | JSON mode | Max ctx | `temperature` | Notes |\n|---|---|---|---|---|---|---|\n| frontier-A | yes | yes | strict | 200k | yes | reasoning model may ignore `temperature` |\n| mid-B | no | yes | yes | 128k | yes | — |\n| small-C | no | partial | best-effort | 16k | yes | weak tool use; verify outputs |\n| vision-D | yes | no | no | 32k | yes | route images here |\n\nUse the matrix two ways: (1) **gate** capability-based routing\u002Ffallback (§2, §4); (2) **scrub** the\nrequest before sending — strip or translate params the target doesn't support, rather than let the\nprovider reject or silently ignore them.\n\n**Observability is the other half of routing** — covered fully in the observability\u002Fevals skill;\ncross-reference rather than duplicate. Route-specific signals to emit: chosen tier, escalation trigger\n+ rate, fallback rate per provider, circuit-breaker transitions, cost-per-request by route, latency by\ntier, degraded-mode served rate. You can't tune a router you can't see — a creeping fallback rate is\nyour earliest outage warning.\n\n---\n\n## 7. Cost \u002F quality \u002F latency per route — the tradeoff\n\nEvery route is a point in a 3-D tradeoff; make the tradeoff explicit per path:\n\n| Route | Cost | Quality | Latency | Fits |\n|---|---|---|---|---|\n| small-only | lowest | adequate-on-easy | lowest | bulk classify\u002Fextract, autocomplete |\n| cascade (small→frontier) | low avg | high (verifier-gated) | low avg, high tail | mixed-difficulty Q&A |\n| frontier-only | highest | highest | highest | reasoning, agents, ambiguity |\n| hedged frontier | high | highest | low tail | latency-critical premium path |\n| mid + capability override | medium | good | medium | general workhorse |\n\nPick per *task class*, not globally. The cascade's \"low average \u002F high tail\" is the classic trap:\ncheap on average but escalated requests are slow — fine for async, risky for a hard interactive SLA\n(prefer a latency-aware direct route there).\n\n---\n\n## 8. Failure modes\n\n- **No fallback → hard outage.** Single provider, no abstraction layer: their 30-minute incident is\n  *your* 30-minute incident. Fix: multi-provider abstraction + fallback order (§4).\n- **Silent quality degradation.** Falling to a weak model (or weak verifier in a cascade) without\n  surfacing it. Users trust confident wrong answers. Fix: degraded-mode signaling (§5) + escalation\n  triggers tuned on real failures (§3).\n- **Retry storm \u002F thundering herd.** Synchronized un-jittered retries hammer a recovering provider and\n  keep it down. Fix: backoff + **full jitter**, bounded attempts, circuit breakers (§4).\n- **Sending unsupported params.** Passing `tools`\u002F`temperature`\u002FJSON mode to a model that rejects or\n  silently ignores them → 400s or ignored constraints. Fix: capability matrix + request scrub (§6).\n- **Routing everything to the cheap model.** Cost-obsessed default tanks quality on the hard minority,\n  invisibly. Fix: measure difficulty distribution (§1), keep `mid` as the safe default, never `small`.\n- **Cascade that never escalates.** Verifier too lenient (or threshold too low) → bad cheap answers\n  pass; cost savings are real, quality loss is hidden. Mirror trap: verifier too strict → escalates\n  everything, paying cascade *plus* frontier. Fix: calibrate the verifier against labeled outcomes,\n  monitor escalation rate (§6).\n- **Unbounded escalation ladder.** Escalating on transient infra errors, or with no cap, loops cost and\n  latency upward. Fix: bound escalations (§3); route infra errors to fallback (§4), not escalation.\n","# Model Routing, Fallback & Degraded Mode\n\nTwo problems share this skill. **Routing** = picking the cheapest model that still meets the quality\nbar for *this* request (a value decision). **Fallback** = surviving when the chosen model is\nunavailable (a reliability decision). Build both — routing without fallback is a single point of\nfailure; fallback without routing burns money on easy work.\n\nTiers, not model IDs, are the durable unit: **frontier** (most capable, slowest, ~10–30× cost),\n**mid** (workhorse), **small** (fast, cheap, weak). Names shift quarterly; the tier logic does not.\n\n---\n\n## 1. Why route — don't send everything to the frontier model\n\nThe frontier model is the wrong default. ~70–90% of production traffic is easy (classification,\nextraction, short rewrites, routine Q&A) and a small model handles it at a fraction of the cost and\nlatency. Routing trades three axes:\n\n| Axis | Frontier tier | Mid tier | Small tier |\n|---|---|---|---|\n| Cost \u002F 1M tok | $$$ (10–60×) | $$ (3–8×) | $ (1×) |\n| Latency (p50 TTFT) | high | medium | low |\n| Quality ceiling | highest | good | adequate-on-easy |\n| Best for | reasoning, ambiguity, long-horizon agents | most tasks | classify, extract, format |\n\nThe win is asymmetric: routing 80% of easy traffic to a small model can cut spend 60–80% with near-\nzero quality delta — *if* you escalate the hard 20% correctly. The risk is asymmetric too: route a\nhard task to a weak model and the failure is silent (a confident wrong answer), worse than a catchable\nerror.\n\n**Do** measure your difficulty distribution before picking a default tier. **Don't** pick by gut —\n\"use the best model\" is a budget decision in disguise.\n\n---\n\n## 2. Routing strategies\n\n### Task-kind \u002F complexity routing (start here)\nMap known task types to tiers with a static table. Highest ROI, zero added latency, fully debuggable.\n\n```\nROUTE_TABLE = {\n  \"classify\":        small,\n  \"extract\":         small,\n  \"summarize_short\": small,\n  \"rewrite\":         mid,\n  \"rag_answer\":      mid,\n  \"code_gen\":        mid,\n  \"multi_step_plan\": frontier,\n  \"ambiguous\":       frontier,\n}\ndef route(task_kind, signals):\n    tier = ROUTE_TABLE.get(task_kind, mid)         # safe default = mid, never small\n    if signals.input_tokens > LONG_CTX_THRESHOLD:  # capability override (§ below)\n        tier = max(tier, mid)\n    return tier\n```\n\n### Difficulty estimation\nWhen task-kind is unknown, estimate difficulty from cheap signals *before* the expensive call: input\nlength, question-word count, code\u002Fmath presence, retrieval-score spread, constraint count,\nconversation depth. Combine into a 0–1 score; threshold into tiers. Keep it a few features — an\nover-fit difficulty model is its own maintenance burden.\n\n### Classifier \u002F router model\nA tiny model (or embedding + logistic head) reads the request and outputs a tier label. More accurate\nthan heuristics on messy input; adds one cheap hop of latency. Train on labeled\n(request → tier-that-succeeded) pairs from your own traffic.\n\n### Cascade (try cheap → verify → escalate on low confidence)\nRun the small model first; accept if a verifier passes, else escalate. Pays the cheap cost on the easy\nmajority, the full cost only on the hard minority. **The verifier is the whole game** — a weak one\npasses bad cheap answers (silent degradation); a paranoid one escalates everything (cascade *plus*\nfrontier cost).\n\n```\ndef cascade(request):\n    cheap = small.run(request)\n    if verify(cheap, request) >= CONF_THRESHOLD:   # self-grade, logprob, judge, or schema check\n        return cheap, {\"tier\": \"small\", \"escalated\": False}\n    strong = frontier.run(request)                 # bounded: ONE escalation, not a ladder to infinity\n    return strong, {\"tier\": \"frontier\", \"escalated\": True}\n```\n\n### LLM-as-router vs heuristic vs learned\n| Approach | Accuracy | Latency cost | Maintenance | Use when |\n|---|---|---|---|---|\n| Heuristic (rules\u002Ftable) | medium | none | low | known task types, hot path |\n| LLM-as-router | high | +1 call | low | varied\u002Funstructured input |\n| Learned (RouteLLM-style) | highest | tiny (classifier) | high (needs labeled data + retrain) | high volume, stable distribution, cost-critical |\n\n**RouteLLM** trains a binary router on preference data to send each query strong-or-weak at a target\nstrong-call rate, recovering most frontier quality while routing a large share to the cheap model.\nStart heuristic; graduate to learned when volume justifies the labeling pipeline.\n\n### Capability-based routing (a gate, not a preference)\nSome requests *require* a capability — route to a model that has it regardless of cost:\n- **Vision** → a multimodal model (text-only model can't see the image).\n- **Long context** → a long-context model when input exceeds others' windows.\n- **Tool\u002Ffunction calling** → a model with reliable structured tool use.\n- **Strict JSON \u002F schema** → a model supporting constrained decoding or JSON mode.\n\nThis intersects the capability matrix (§6): never route to a model that lacks the required\ncapability or that silently ignores the param you depend on.\n\n### Cost-aware and latency-aware routing\n- **Cost-aware:** track $\u002Frequest per route; enforce a per-tenant\u002Frequest budget cap; downgrade a tier\n  when a budget threshold is hit (with a degraded-mode signal, §5).\n- **Latency-aware:** under a tight SLA (interactive UI, voice), bias toward the lower-latency tier even\n  at some quality cost; reserve the slow frontier tier for async\u002Fbatch work. **Don't** optimize one\n  axis blind: cheapest-always tanks quality; fastest-always overpays.\n\n---\n\n## 3. Escalation\n\nEscalation = routing *up* a tier after a first attempt gave evidence it was insufficient. Escalate on:\n\n| Trigger | Signal |\n|---|---|\n| Low confidence | verifier\u002Fjudge score below threshold, low token logprobs, model hedging (\"I'm not sure\") |\n| Validation failure | output fails schema\u002FZod parse, fails tests, fails a business rule |\n| Refusal \u002F safety stop | model refused a legitimate task, or truncated |\n| Retrieval gap | RAG context thin or off-topic, model says \"not in the provided context\" |\n| Empty \u002F degenerate | blank, repetition loop, wrong language, wrong format |\n\n**Bounded escalation is non-negotiable.** Cap escalations per request (typically **one**: small →\nfrontier, stop). An unbounded ladder retries forever, multiplies cost, and stacks latency. After the\ncap, return the best attempt with a degraded-mode signal (§5) — don't loop.\n\n```\ndef with_escalation(request, max_escalations=1):\n    tier, escalations = small, 0\n    while True:\n        out = tier.run(request)\n        if accept(out) or escalations >= max_escalations:\n            return out, {\"escalations\": escalations, \"final_tier\": tier.name}\n        tier = next_tier_up(tier); escalations += 1   # bounded: terminates\n```\n\n**Do** log every escalation with its trigger — escalation rate is a routing-quality KPI (§6). **Don't**\nescalate on transient infra errors (timeout, 5xx); that's a *fallback* concern (§4), not a difficulty\nsignal — escalating a tier won't fix a network blip.\n\n---\n\n## 4. Graceful fallback for failures\n\nFailures are operational, not quality: outage, 429 rate limit, timeout, 5xx, connection reset, region\ndown. Classify the error, then act — they don't all warrant the same response.\n\n| Error class | Retryable? | Action |\n|---|---|---|\n| 429 rate limit | yes, after `Retry-After`\u002Fbackoff | backoff+jitter, then fall over to next provider |\n| 500\u002F502\u002F503 | yes, bounded | retry once, then fall over |\n| Timeout | maybe | respect timeout budget; hedge or fall over, don't blind-retry |\n| 400 \u002F invalid request | **no** | fix the request (e.g. unsupported param, §6); retrying repeats the error |\n| 401\u002F403 auth | **no** | alert; never retry a bad key |\n| Content filter | **no** | surface to user; not a model-availability problem |\n\n### Retry with backoff + jitter\nRetry only retryable classes. Exponential backoff with **full jitter** spreads retries so a recovering\nprovider isn't hammered by a synchronized herd. Cap attempts (2–3).\n\n```\ndef backoff_delay(attempt, base=0.5, cap=8.0):\n    return random.uniform(0, min(cap, base * 2 ** attempt))   # full jitter\n```\n\n### Multi-provider abstraction (prerequisite for fallback)\nFallback requires a uniform interface so the caller doesn't know which provider answered. Normalize\nrequest and response shapes; map each provider's params\u002Ferrors to a common vocabulary.\n\n```\nclass Provider(Protocol):\n    def run(self, req: ChatRequest, timeout: float) -> ChatResponse: ...\n    capabilities: Capabilities      # drives the capability matrix (§6)\n```\n\n### Fallback ORDER\nOrder is policy, not an afterthought. Default: same-quality alternate first (preserve UX), cheaper\u002F\nweaker last (preserve availability).\n\n```\nFALLBACK_ORDER = [\n    primary_frontier,         # 1. intended quality\n    alt_provider_frontier,    # 2. same tier, different provider — best UX preservation\n    same_provider_mid,        # 3. degrade tier, same vendor\n    alt_provider_mid,         # 4. degrade tier + vendor\n    cached_or_static,         # 5. last resort — never fail hard (§5)\n]\n```\nSkip any candidate that fails the request's **capability gate** (a vision request on a text-only model\n\"succeeds\" blind). Stop at the first success; emit a degraded signal if the answering tier is below\nintended.\n\n### Circuit breaker\nDon't retry into a provider you know is down — that wastes the timeout budget on every request. Per\nprovider: **closed** (normal) → **open** after N consecutive failures (fail fast, skip straight to\nfallback) → **half-open** after a cooldown (one probe; success closes it, failure re-opens).\n\n```\nclass Breaker:\n    state, fails = \"closed\", 0\n    def allow(self): return self.state != \"open\" or self.cooled_down()\n    def record(self, ok):\n        if ok: self.state, self.fails = \"closed\", 0\n        else:\n            self.fails += 1\n            if self.fails >= THRESHOLD: self.state = \"open\"; self.opened_at = now()\n```\n\n### Hedged requests\nTail-latency-sensitive paths: if the primary hasn't responded by p95, fire a second request to an\nalternate, take whichever returns first, cancel the loser. Cuts tail latency at the cost of duplicate\nspend — cap the hedge rate (e.g. ≤5%) so a slow provider doesn't double your bill.\n\n### Timeout budgets\nSet a **total** per-request budget and subtract elapsed time before each fallback hop; never let\nretries + fallbacks blow the user-facing deadline. A 30s budget allots 8s primary, 8s alternate, then\na cached\u002Fpartial response — not three sequential 30s waits totaling 90s.\n\n---\n\n## 5. Degraded-mode UX — never fail hard, never lie\n\nWhen you fall back or downgrade, the user is getting something different from the ideal. The cardinal\nrule: **degrade honestly — never silently, never to a hard error.**\n\n| Degradation | What the user sees |\n|---|---|\n| Fell to slower\u002Fcheaper model | answer + subtle \"responding in limited mode\" note if quality may differ |\n| Served cached answer | answer + \"showing a recent result\" \u002F timestamp |\n| Partial result | what completed + \"couldn't finish X\" + retry affordance |\n| Feature flagged off | the capability hidden\u002Fdisabled, not a crash |\n| Fully unavailable | graceful message + ETA\u002Fretry, queue position if queued |\n\n- **Honest vs silent:** silently serving a weak model as if it were the frontier one is the most\n  dangerous failure mode — users trust a wrong answer they can't tell is degraded. Surface it, subtly.\n- **Don't over-apologize either:** a banner on every minor fallback trains users to ignore it. Signal\n  proportionally — quiet note for a same-tier provider swap, explicit banner for a real quality drop.\n- **Feature-flag down:** under load or partial outage, disable the most expensive optional features\n  (e.g. agentic multi-step, long-context summarization) and keep the core path alive.\n- **Queue \u002F backpressure:** when capacity is exhausted, queue with a visible position\u002FETA or shed load\n  with a clear \"try again shortly\" — bounded waiting beats an opaque hang or a 500.\n- **Never-fail-hard:** the final fallback is always *something* — cached result, static response, or a\n  clear actionable error. A blank screen or stack trace is never acceptable.\n\n**Do:** make degraded mode a designed state with its own copy and telemetry.\n**Don't:** let degraded mode be \"whatever the exception handler happens to render.\"\n\n---\n\n## 6. Capability matrix & observability\n\nMaintain a per-model capability table so the router never sends an unsupported param — a top source of\nsilent 400s and ignored-parameter bugs:\n\n| Model (tier) | Vision | Tools | JSON mode | Max ctx | `temperature` | Notes |\n|---|---|---|---|---|---|---|\n| frontier-A | yes | yes | strict | 200k | yes | reasoning model may ignore `temperature` |\n| mid-B | no | yes | yes | 128k | yes | — |\n| small-C | no | partial | best-effort | 16k | yes | weak tool use; verify outputs |\n| vision-D | yes | no | no | 32k | yes | route images here |\n\nUse the matrix two ways: (1) **gate** capability-based routing\u002Ffallback (§2, §4); (2) **scrub** the\nrequest before sending — strip or translate params the target doesn't support, rather than let the\nprovider reject or silently ignore them.\n\n**Observability is the other half of routing** — covered fully in the observability\u002Fevals skill;\ncross-reference rather than duplicate. Route-specific signals to emit: chosen tier, escalation trigger\n+ rate, fallback rate per provider, circuit-breaker transitions, cost-per-request by route, latency by\ntier, degraded-mode served rate. You can't tune a router you can't see — a creeping fallback rate is\nyour earliest outage warning.\n\n---\n\n## 7. Cost \u002F quality \u002F latency per route — the tradeoff\n\nEvery route is a point in a 3-D tradeoff; make the tradeoff explicit per path:\n\n| Route | Cost | Quality | Latency | Fits |\n|---|---|---|---|---|\n| small-only | lowest | adequate-on-easy | lowest | bulk classify\u002Fextract, autocomplete |\n| cascade (small→frontier) | low avg | high (verifier-gated) | low avg, high tail | mixed-difficulty Q&A |\n| frontier-only | highest | highest | highest | reasoning, agents, ambiguity |\n| hedged frontier | high | highest | low tail | latency-critical premium path |\n| mid + capability override | medium | good | medium | general workhorse |\n\nPick per *task class*, not globally. The cascade's \"low average \u002F high tail\" is the classic trap:\ncheap on average but escalated requests are slow — fine for async, risky for a hard interactive SLA\n(prefer a latency-aware direct route there).\n\n---\n\n## 8. Failure modes\n\n- **No fallback → hard outage.** Single provider, no abstraction layer: their 30-minute incident is\n  *your* 30-minute incident. Fix: multi-provider abstraction + fallback order (§4).\n- **Silent quality degradation.** Falling to a weak model (or weak verifier in a cascade) without\n  surfacing it. Users trust confident wrong answers. Fix: degraded-mode signaling (§5) + escalation\n  triggers tuned on real failures (§3).\n- **Retry storm \u002F thundering herd.** Synchronized un-jittered retries hammer a recovering provider and\n  keep it down. Fix: backoff + **full jitter**, bounded attempts, circuit breakers (§4).\n- **Sending unsupported params.** Passing `tools`\u002F`temperature`\u002FJSON mode to a model that rejects or\n  silently ignores them → 400s or ignored constraints. Fix: capability matrix + request scrub (§6).\n- **Routing everything to the cheap model.** Cost-obsessed default tanks quality on the hard minority,\n  invisibly. Fix: measure difficulty distribution (§1), keep `mid` as the safe default, never `small`.\n- **Cascade that never escalates.** Verifier too lenient (or threshold too low) → bad cheap answers\n  pass; cost savings are real, quality loss is hidden. Mirror trap: verifier too strict → escalates\n  everything, paying cascade *plus* frontier. Fix: calibrate the verifier against labeled outcomes,\n  monitor escalation rate (§6).\n- **Unbounded escalation ladder.** Escalating on transient infra errors, or with no cap, loops cost and\n  latency upward. Fix: bound escalations (§3); route infra errors to fallback (§4), not escalation.\n",{"name":5,"tags":23,"description":7},[24,25,26,27],"ai-engineering","routing","fallback","reliability","main","4911ae44bbb35beef4511ba298475ba5a82b7e1c","ai-engineering-skills\u002Fmodel-routing-and-fallback",0,"https:\u002F\u002Fgithub.com\u002Fjpoindexter\u002FVanta","https:\u002F\u002Fdocs.vanta.theft.studio","https:\u002F\u002Fgithub.com\u002Fjpoindexter","jason.theft.studio","Just some guy trying to build stuff","2026-11-12 17:11:35",{"source":8,"skillName":5,"commands":39,"prompt":49,"zipAvailable":50},[40,43,46],{"tool":41,"command":42},"npx","npx skills add jpoindexter\u002FVanta --skill model-routing-and-fallback",{"tool":44,"command":45},"bunx","bunx skills add jpoindexter\u002FVanta --skill model-routing-and-fallback",{"tool":47,"command":48},"pnpm","pnpm dlx skills add jpoindexter\u002FVanta --skill model-routing-and-fallback","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fjpoindexter\u002FVanta\u002Fblob\u002Fmain\u002Fai-engineering-skills\u002Fmodel-routing-and-fallback\u002FSKILL.md",true,[],[53,60,67,74,81,87],{"skillNo":54,"name":55,"nameZh":6,"description":56,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":9,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":57,"categories":58,"keywords":59,"publishedAt":18},"01M7582PEM7XM8B98VFRDV0C0J","write-changelog","Turn a range of commits into a user-facing changelog","https:\u002F\u002Fgithub.com\u002Fjpoindexter\u002FVanta\u002Fblob\u002Fmain\u002Fvanta-ts\u002Fsrc\u002Fmigrate\u002F__fixtures__\u002Fopenclaw\u002Fskills\u002Fwrite-changelog\u002FSKILL.md",[],[],{"skillNo":61,"name":62,"nameZh":6,"description":63,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":9,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":64,"categories":65,"keywords":66,"publishedAt":18},"01M7582KTQJMP5Y7GS83MS1C7Z","debug-flaky-test","Reproduce and isolate a flaky test before fixing it","https:\u002F\u002Fgithub.com\u002Fjpoindexter\u002FVanta\u002Fblob\u002Fmain\u002Fvanta-ts\u002Fsrc\u002Fmigrate\u002F__fixtures__\u002Fopenclaw\u002Fskills\u002Fdebug-flaky-test\u002FSKILL.md",[],[],{"skillNo":68,"name":69,"nameZh":6,"description":70,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":9,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":71,"categories":72,"keywords":73,"publishedAt":18},"01M7582HG7XFM4Z5NGG1YFECT8","triage-incident","First 10 minutes of an incident — stabilize, then diagnose","https:\u002F\u002Fgithub.com\u002Fjpoindexter\u002FVanta\u002Fblob\u002Fmain\u002Fvanta-ts\u002Fsrc\u002Fmigrate\u002F__fixtures__\u002Fhermes\u002Fskills\u002Ftriage-incident\u002FSKILL.md",[],[],{"skillNo":75,"name":76,"nameZh":6,"description":77,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":9,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":78,"categories":79,"keywords":80,"publishedAt":18},"01M7582DQABK7A96XHMB770KQZ","writing-plans","Write implementation plans: bite-sized tasks, paths, code.","https:\u002F\u002Fgithub.com\u002Fjpoindexter\u002FVanta\u002Fblob\u002Fmain\u002Fvanta-ts\u002Fskills-library\u002Fwriting-plans\u002FSKILL.md",[],[],{"skillNo":82,"name":83,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":9,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":84,"categories":85,"keywords":86,"publishedAt":18},"01M7582BBK8H0HGSXKK08FCXJ1","vanta-port-adapter","https:\u002F\u002Fgithub.com\u002Fjpoindexter\u002FVanta\u002Fblob\u002Fmain\u002Fvanta-ts\u002Fskills-library\u002Fvanta-port-adapter\u002FSKILL.md",[],[],{"skillNo":88,"name":89,"nameZh":6,"description":90,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":9,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":91,"categories":92,"keywords":93,"publishedAt":18},"01M75828P8PX5XSBMJ2BVVDA9Y","test-driven-development","TDD: enforce RED-GREEN-REFACTOR, tests before code.","https:\u002F\u002Fgithub.com\u002Fjpoindexter\u002FVanta\u002Fblob\u002Fmain\u002Fvanta-ts\u002Fskills-library\u002Ftest-driven-development\u002FSKILL.md",[],[]]