跳到正文
DEV Community· Jangwook Kim·· 2 小時前AI 評分53

LiteLLM Proxy 故障切換:延遲、重試與生產風險

LiteLLM Proxy Failover: Latency, Retries, and Production Risk

AI 導讀

Jangwook Kim 評估 LiteLLM Proxy 的故障切換後,認為它可作為路由層,但現有證據不足以支持通用的切換延遲 SLO 或多租戶隔離保證。

正文

Why We Evaluated LiteLLM Failover

The gateway failure we worry about most is not a visible 503. It is a successful response that arrives after the application has abandoned the request, while retries continue consuming connections and upstream capacity.

LiteLLM promises to handle routing between our application and multiple model providers. Underneath its OpenAI-compatible interface, the router selects deployments, retries eligible failures, applies cooldowns, and moves requests through configured fallback model groups.

That distinction matters: fallback is not necessarily the first response to failure. It follows retry handling. A generous retry policy can turn an available backup into a destination reached too late.

Our review asks whether we would put that mechanism on a production request path. We examined the official fallback configuration, the published full-feature benchmark, the Pfizer resilience investigation, and a separate 30-day gateway field report.

One boundary is important upfront: we did not execute a pinned LiteLLM installation for this review. The walkthrough below is a runnable reproduction candidate, not a completed benchmark. We cannot honestly supply our own measured switching latency, error rate, or retry count. We keep external measurements attributed and separate from our calculations.

Our architectural conclusion is nevertheless actionable: LiteLLM is a credible routing layer, but its production acceptance test must include deadlines, attempted upstream calls, and unaffected traffic—not just final HTTP status.

We apply the same distinction between routing capability and deployment readiness in our llm-d production review.

Hands-On Walkthrough: Setup, Execution & Output

We designed the reproduction around two local OpenAI-compatible endpoints. The primary returns a real HTTP 503; the backup returns a valid completion. No provider credentials or paid inference are needed.

The proxy installation command is:

python3 -m venv .venv
. .venv/bin/activate
python -m pip install 'litellm[proxy]'
python -m pip freeze > requirements.observed.txt

The quotes protect the extras syntax from shell expansion. The supplied source material does not independently verify the installation page or a compatible package pin, so this command is a bootstrap path—not a reproducibility lock. Before accepting results, we would rebuild from a tested lockfile and record Python, LiteLLM, OpenAI SDK, and HTTP-client versions.

For configuration, we use the model-group fallback shape in the official reliability guide:

# config.yaml
model_list:
  - model_name: primary
    litellm_params:
      model: openai/gpt-4o-mini
      api_base: http://127.0.0.1:8101/v1
      api_key: local-only
      timeout: 2
  - model_name: backup
    litellm_params:
      model: openai/gpt-4o-mini
      api_base: http://127.0.0.1:8102/v1
      api_key: local-only
      timeout: 2

router_settings:
  routing_strategy: simple-shuffle
  num_retries: 2
  allowed_fails: 3
  cooldown_time: 30
  fallbacks:
    - primary: [backup]

general_settings:
  master_key: sk-local-test

Different aliases make the fallback transition explicit. Two deployments sharing one alias would instead introduce within-group selection into the experiment.

Save this standard-library mock as mock.py:

import json
import os
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

PORT = int(os.environ["PORT"])
STATUS = int(os.environ.get("STATUS", "200"))
DELAY = float(os.environ.get("DELAY", "0"))
NAME = os.environ["NAME"]


class Handler(BaseHTTPRequestHandler):
    def do_POST(self):
        body = json.loads(
            self.rfile.read(int(self.headers.get("Content-Length", "0")))
        )
        request_id = body["messages"][-1]["content"]
        start = time.monotonic_ns()
        print(json.dumps({
            "event": "start", "endpoint": NAME,
            "request_id": request_id, "ns": start
        }), flush=True)
        time.sleep(DELAY)

        if STATUS == 200:
            result = {
                "id": "chatcmpl-local",
                "object": "chat.completion",
                "created": int(time.time()),
                "model": "gpt-4o-mini",
                "choices": [{
                    "index": 0,
                    "message": {"role": "assistant", "content": NAME},
                    "finish_reason": "stop"
                }],
                "usage": {
                    "prompt_tokens": 1,
                    "completion_tokens": 1,
                    "total_tokens": 2
                }
            }
        else:
            result = {"error": {
                "message": "Injected outage",
                "type": "server_error",
                "code": "service_unavailable"
            }}

        payload = json.dumps(result).encode()
        self.send_response(STATUS)
        self.send_header("Content-Type", "application/json")
        self.send_header("Content-Length", str(len(payload)))
        self.end_headers()
        self.wfile.write(payload)
        print(json.dumps({
            "event": "end", "endpoint": NAME,
            "request_id": request_id,
            "ns": time.monotonic_ns(), "status": STATUS
        }), flush=True)

    def log_message(self, *args):
        pass


