By Abhijith N M · Reviewed 24 October 2026 · Editorial standards
The model-portability lesson split three decisions that people often blur: a retry uses the same model again because the error was transient, a fallback uses a different model because the provider is degraded, and a degrade uses no model at all. This lab makes the split concrete by simulating provider failures, then measuring what the customer sees in each case.
The fixture is a fake provider that raises a 503 for its first N calls. Two attempts go to the primary, then one call to a fallback, then a degraded hand-off. Every step is deterministic, so the scenario matrix can live in CI next to the ordinary unit tests.
The snippet runs three scenarios against the same agent wrapper: a single transient 503, a sustained provider outage, and every provider down. It prints the channel that answered, the user-visible message, and the fallback rate over the matrix.
"""Simulate provider failure and measure what the customer sees."""
class ProviderError(Exception):
def __init__(self, status):
super().__init__(f"provider error {status}")
self.status = status
class FakeProvider:
"""Deterministic stand-in: raises on its first `failures` calls."""
def __init__(self, name, failures=0):
self.name = name
self.failures = failures
self.calls = 0
def call(self):
self.calls += 1
if self.calls <= self.failures:
raise ProviderError(503)
return f"answer from {self.name}"
def answer(primary, fallback):
last = None
for attempt in range(1, 3):
try:
return f"attempt {attempt}: {primary.call()}", "primary"
except ProviderError as error:
last = error
try:
return f"fallback after {last.status}: {fallback.call()}", "fallback"
except ProviderError:
return "Sorry - a human will pick this up within one hour.", "degrade"
SCENARIOS = [
("one 503", FakeProvider("primary", failures=1), FakeProvider("fallback")),
(
"provider outage",
FakeProvider("primary", failures=9),
FakeProvider("fallback"),
),
(
"all providers down",
FakeProvider("primary", failures=9),
FakeProvider("fallback", failures=9),
),
]
fallbacks = 0
for label, primary, fallback in SCENARIOS:
message, channel = answer(primary, fallback)
fallbacks += channel == "fallback"
print(f"{label:>18} -> {channel:<8} | {message}")
print(
f"fallback rate over {len(SCENARIOS)} scenarios: "
f"{fallbacks / len(SCENARIOS):.2f}"
)The transient 503 costs one hidden retry and the customer never sees it. The sustained outage costs the primary's two attempts and then serves a fallback answer, which is a different model doing the work and should be labelled as such in the trace. When every provider is down the only honest outcome is a short apology and a hand-off - not a fabricated answer and not an unbounded retry loop.
The 0.33 fallback rate here is a property of the test matrix, not a production KPI. In production the same counter is how you notice a degraded provider: a fallback rate that creeps above a few percent means the primary is failing quietly and quality may have changed with it.
Classify the error before choosing a response. This table is the version to adapt in your own runbook; the important column is the last one, because a failure you cannot see on a dashboard becomes a surprise invoice or a duplicate write.
| Failure class | Retry same provider? | Fallback? | Degrade? | What the customer sees | Metric to watch |
|---|---|---|---|---|---|
| 429 rate limit | Yes, with backoff and jitter, inside the deadline | Yes, if the deadline allows | If both are exhausted | A slower reply, or a hand-off | 429 count and fallback rate |
| 500 or 503 outage | One bounded retry | Yes, on an independent provider | If the fallback also fails | A normal answer, labelled as fallback internally | Error rate and fallback rate |
| Timeout | Only if time remains in the request deadline | Yes, for the same logical call | Hand-off, never a second long wait | An apology with the request id | p95 latency and timeout rate |
| Auth or invalid request | No - a retry cannot fix it | No | Fail fast with a clean error | A clean 4xx or 503, not a retry loop | Configuration errors |
| Context overflow | No | No - trim the prompt or route the request | Clean error and a shorter prompt path | A short answer or a hand-off | Context-window errors |
| Write with unknown outcome | Never | Never on the write itself | Reconcile, then escalate to a human | A human resolves the duplicate risk | Duplicate-write count |
A failover design is only as good as the user-visible behaviour it produces. Count the outcomes, not just provider errors.
The serving lesson suggested a revoked key as the cheapest outage rehearsal; this lab adds the fallback assertion. Point staging at a revoked primary and confirm four things at once: the customer gets a clean answer or hand-off inside the deadline, the fallback actually carries the same tools and prompt, the health check stays green, and the trace names the failing provider.
Then add the fake provider to the keyless suite. A scripted failure that asserts the fallback answer, the degrade message and the fallback-rate counter is a regression test for the resilience code itself, and it runs on every pull request that touches the model wrapper.
Key takeaways
Classify failures before responding: retry is the same model, fallback is a different model, degrade is no model at all.
Bound retries with backoff inside the request deadline, and never retry a write whose outcome is unknown.
A fallback must carry the same tools, prompt and output contract; otherwise it is a silent quality downgrade.
Measure success, fallback rate, degraded rate, deadline misses and which model answered per request.
Rehearse a revoked primary in staging and keep the failure scenarios in the keyless suite.
Written and edited by the nexGenCoders team. Spotted a mistake? Tell us and we will fix it.
Don't lose this lesson
Create a free account to save your progress, keep your streak, and work toward a shareable certificate.