The day your single LLM provider has a bad hour, your product has a bad hour. If every request in your app funnels through one vendor’s API, then their rate limit, their regional outage, and their surprise pricing change are all your problems now, and you find out about them in production. I have watched a classification pipeline sit dead for forty minutes because an upstream provider returned 529s and the code had no concept of anywhere else to send the request.

The naive fix is to wrap each provider’s SDK in a try/except and call a different one on failure. That works for exactly one afternoon, until you have three providers, four teams, and nobody can tell you what the app spent yesterday. LiteLLM is the layer that makes multi-provider routing boring. It speaks the OpenAI API format on the front, routes to Anthropic, Gemini, Groq, or a local Ollama on the back, and gives you fallbacks, budgets, and logging without touching your application code. This is the setup I run, and the mistakes I made getting there.

Start With the Naive Version and Watch It Break

Here is the direct approach most teams reach for first. One provider, called directly.

from anthropic import Anthropic

client = Anthropic(api_key=ANTHROPIC_KEY)

def classify(text):
    resp = client.messages.create(
        model="claude-haiku",
        max_tokens=16,
        messages=[{"role": "user", "content": f"Label as spam or ham: {text}"}],
    )
    return resp.content[0].text

This is fine until it is not. The failure modes stack up fast:

  • The provider returns a 429 or 529 and every call in the pipeline fails at once. You have no second provider wired in.
  • A new team wants to try Gemini for a cheaper task. Now you have two SDKs, two auth schemes, two response shapes to normalize.
  • Finance asks what you spent on AI last month, broken down by feature. You have no answer because spend lives in three separate vendor dashboards.
  • You want to cap a flaky internal tool at $50 a month so a runaway loop cannot bankrupt you. There is nowhere to put that limit.

Each of these is solvable with more application code. The problem is that it is the same code, written again in every service, drifting out of sync. Routing, retries, budgets, and logging are infrastructure concerns. They do not belong scattered across your business logic.

The Proxy Model

LiteLLM’s core idea is a single HTTP server that looks exactly like the OpenAI API. Your app points its OpenAI client at http://litellm:4000 instead of api.openai.com, and the proxy decides where each request actually goes.

                  ┌──────────────────────────────────┐
                  │          LiteLLM Proxy            │
  your apps  ───▶ │  OpenAI-format in                 │
 (OpenAI SDK)     │   ├─ route by model name          │ ───▶ Anthropic
                  │   ├─ fallback on error            │ ───▶ Gemini
                  │   ├─ enforce per-key budget       │ ───▶ Groq
                  │   ├─ log to Langfuse              │ ───▶ Ollama (local)
                  │  OpenAI-format out                │
                  └──────────────────────────────────┘

The win is that your application never learns a second SDK. Everything downstream of the proxy, which model, which provider, what the fallback order is, lives in one config file you can change without a deploy.

from openai import OpenAI

client = OpenAI(base_url="http://litellm:4000", api_key="sk-my-proxy-key")

def classify(text):
    resp = client.chat.completions.create(
        model="cheap-classifier",   # a logical name, not a provider model
        messages=[{"role": "user", "content": f"Label as spam or ham: {text}"}],
    )
    return resp.choices[0].message.content

Notice cheap-classifier. The app asks for a capability, not a vendor model id. What that resolves to is a routing decision made in config, and you can repoint it from Groq to Ollama to Haiku without changing a line of application code.

Per-Route Model Mapping

The config file is where the real work happens. Each entry under model_list maps a public name your apps call to an underlying provider model. You can point several providers at the same public name to build a routing pool.

# config.yaml
model_list:
  # Bulk classification: cheapest wins, fall through if it chokes
  - model_name: cheap-classifier
    litellm_params:
      model: groq/llama-3.3-70b-versatile
      api_key: os.environ/GROQ_API_KEY
  - model_name: cheap-classifier
    litellm_params:
      model: ollama/llama3.2
      api_base: http://ollama:11434

  # Balanced work: production default
  - model_name: workhorse
    litellm_params:
      model: anthropic/claude-sonnet
      api_key: os.environ/ANTHROPIC_API_KEY
  - model_name: workhorse
    litellm_params:
      model: gemini/gemini-2.5-pro
      api_key: os.environ/GEMINI_API_KEY

  # Hard reasoning: frontier only
  - model_name: deep-reasoning
    litellm_params:
      model: anthropic/claude-opus
      api_key: os.environ/ANTHROPIC_API_KEY