ThreadingHTTPServer(("127.0.0.1", PORT), Handler).serve_forever()

Start the endpoints and proxy in separate terminals:

PORT=8101 STATUS=503 NAME=primary python mock.py > primary.jsonl
PORT=8102 STATUS=200 NAME=backup python mock.py > backup.jsonl
litellm --config config.yaml --host 127.0.0.1 --port 4000

Then send a request without SDK-level retries:

curl --silent --show-error --max-time 15 \
  --write-out '\nhttp=%{http_code} total_seconds=%{time_total}\n' \
  http://127.0.0.1:4000/v1/chat/completions \
  -H 'Authorization: Bearer sk-local-test' \
  -H 'Content-Type: application/json' \
  -d '{
    "model": "primary",
    "messages": [{"role": "user", "content": "probe-0001"}]
  }'

A simulated successful response excerpt, not captured test output, looks like:

{
  "object": "chat.completion",
  "choices": [
    {
      "index": 0,
      "message": {"role": "assistant", "content": "backup"},
      "finish_reason": "stop"
    }
  ]
}

The response proves little without the endpoint logs. We would calculate:

  • Client recovery latency: request submission to completed fallback response.
  • Switch gap: backup request start minus the final primary response-end timestamp. This is a same-host approximation, not an internal router span.
  • Attempt amplification: all upstream request starts divided by submitted client requests.
  • Client error rate: failed requests divided by submitted requests.
  • Deadline-miss rate: requests exceeding the application deadline, including late HTTP 200 responses.

The switch gap can be slightly negative because a server-side log after writing a response can lag client receipt. For precise routing attribution, we would add gateway spans.

Our execution matrix starts with a healthy primary, then disables fallback during a primary failure, then enables fallback. We would repeat with zero and two retries, immediate 503s, 429s, and a primary delayed beyond its attempt timeout.

We would restart the proxy between cold-state runs, then run a separate continuous-outage sequence to observe cooldown behavior. A second request must not be assumed to skip the primary merely because the first failed.

For load testing, we would add fixed-rate arrivals and explicitly count missed submissions. A sequential curl loop cannot establish capacity or tail latency.

What We Could Not Verify and Other Limitations

Our review lacked execution evidence: no verified package lock, no local run, and no captured attempt traces. We would not replace those gaps with plausible-looking millisecond numbers.

The configuration and production evidence highlight several additional risks.

Synthetic fallback flags are not a proxy fault injector. For our proxy test design, we account for a version-specific constraint: starting with Proxy v1.85.0, incoming mock_testing_fallbacks, mock_testing_context_fallbacks, and mock_testing_content_policy_fallbacks are stripped and have no effect. Our reproduction therefore uses actual upstream HTTP failures. A direct Router unit test and a proxy request do not exercise identical boundaries.

Retries are a budget, not an attempt guarantee. Two retries may suggest three primary attempts, but cooldown, deployment availability, error classification, and overrides can change what reaches the endpoint. We count observed calls rather than infer them from YAML.

Per-attempt timeouts are not an end-to-end deadline. As an illustrative calculation, three primary attempts each consuming two seconds, followed by a two-second backup attempt, could consume eight seconds before backoff and overhead. That is not measured LiteLLM behavior or a universal upper bound. It is why we require explicit deadline budgeting.

A clean error graph can conceal lost capacity. In the joint Pfizer/LiteLLM investigation, we find a particularly relevant warning: CI throughput moved from roughly 300 RPS to 156 RPS during upgrade validation, without an increased HTTP error rate.

In our review of the regression, we traced the failure mechanism to Redis TLS selection: checking whether ssl existed instead of whether it was true. With ssl: false against plaintext Redis, best-effort cache operations could stall on the default five-second socket timeout and still let the request return HTTP 200.

We identified PR #32590, shipped in v1.93.0, as the Redis fix boundary for our release checks. We would verify that fix in the selected release and dependencies rather than treat a version number as sufficient assurance. This regression was caught in CI, not evidence of a provider-failover outage in Pfizer production. Its fallback fault-injection work was still listed as work in progress.

Streaming requires a separate contract. We would test failures before headers, before first content, and after partial output. Once the application consumes generated text, restarting elsewhere is not equivalent to transparently replaying an untouched request.

Cross-provider fallback also changes semantics. We treat encrypted reasoning as a fallback compatibility constraint: a target on another provider or API key cannot decrypt the earlier deployment's encrypted reasoning. During fallback, incompatible encrypted content is dropped; readable Responses reasoning summaries are retained, while incompatible thinking blocks are dropped whole. Schema support, tool calling, context capacity, residency, and output quality also need explicit acceptance tests.

Finally, the local configuration excludes Redis, budgets, callbacks, and spend persistence. Passing it would establish a narrow routing contract—not production readiness. We would add those dependencies incrementally, following the same observability discipline discussed in our Langfuse ingestion review.

