My earlier post on running Amazon's Ergo model locally with vLLM and quantization (https://dev.to/robust_true_try/serving-amazons-ergo-model-locally-without-burning-money-50o1) ended with a fallback router: try the local GPU first, fall back to the Bedrock API when it fails. That design holds up. The router is what breaks.

This post covers the three failure modes you hit within the first week of production, and the router behavior that prevents them. By the end you'll know how to handle timeouts, streaming, and retry storms without waking up to a surprise API bill.

The timeout that costs money

The obvious fallback rule is: if the local call fails, use the API. The dangerous version is "fails" meaning "raised an exception." A slow local model does not raise anything. It just hangs.

When the local request hangs, an impatient router times it out and sends the same request to Bedrock. The local request is still running. If it eventually finishes, you paid for both compute paths and returned whichever answer arrived first.

Set a hard deadline on the local call and cancel the task, not just abandon it:

import asyncio import httpx LOCAL_TIMEOUT = 30.0 async def call_local(prompt: str, client: httpx.AsyncClient) -> str: resp = await client.post( "http://localhost:8000/v1/completions", json={"model": "ergo", "prompt": prompt, "max_tokens": 512}, timeout=LOCAL_TIMEOUT, ) resp.raise_for_status() return resp.json()["choices"][0]["text"] async def route(prompt: str, client: httpx.AsyncClient) -> str: try: return await asyncio.wait_for(call_local(prompt, client), LOCAL_TIMEOUT + 2) except (asyncio.TimeoutError, httpx.TransportError): return await call_api(prompt, client) 

The two-second buffer lets httpx deliver its own timeout and clean up the connection. asyncio.wait_for cancels the inner task, which closes the in-flight request instead of leaving vLLM generating tokens nobody will read.

Streaming changes the failure model

Non-streaming calls fail before they produce output, so fallback is clean. Streaming calls fail in the middle. The client has already received half the answer, sent it to the user, and rendered it.

You cannot fall back mid-stream without duplicating output. Decide the policy before you ship:

  • Retry only if zero tokens have been emitted. Track the first chunk; before it arrives, a failure is invisible to the user.
  • If tokens have flowed, end the stream cleanly with a truncation notice instead of restarting.
  • Never buffer the whole stream "just in case." That erases the latency benefit of streaming.

The router needs a guard around the first chunk:

async def stream_with_fallback(prompt: str): emitted = 0 try: async for chunk in stream_local(prompt): emitted += 1 yield chunk except httpx.TransportError: if emitted == 0: async for chunk in stream_api(prompt): yield chunk return yield "\n\n[response truncated: local server disconnected]" 

This is the part no tutorial covers. Test it by killing the vLLM process mid-stream; you will find your router's real behavior in ten seconds.

Fallback loops create retry storms

The third failure is self-inflicted. A naive router treats every error as "local is down, use the API." A single malformed request returns a 400 from vLLM, the router retries on Bedrock, Bedrock also returns a 400, and now you have paid for two API calls to answer a request neither model could handle.

Classify errors before routing:

RETRYABLE = {429, 500, 502, 503, 504} def should_fallback(status: int | None, exc: Exception | None) -> bool: if exc and isinstance(exc, (httpx.ConnectError, httpx.ReadTimeout)): return True # server-side problem, API may succeed if status is not None: return status in RETRYABLE return False # 4xx: same request, same result, don't pay twice 

A 4xx means the request itself is broken. Send it to your dead-letter log, not to a second provider.

Add a cooldown so one bad minute doesn't drain the budget

Once the local server fails, every request in the next burst hits the API while you restart vLLM. Add a circuit breaker: after N consecutive fallbacks, route everything to the API for a fixed cooldown, then probe the local server with one cheap request before restoring traffic.

A small class is enough:

import time class CircuitBreaker: def __init__(self, threshold: int = 3, cooldown: float = 60.0): self.failures = 0 self.threshold = threshold self.cooldown = cooldown self.opened_at = 0.0 def allow_local(self) -> bool: if self.failures >= self.threshold: if time.monotonic() - self.opened_at < self.cooldown: return False self.failures = self.threshold - 1 # half-open: probe with real traffic return True def record(self, ok: bool) -> None: if ok: self.failures = 0 else: self.failures += 1 if self.failures >= self.threshold: self.opened_at = time.monotonic() 

The half-open probe matters. Without it, the breaker either stays open forever or slams fully shut and dumps the whole queue back onto a server that may still be unhealthy.

Watch the metric that predicts the bill

Local GPU utilization tells you the server is alive, not that traffic is routing correctly. Track one number instead: the fallback ratio, fallbacks divided by total requests, per minute. A healthy setup sits near zero. A rising ratio means the local path is degrading before your alerts notice, and every point of that ratio is API spend.

Log the reason code with each fallback (timeout, connect_error, 5xx). "Fallback rate is up" is an incident; "fallbacks due to timeouts doubled after the last deploy" is a fix.

Key takeaways

  • Apply a hard timeout to local calls and actually cancel the task, or you pay for both the GPU and the API on every slow request.
  • Only fall back mid-stream if zero tokens have been emitted; otherwise truncate cleanly.
  • Never route 4xx errors to the API provider; the same request will fail there too, and you pay for the lesson.
  • A circuit breaker with a half-open probe prevents one vLLM restart from turning into an API spending burst.
  • Monitor the fallback ratio per minute with reason codes; it is the earliest signal of both technical failure and cost drift.

Source

Serving Amazon's Ergo Model Locally Without Burning Money — this follow-up adds the production failure modes the first post's fallback design doesn't handle: timeouts, mid-stream failures, retry storms, and circuit breaking.

Support this work

These write-ups are researched and published with no paywall, sponsor, or tracking. If one saved you an afternoon, a small tip keeps them coming.

USDT, USDC or USDD · TRC-20 (Tron)

TFTNsfyomKrnUutRjBTGVULp19ByW29KbY