router_settings:
  routing_strategy: latency-based-routing
  num_retries: 2
  fallbacks:
    - cheap-classifier: ["workhorse"]
    - workhorse: ["deep-reasoning"]
  context_window_fallbacks:
    - workhorse: ["deep-reasoning"]

Two public names, cheap-classifier and workhorse, each have multiple backends. The router load-balances across the backends for a name and, on failure, walks the fallbacks map to a different pool. context_window_fallbacks is the one people forget: when a request exceeds the chosen model’s context window, LiteLLM reroutes it to a model that can hold it instead of returning an error.

Keep secrets out of the file. The os.environ/NAME syntax tells LiteLLM to read the key from the environment at load time, so the config is safe to commit.

Routing Strategies, and Picking the Right One

routing_strategy decides which backend in a pool gets a given request. The choice has real cost and latency consequences.

StrategyHow it picksUse when
simple-shuffleRandom, weighted by rpm/tpmYou just want even spread across keys
latency-based-routingLowest recent p95 latencyUser-facing, latency matters most
usage-based-routing-v2Least-loaded by current TPMYou are hugging provider rate limits
cost-based-routingCheapest capable backendBatch and background jobs

The pattern that actually moves the bill is matching strategy to workload. User-facing chat uses latency-based-routing so people are not staring at a spinner. Overnight batch classification uses cost-based-routing so it drains to the cheapest backend that can do the job. You do not need one global answer; you can run two proxy deployments, or scope strategy per model group with model_group_alias settings.

The biggest single lever is sending bulk, low-stakes work to cheap models. Spam labeling, intent classification, routing tickets to queues, extracting a field from a document: these are high-volume and forgiving. Point them at cheap-classifier backed by Groq or a local Ollama and let the frontier models handle only the work that needs reasoning. In one pipeline, moving classification off a frontier model and onto a 70B open model behind Groq cut that workload’s cost by roughly 30x for no measurable accuracy loss on the label set we cared about.

Budgets and Virtual Keys

Direct provider keys are blunt instruments. Every service sharing one key means one leaked key, one runaway loop, and no per-feature accounting. LiteLLM issues virtual keys, which are proxy-side credentials with their own budgets, rate limits, and allowed-model lists.

First, turn on the database-backed features and a master key.

general_settings:
  master_key: os.environ/LITELLM_MASTER_KEY
  database_url: os.environ/DATABASE_URL

litellm_settings:
  max_budget: 2000        # global monthly ceiling in USD
  budget_duration: 30d

Then mint a scoped key for a specific service. This is a call to the proxy’s admin API using the master key.

import httpx

httpx.post(
    "http://litellm:4000/key/generate",
    headers={"Authorization": f"Bearer {MASTER_KEY}"},
    json={
        "models": ["cheap-classifier"],   # this key cannot touch frontier models
        "max_budget": 50,                 # hard stop at $50
        "budget_duration": "30d",
        "rpm_limit": 500,
        "metadata": {"team": "support-tooling"},
    },
)

That key can only call cheap-classifier, cannot spend past $50 a month, and is capped at 500 requests a minute. A bug in the support tool now costs you $50 and a 400 error, not a five-figure surprise. When the budget is hit the proxy returns a clean error your code can catch, and spend is attributed to the team metadata so your cost report writes itself.

The important shift is that budget enforcement lives at the proxy, not in application code that everyone forgets to add. A new service cannot overspend by default, because it does not get a key without a budget attached.

Logging to Langfuse

You cannot optimize what you cannot see. Raw provider dashboards tell you totals, not which prompt, which user, or which feature drove them. LiteLLM has first-class callbacks that ship every request to an observability backend. Langfuse is the common choice because it gives you traces, token counts, and cost per call without you instrumenting anything.

litellm_settings:
  success_callback: ["langfuse"]
  failure_callback: ["langfuse"]
# environment
LANGFUSE_PUBLIC_KEY=pk-lf-...
LANGFUSE_SECRET_KEY=sk-lf-...
LANGFUSE_HOST=https://cloud.langfuse.com

That is the entire integration. Every call through the proxy now lands in Langfuse with its model, latency, input and output tokens, and computed cost. You can attach a trace id and user id from the app so a single conversation shows up as one trace across however many model calls it made.

resp = client.chat.completions.create(
    model="workhorse",
    messages=messages,
    extra_body={
        "metadata": {
            "trace_id": conversation_id,
            "generation_name": "summarize-ticket",
            "trace_user_id": user_id,
        }
    },
)