Scale, Latency & Cost vs. Alternatives

We keep two evidence sets separate.

In our analysis of full-feature gateway performance, we keep the test conditions explicit: mock upstreams, four dedicated cores, 16 GiB per gateway, and one run per configuration. Routing uses simple-shuffle, two retries, three allowed fails, and a 30-second cooldown.

Under those conditions, we identify Python overload as a capacity warning: the gateway served 78.9% of requests at 75 RPS and 29.3% at 100 RPS. Those are workload-specific overload observations, not universal LiteLLM capacity limits. Enabling retries in a benchmark does not establish provider-down switching performance.

The Rust implementation in that article is a benchmark branch, with a fast path expected December 1. At this article's November 24 publication date, we would not treat those branch results as guaranteed performance from a pip-installed Python proxy.

For our separate 30-day workload comparison, we examine the following measurements rather than treat them as results from our unexecuted local harness:

Gateway Reported p50 overhead Reported p99 overhead Reported provider-down failover Reported memory at 1k RPS
LiteLLM 8 ms 41 ms 620 ms 890 MB
Bifrost 3 ms 11 ms 180 ms 412 MB
Portkey, self-hosted 6 ms 29 ms 340 ms 650 MB

These are external, workload-specific observations—not our measurements. For our interpretation, we retain the workload conditions: mirrored traffic, cache disabled, and an OpenAI → Anthropic → Bedrock chain. We could not verify the LiteLLM version, exact fallback YAML, client deadline, or a sufficiently precise definition of “failover time” to reproduce the table.

We therefore use it to identify candidates, not to rank gateways by their ability to meet our SLOs. We would shortlist Bifrost for a fresh routing-focused comparison, LiteLLM where provider integrations and callbacks matter, and managed offerings where operating the gateway is the larger cost.

For economics, we separate attempts from billable completions. A rejected 503 is not automatically billed like successful generation.

Consider this illustrative monthly planning model:

  • 10 million client requests.
  • 1% require fallback.
  • Each affected request makes three primary attempts and one backup attempt.
  • Unaffected requests make one attempt.

Total upstream attempts become:

9.9 million + (100,000 × 4) = 10.3 million

That is 1.03× aggregate amplification, but 4× for the affected cohort. Cooldown can reduce it; layered client retries can increase it.

If every fallback completion costs an additional $0.002 relative to the primary, that cohort adds $200 in completion cost. We would add any billable abandoned generation separately.

For a simple build-versus-operate comparison, assume $150/month in gateway infrastructure and six maintenance hours at $150/hour: $1,050/month. A managed alternative at an effective $0.00015 per request costs $1,500 at this volume. These are assumptions, not vendor quotes.

The arithmetic break-even is seven million requests per month. That comparison excludes initial integration and migration work; it also excludes any managed base fee. Avoiding custom routing code can justify LiteLLM below that threshold, while recurring incident work can erase the apparent self-hosting savings above it.

Error-budget math is equally unforgiving. At 10 million requests and 99.9% availability, the monthly allowance is 10,000 bad requests. If 100,000 outage-affected requests recover but 20% miss the application deadline, those 20,000 deadline failures consume twice the allowance—even with eventual HTTP 200 responses.

To measure blast radius, we would run failing-primary traffic beside direct-to-backup traffic and an independent healthy cohort. We would compare each cohort's deadline misses, throughput, queueing, and attempts. Aggregate success rate cannot reveal whether one provider's outage degraded unrelated tenants.

Our Final Verdict: When to Deploy, When to Skip

We would deploy LiteLLM when:

  • Its provider integrations and callbacks replace meaningful application complexity.
  • Every fallback target passes quality, schema, security, and residency checks.
  • The application deadline accommodates the measured retry and fallback path.
  • Client retries are coordinated with gateway retries.
  • Release gates track submitted traffic, completed traffic, deadline misses, and upstream attempts.
  • Healthy tenants remain healthy during injected provider outages.

We would hold off when:

  • A purchase decision depends on treating the reported 620 ms as a guaranteed failover bound.
  • The team cannot reproduce its package and dependency set.
  • Streaming recovery is assumed rather than tested.
  • The backup shares the primary's constrained quota or failure domain.
  • The proposed “high availability” design is one irreplaceable proxy instance.
  • Monitoring counts only HTTP errors.

Our verdict is conditional adoption, not an unconditional performance endorsement. LiteLLM offers the right routing primitives, but the supplied evidence does not establish a universal switching-latency SLO or multi-tenant isolation guarantee.

We would start with the official fallback guide, run the two-endpoint contract check, and then add production features and concurrency. For agent workloads, we would also review durable execution and side-effect boundaries: routing a generation twice must not accidentally become permission to execute a business action twice.

來源:DEV Community · dev.to