Fault-Tolerant Router for Multiple LLM API Vendors
System DesignModel answerLast updated
Design a client library that spreads LLM calls across several vendors, enforcing limits, isolating failures, and choosing providers by cost and latency while staying thread-safe and observable.
Your team calls several third-party LLM vendors, and a single vendor outage or throttling event should not take the product down. You are asked to design and sketch the implementation of an in-process client library that sends each request to the best available vendor.
The library must cover:
- Vendor registration and capabilities: adding and removing vendors at runtime, and mapping each vendor's models to a common model family, including context window size and feature support (tools, streaming) and pricing.
- Governance: per-vendor and per-key rate limits (requests and tokens per minute) and spend quotas.
- Resilience: health checks, per-attempt and overall timeouts, and circuit breakers.
- Routing: load balancing that accounts for cost and latency, plus retry and fallback policies when a vendor is degraded or down.
- Observability: metrics, logs, and tracing.
- Security: safe handling of API keys.
- Concurrency: correct behavior with many threads sharing the library.
State your assumptions about scale (vendors, request rate, token sizes, latency targets, whether streaming is required). Then describe the public interfaces, the core data structures, the lifecycle of a single request, and how each failure mode is handled. Include a code sketch for at least one non-trivial component, such as the circuit breaker or the rate limiter.
Hints
Hint 1
Separate vendor-specific details (request formats, error codes) behind an adapter, so the router only deals with a canonical model family and a small set of error classes: retryable, non-retryable, and auth.
Hint 2
Think about what happens when every instance of your service picks the same 'best' vendor at the same moment. Consider randomized selection among the top candidates rather than a strict minimum score.
Hint 3
Streaming changes retry rules: once any output has been sent to the caller, a transparent retry on another vendor can duplicate or corrupt output. Decide where the retry boundary is.
Hint 4
Rate limits are enforced by the vendor per key, but your fleet has many instances. Compare static per-instance shares, a central Redis bucket, and leasing batches of tokens.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Overview
I would build this as a thin in-process router around per-vendor adapters. Each vendor has its own isolated state (limiter, breaker, latency stats), so one sick vendor cannot degrade the rest. The routing path must be cheap, since the budget is about 1 ms of overhead per request.
1. Assumptions
- 3 to 8 vendors, 2 to 10 models each, including a self-hosted option.
- About 2,000 requests/s peak per instance and tens of instances; roughly 2k input and 500 output tokens per request.
- Time to first token p50 around 400 ms, p99 under 3 s; overall deadline 60 s.
- Vendor limits are per API key (requests/min and tokens/min); budgets are monthly dollar amounts.
- Streaming is required. Optional Redis is available for fleet-wide limits.
2. Interfaces
ProviderAdapter:capabilities(),complete(),stream(),classify(exc) -> ErrorClass,health_probe().ModelCapability: vendor model id, canonical family, max context, tool/streaming support, input and output price per 1k tokens.LLMRequest: family, messages, max_tokens, stream flag, deadline, priority, idempotency key, routing hint (cheapest,fastest,balanced).ProviderPool:register(adapter, limits, key_ref),deregister(name),complete(req),stream(req).ErrorClass:RETRYABLE(429, 5xx, timeouts, resets),NON_RETRYABLE(400, context too long, content policy),AUTH(401/403).
The adapter keeps vendor quirks out of the router, which makes new vendors cheap to add and easy to test with fakes.
3. Data structures
- Capability index:
family -> [(vendor, capability)], rebuilt on register/deregister and swapped atomically (copy-on-write) so the hot path reads without locks. - Per-vendor state: request bucket, token bucket, circuit breaker, latency EWMAs (TTFT and per-output-token), a bucketed error-rate window, an in-flight counter, and a spend counter.
- Secrets: only a
key_ref(for example a vault path) is stored. A secret provider resolves it and caches it with a TTL, which also enables rotation without restarts.
4. Request lifecycle
- Filter: drop candidates whose context window is too small for prompt plus max_tokens, that lack a required feature, whose breaker is open, or whose quota is spent.
- Score: a weighted sum of normalized expected cost, latency EWMA, recent error rate, and load (in-flight over capacity). The routing hint picks the weights.
- Select: power-of-two-choices among the top k, or weighted random. A strict argmin makes every instance herd onto one vendor and oscillate.
- Acquire capacity: non-blocking
try_acquireon both buckets using an estimated token charge. If it fails, go to the next candidate rather than waiting. - Call: timeout is
min(per_attempt_timeout, remaining_deadline). - Record: update breaker, EWMA, error window, and spend; reconcile the token bucket with the usage the vendor reports.
- Failure handling: classify, then retry, fall back, or fail.
5. Key components
Rate limiting. Use token buckets for requests and tokens. Three options for the fleet:
- Static share (
limit / instances): simple, but wastes capacity under skewed traffic. - Central Redis Lua bucket: accurate, about 0.5 ms per call and a new dependency.
- Hybrid: lease batches of tokens from Redis and spend them locally. This is usually the best trade-off.
On a 429, honor Retry-After by pushing out the bucket's next-available time. That is cheaper and more precise than tripping the breaker.
Circuit breaker. Three states:
- Closed: record outcomes in a short sliding window (say 10 s). Open when there are at least about 20 calls and a failure ratio of 50% or more.
- Open: reject immediately for a cool-down (say 30 s).
- Half-open: allow a small number of probes (say 3). One failure reopens; success closes and clears the window.
Guard transitions with a lock, keep the critical section tiny, and make sure half-open probe counts are decremented on every outcome. Count only retryable failures; a 400 caused by a bad request must not open the breaker.
Retries and fallback.
- Retry only
RETRYABLEerrors, with exponential backoff and full jitter, capped by the remaining deadline. - Prefer failing over to a different vendor over retrying the same one.
- Use a retry budget (for example retries at most 10% of traffic) to avoid retry storms during a partial outage.
NON_RETRYABLEerrors return immediately.AUTHerrors disable that key, alert, and fail over.- Use idempotency keys where the vendor supports them.
Streaming. Before the first chunk is delivered, failover is safe and invisible. After that, a transparent retry could duplicate or splice output. Either surface a typed error to the caller, or (if the product allows) resume with a continuation prompt and clearly mark it. Use a TTFT timeout plus an inter-chunk idle timeout.
Health checks. Combine passive signals (real traffic outcomes) with light active probes while a breaker is open, so recovery is detected without sacrificing user requests. Avoid probes that cost real money at high frequency.
Quotas. Track spend using estimated cost at admission and reconcile on completion. At a soft threshold, bias routing toward cheaper vendors; at the hard cap, exclude the vendor. Lower-priority requests are shed first under pressure.
6. Observability and security
- Metrics: per vendor and model: request count, error count by class, latency histograms (TTFT and total), tokens, cost, breaker state, bucket fill, retries and fallbacks. Keep label cardinality bounded.
- Tracing: one span per request with child spans per attempt, annotated with vendor, model, error class, and fallback reason.
- Logs: structured, with request ids. Never log prompts by default, and never log keys or authorization headers; redact at the adapter boundary.
- Keys: stored in a secrets manager, fetched by reference, rotated by TTL, scoped per environment, and separate per vendor.
7. Concurrency
- Lock-free reads of the capability index through atomic reference swap.
- Fine-grained locks (or atomics) per vendor state; never hold a lock across network I/O.
- Bounded in-flight per vendor (a semaphore or bulkhead) so a slow vendor cannot consume all threads.
- Clean shutdown: drain in-flight calls on deregister.
8. Trade-offs and common mistakes
- Strict lowest-score routing causes herding; add randomness.
- Retrying on the same failing vendor, or retrying without a budget, amplifies outages.
- Counting client errors (400s) toward breaker failure rates.
- Ignoring streaming semantics and silently replaying partial output.
- Estimating tokens only at admission and never reconciling, which drifts the limiter.
- Holding locks during I/O, or logging secrets and prompts.
Complexity of the hot path is O(k) in the number of candidate vendors for a family (small), with constant-time limiter and breaker checks.