Now the question “what did feature X cost last week, and which users drove it” is a Langfuse filter, not a forensic exercise across three vendor consoles. Failed calls land too, through failure_callback, so you can see when fallbacks fired and why, which is the data you need to tune the routing you set up earlier.

The Docker Setup

Running the proxy is one container, plus Postgres if you want virtual keys and budgets, plus Ollama if you want a local backend. Compose ties it together.

# docker-compose.yaml
services:
  litellm:
    image: ghcr.io/berriai/litellm:main-stable
    command: ["--config", "/app/config.yaml", "--port", "4000"]
    ports: ["4000:4000"]
    volumes:
      - ./config.yaml:/app/config.yaml:ro
    environment:
      LITELLM_MASTER_KEY: ${LITELLM_MASTER_KEY}
      DATABASE_URL: postgresql://litellm:litellm@db:5432/litellm
      ANTHROPIC_API_KEY: ${ANTHROPIC_API_KEY}
      GEMINI_API_KEY: ${GEMINI_API_KEY}
      GROQ_API_KEY: ${GROQ_API_KEY}
      LANGFUSE_PUBLIC_KEY: ${LANGFUSE_PUBLIC_KEY}
      LANGFUSE_SECRET_KEY: ${LANGFUSE_SECRET_KEY}
    depends_on: [db]

  db:
    image: postgres:16
    environment:
      POSTGRES_USER: litellm
      POSTGRES_PASSWORD: litellm
      POSTGRES_DB: litellm
    volumes:
      - litellm-pg:/var/lib/postgresql/data

  ollama:
    image: ollama/ollama:latest
    ports: ["11434:11434"]
    volumes:
      - ollama:/root/.ollama

volumes:
  litellm-pg:
  ollama:

Pin to main-stable rather than latest in anything you care about; LiteLLM ships fast and the bleeding edge occasionally breaks a callback. Put the proxy behind your normal ingress, give it a readiness probe on /health/readiness, and run at least two replicas so the proxy itself is not a single point of failure. The whole point was to survive one backend’s outage; do not reintroduce a single point of failure in the thing meant to prevent it.

A quick sanity check once it is up:

curl http://localhost:4000/v1/chat/completions \
  -H "Authorization: Bearer $LITELLM_MASTER_KEY" \
  -H "Content-Type: application/json" \
  --data '{"model": "cheap-classifier", "messages": [{"role": "user", "content": "ping"}]}'

If that returns a completion, your routing, fallbacks, and logging are all live, and your apps can swap their base_url over one at a time.

A Realistic Routing Policy

Putting the pieces together, here is a policy that balances cost against reliability for a typical product with mixed workloads.

WorkloadPublic namePrimary backendFallbackStrategy
Spam / intent labelscheap-classifierGroq 70BOllama localcost-based
Chat repliesworkhorseClaude SonnetGemini Prolatency-based
Long document analysisworkhorseGemini ProClaude Opus (context fallback)latency-based
Agentic / hard reasoningdeep-reasoningClaude OpusGemini Prolatency-based

The shape is deliberate. Cheap and forgiving work drains to the cheapest capable backend and only climbs tiers on failure. User-facing work optimizes for latency and crosses providers on error so a single outage degrades gracefully instead of failing. Nothing calls a frontier model unless the task genuinely needs one, which is where most of the savings come from.

What Works, What Does Not, and What to Actually Do

What works without reservation: the OpenAI-compatible front end means adoption is a base_url change, not a rewrite, so you can migrate one service at a time. Fallbacks and context-window rerouting genuinely remove the class of outage where one provider’s bad hour becomes yours. Virtual keys with budgets move overspend protection into infrastructure where it belongs, and the Langfuse integration turns cost from a mystery into a dashboard.

What does not: the proxy is now a hop in your critical path, so its latency and availability are your latency and availability. Budget them. The config file grows into something that deserves review and version control, because a bad fallback edit is a production change with no code review if you let it be. And LiteLLM normalizes the common surface of these APIs well, but provider-specific features at the edges, some tool-calling quirks, certain streaming behaviors, do not always map cleanly, so test the features you actually depend on rather than assuming parity.

What to actually do: stand up the proxy with two or three providers and a Postgres, point one non-critical service at it, and wire Langfuse on day one so you have cost data from the start. Define logical model names by capability, not by vendor, so routing stays a config decision. Move your highest-volume, lowest-stakes workload to a cheap backend first, because that is where the money is, and let fallbacks handle the reliability you were missing. The goal is not to pick the perfect provider. It is to stop betting your uptime on any single one.