Heidelberg AICurriculum
Track 12 · Advanced
12.8

The LLM gateway

One key, many models, and a budget that actually holds

7 lessons 2026-08-13 AI-generated

1Overview

A proxy that speaks one API to your applications and many APIs to providers, adding auth, budgets, routing, failover and logging in between.

The EU-sovereign inference chapter answers whose GPUs run your tokens. This one answers what happens to a request on the way there: which model it lands on, whose budget it spends, what happens when that provider is down, and whether anyone can reconstruct it afterwards. → A gateway is the single most useful piece of infrastructure for an organisation with more than one AI project, and it is one container. → It is also where the governance policy you wrote in an earlier chapter stops being a document and becomes a rule that returns HTTP 429.

One endpoint in front of every model you use — local, EU-hosted, frontier — with per-key budgets, provider failover and a log of every token. It is the layer where "we have a policy about AI spending" becomes a 429 instead of a memo.

1.2After this chapter you can
Put one OpenAI-compatible endpoint in front of several model providers
Enforce a per-team or per-key budget that fails the request instead of the invoice
Fail over between providers without changing application code
Log every request so a cost spike can be traced to a caller
Route by task: cheap model for bulk, expensive model for judgment
Decide when a gateway is worth its operational weight and when it is not
1.3When to reach for it

Two or more projects, or two or more providers. One app talking to one provider does not need this.

1.4Key parts

Virtual keys per team, a spend ceiling per key, a routing policy, a fallback chain, and a request log with token counts.

1.5Free vs paid

Both anchors are open source and self-hostable; both also sell a managed tier. Self-hosted costs one small container and a database.

1.6Watch out

A gateway is on the critical path of every AI call you make. Budget for its failure modes before you route production through it.

2Lessons 7

2.1 Route all LLM calls through a single OpenAI‑compatible endpoint

The LiteLLM proxy (or openziti llm‑gateway) provides an OpenAI‑compatible /v1/chat/completions endpoint that forwards requests to configured providers.

Run a gateway exposing one /v1/chat/completions URL and forward calls to multiple model backends

  1. Create a config.yaml file listing each provider’s API key and base_url
  2. Start the gateway with llm-gateway run config.yaml (or litellm --config config.yaml)
  3. Send a request to http://localhost:8080/v1/chat/completions using any OpenAI‑compatible client
  • You'll see The client receives a normal response even though the request was routed through the local gateway to different providers
  • Takeaway A single endpoint lets every application talk to many models without changing code
  • Check How does routing all LLM calls through one OpenAI‑compatible /v1/chat/completions endpoint simplify integration with multiple model providers?
  • Cost Free and open source to self-host; both projects also sell a managed tier. Self-hosting costs one small container and, for LiteLLM, a database for key and spend state.

2.2 Create a virtual key with a hard spend limit

A virtual key is an API token generated for a team that includes a max_budget enforcing a hard spending ceiling.

Generate a virtual key for a team and set a maximum budget that returns an error once the limit is reached

  1. Open Terminal and run a curl command to POST to /key/generate on the LiteLLM admin endpoint, including your master‑key in the Authorization: Bearer header and a JSON body with {"models": ["gpt-4"], "max_budget": 50}
  2. Verify that the response contains a new virtual key identifier and that it is stored in the proxy’s LiteLLM_VerificationTokenTable backed by Postgres
  3. Make an API call using the newly created virtual key; when the cumulative spend exceeds the max_budget, observe an HTTP 400 error with the message Authentication Error, ExceededTokenBudget…
  4. If using Bifrost, open the Web UI, navigate to Virtual Keys → Add Virtual Key, set the budget amount and reset period, assign the key to a team, and save
  • You'll see The application receives a normal response on the first request and an HTTP 400 ExceededTokenBudget error on the request that exceeds the key’s budget
  • Takeaway A virtual key separates caller identity from the provider key and enforces spend limits instantly via error responses
  • Check What response does the gateway return when the cumulative spend of a virtual key exceeds its defined max_budget?
  • Cost Free — budgeting is a core feature of both open-source proxies, not a paid add-on. The cost is operational: someone has to decide the ceilings and update them as teams grow.

2.3 Switch to another LLM provider automatically

The fallback chain maps a primary model to an ordered list of alternate models used when the primary fails.

Declare a fallback chain so a provider outage or rate‑limit becomes a slower response instead of a failed one, with zero changes on the calling side.

  1. Open config.yaml in your favourite editor.
  2. Add a fallbacks entry under litellm_settings, mapping the primary model to an ordered list of alternates, e.g. fallbacks: [{"gpt-4": ["claude-opus", "local-llama"]}].
  3. Optionally configure content_policy_fallbacks, context_window_fallbacks and default_fallbacks for specific failure types.
  4. Set num_retries and cooldown_time in the same file to control how many attempts are made before moving on and how long a failing model is skipped.
  • You'll see A request against a deliberately down provider still returns a normal 200 response with an answer because the gateway used the next entry in the fallback chain.
  • Takeaway A fallback chain in LiteLLM’s config or Bifrost’s weighted pool turns a provider outage into a slower answer without changing application code, provided the alternate models are acceptable substitutes
  • Check How does configuring a fallback chain in LiteLLM’s config change the behaviour of requests when the primary model is unavailable?
  • Cost Free — fallback routing is core proxy behavior in both projects. The real cost is a slower response on the failover path (extra retry + a second provider round-trip) and, if the fallback model is weaker, a quality gap nobody flagged.

2.4 Find the exact caller behind a cost spike

The Logs UI provides controls such as Date filter, Key column with Group by key, and Model column with Group by model to trace spend.

Pinpoint which API key, team and model caused an unexpected increase in spend using the gateway’s request log

  1. Open the Logs UI from the gateway dashboard
  2. Set the date range to cover the period of the spike using the Date filter control
  3. Add a Key column and select Group by key to see spend per API key
  4. Add a Model column and enable Group by model to break down cost by model
  5. If needed, toggle Store Prompts in Spend Logs under Settings to include prompt content for deeper analysis
  • You'll see A spend chart showing a sudden rise and a filtered request list that isolates the responsible key and model within a few clicks
  • Takeaway The gateway logs attach caller identity to every request, turning anonymous provider totals into traceable spend data
  • Check Which controls in the Logs UI let you isolate the specific API key and model responsible for a sudden cost spike?
  • Cost Free — logging spend metadata is core to both proxies. Storing full prompt/response content is a real storage cost and a privacy decision, which is exactly why LiteLLM makes it an explicit opt-in rather than the default.

2.5 Send bulk calls to a cheap model and judgment calls to an expensive model

Model groups like bulk-classify and judgment-review are named mappings that the gateway resolves to specific underlying models.

Route high‑volume tasks to a low‑cost model while reserving the frontier model for judgement‑heavy requests without changing application code

  1. Open config.yaml in the LiteLLM gateway directory
  2. Add a group named bulk-classify that maps to a cheap, high‑throughput model (or local open‑weight model)
  3. Add a group named judgment-review that maps to the frontier model you want for judgement tasks
  4. Save config.yaml and restart the LiteLLM gateway service
  • You'll see Two identical request blocks – one with model: "bulk-classify" and one with model: "judgment-review" – are resolved by the gateway to different real models and show different per‑call costs
  • Takeaway Name model groups by task so the gateway can swap underlying models without touching call sites
  • Check How do the named model groups bulk-classify and judgment-review determine which underlying model processes each request?
  • Cost No direct cost — this is a config decision on top of infrastructure you already stood up in the first lesson. The savings come from routing volume away from the model that was never needed for it.

2.6 Plan for gateway failures

Deploying multiple gateway instances behind a load balancer with datastore backups ensures high availability.

Define an availability strategy for the AI gateway before routing production traffic through it

  1. Identify the failure scenarios that could affect the gateway process and its database
  2. Deploy multiple gateway instances behind a load balancer to eliminate a single‑container SPOF
  3. Configure backups and automated restart for the gateway’s datastore (Postgres, SQLite or ClickHouse)
  4. Document an on‑call rotation specifically for gateway incidents, separate from provider account owners
  • You'll see All applications report AI call errors simultaneously, indicating a gateway outage rather than a single‑provider failure
  • Takeaway A central gateway is a single point of failure, so its redundancy, backup and ownership must be treated with the same rigour as any downstream provider
  • Check What architectural measure prevents a single gateway instance from becoming a point of failure for production traffic?
  • Cost No new tool — this is an operational commitment (a second instance, a monitored database, an on-call owner) layered on infrastructure you already run. Skipping it costs nothing until the day it costs everything downstream of the gateway at once.

2.7 Decide if your organisation needs an LLM gateway

The decision framework evaluates whether you have two or more projects or providers before justifying a gateway.

Make a concrete decision about deploying a gateway using the two‑or‑more projects or providers threshold

  1. Review the list of problems a gateway solves – single endpoint, spend ceiling, fallback chain, traceable logs and routing rules – and note which of these currently exist in your stack.
  2. Compare the number of projects and providers you are using against the threshold of two or more for each; if either count is below two, the gateway adds extra service overhead.
  3. Identify any real‑world symptoms such as unallocated spend, rate‑limiting collisions, or unenforceable governance policies that indicate you have crossed the threshold.
  4. Choose to stand up a self‑hosted gateway only if those symptoms are present, otherwise keep the infrastructure at zero.
  • You'll see A single application talking to a single provider with no virtual keys, fallback chain or gateway in front of it
  • Takeaway A gateway is justified only when you have two or more projects or two or more providers, otherwise it adds unnecessary complexity and a new point of failure
  • Check According to the decision framework, what threshold must be met before it is justified to stand up an LLM gateway?
  • Cost Choosing not to deploy a gateway costs nothing today. The cost of deploying one too early is the same operational weight named in the previous lesson, carried for governance nobody is exercising yet.

3You’ll know it worked 30 checkable outcomes in this chapter

  • Send a finance‑related query and see it hit OpenAI GPT‑4; send a coding query and see it go to Gemini
  • Disable the primary provider (e.g., block OpenAI endpoint) and observe that requests are fulfilled by the fallback model (e.g., Gemini)
  • curl http://localhost:8080 returns a 200 response (or model output) instead of connection refused
  • When the primary API key is invalid, the response comes from a fallback model
  • Log shows alternating `deployment_id`s or key identifiers across consecutive calls
  • Dashboard displays non‑zero usage numbers that match known test calls from each team
  • Visiting the instance URL shows the LiteLLM dashboard login page
  • The Usage page lists requests, models used, tokens consumed, and dollar cost; totals match the provider billing statements

30 outcomes in all — one per recipe below.

4FAQ, Tips & How-to 30

one problem, one solution, one action
How-to Everyone

Finance or coding queries go to the right AI model

Semantic routing lets you define topics with example utterances and map each topic to a specific LLM model. When a request arrives, the gateway matches the prompt against the topics and forwards it to the mapped provider, ensuring cost‑effective and accurate responses.

MuleSoft Videos ↗ Lesson → AI-generated
Tip Everyone

Unified Endpoint — simplify multi‑provider access

The gateway exposes a single HTTP endpoint that abstracts away individual API keys and URLs for each LLM provider. Developers authenticate once, and the gateway handles authentication to the underlying models, providing high availability via automatic fallback.

How-to Everyone

When your LLM usage hits its token budget

A token‑rate‑limit policy lets you set maximum tokens per time window for each client or business group. The gateway tracks usage and rejects requests that would exceed the limit, turning budget overruns into HTTP 429 errors.

MuleSoft Videos ↗ Lesson → AI-generated
How-to Everyone

Primary language model fails

If the primary model for a topic cannot be reached, the gateway can automatically route the request to a secondary model defined in the fallback configuration, ensuring uninterrupted service.

MuleSoft Videos ↗ Lesson → AI-generated
How-to Everyone

Want to use different AI models for each client region

Header‑based routing lets you route requests based on custom HTTP headers such as region or client ID. This enables scenarios like EU‑specific models for compliance or per‑customer model selection.

MuleSoft Videos ↗ Lesson → AI-generated
How-to Everyone

Want to connect a new language model to your gateway

An Agent Gateway backend is a custom Kubernetes resource that represents an LLM provider (e.g., Gemini, Anthropic). By creating a secret with the API key and applying a Backend CRD, the gateway can route requests to that model without changing application code.

That DevOps Guy ↗ Lesson → AI-generated
How-to Everyone

Want one endpoint to call many AI models

Agent Gateway’s HTTPRoute can contain multiple rules, each matching a URL prefix and rewriting it before forwarding to a chosen backend. This lets one endpoint serve many models (e.g., /ai/gemini → Gemini, /ai/claude → Anthropic).

That DevOps Guy ↗ Lesson → AI-generated
How-to Everyone

Local testing can’t reach the gateway

When using a local Kind cluster without an external load balancer, `kubectl port-forward` can forward the gateway service’s port to localhost, allowing curl or client apps to reach the gateway as if it were a public endpoint.

That DevOps Guy ↗ Lesson → AI-generated
How-to Everyone

Need an API gateway running in my Kubernetes cluster

Agent Gateway provides two Helm charts: one for its custom resource definitions (CRDs) and another for the control‑plane deployment. Installing both sets up the gateway API objects and the data‑plane proxy in a Kubernetes cluster.

That DevOps Guy ↗ Lesson → AI-generated
How-to Everyone

Need to limit which gateways can be created

A GatewayClass resource defines the type of gateway (e.g., Agent Gateway) that can be instantiated in the cluster. By creating a specific class, you enforce policy such as replica count or load‑balancer type for all Agent Gateways.

That DevOps Guy ↗ Lesson → AI-generated
How-to Everyone

Need to swap AI providers without changing code

The `completion` function from LiteLLM abstracts away provider-specific SDKs. By passing the model name and a standard message payload, you can call OpenAI, Anthropic, Google Gemini, Grok, etc., with identical code.

Krish Naik ↗ Lesson → AI-generated
How-to Everyone

Primary LLM fails

LiteLLM’s `fallbacks` parameter lets you list secondary models. If the primary model raises an error (e.g., 403 or timeout), LiteLLM automatically retries with the next model, ensuring uninterrupted service.

Krish Naik ↗ Lesson → AI-generated
How-to Everyone

Can’t tell what an LLM call spends

LiteLLM maintains a pricing database and provides `completion_cost` which returns input tokens, output tokens, and monetary cost for the request, enabling per‑team budgeting.

Krish Naik ↗ Lesson → AI-generated
How-to Everyone

Repeated LLM prompts feel sluggish

Enabling `cache=True` with `cache_type="local"` stores request/response pairs in RAM. Subsequent identical prompts hit the cache instantly, saving latency and token cost.

Krish Naik ↗ Lesson → AI-generated
How-to Everyone

Coding questions cost too much

Using LiteLLM’s `router` you map abstract task names (e.g., "fast", "code") to concrete provider configurations. The router selects the appropriate model at runtime based on the task label.

Krish Naik ↗ Lesson → AI-generated
How-to Everyone

My requests hit rate‑limit errors

Define several entries for the same provider with different API keys; LiteLLM’s `simple_shuffle` strategy rotates requests, automatically avoiding rate‑limit errors and balancing load.

Krish Naik ↗ Lesson → AI-generated
How-to Everyone

Want one simple spot for all LLM calls in your chain

LangChain provides `ChatLiteLLM` wrapper that accepts the same config as LiteLLM. You can build a prompt template, chain it with other components, and still benefit from routing, fallbacks, cost tracking, etc.

Krish Naik ↗ Lesson → AI-generated
How-to Everyone

Each app has its own hard‑coded AI model URL

The AI Gateway acts as a reverse proxy that presents one API endpoint to all applications, handling request transformation and routing to any configured LLM provider. This removes hard‑coded model URLs and SDK differences, simplifying integration.

Mule Ace Academy ↗ Lesson → AI-generated
How-to Everyone

Don’t know which team is burning AI tokens

The gateway records token counts for every request, tagging them with the originating application or team. This visibility lets finance and engineering pinpoint budget hotspots and enforce spend limits.

Mule Ace Academy ↗ Lesson → AI-generated
How-to Everyone

High AI costs on all queries

By inspecting request payloads (e.g., length, complexity) the gateway can route cheap queries to a low‑cost LLM and send demanding ones to an expensive, high‑performance model, reducing overall spend while preserving quality where needed.

Mule Ace Academy ↗ Lesson → AI-generated
How-to Everyone

Missing API key or PII in LLM calls

The gateway can enforce API‑key validation, PII masking, and access control before any request reaches an LLM, turning governance documents into enforced runtime rules that return HTTP 429 when limits are exceeded.

Mule Ace Academy ↗ Lesson → AI-generated
How-to Everyone

Need to change AI model without rewriting code

Because applications talk only to the gateway, changing the underlying LLM provider is a configuration update in the gateway rather than a code rewrite across multiple services.

Mule Ace Academy ↗ Lesson → AI-generated
How-to Everyone

Multiple AI providers but only one endpoint

LiteLLM acts as a single proxy that normalizes API calls across providers, letting you route requests through one endpoint. Installing it (self‑hosted or via Elestio) gives you immediate control over all your keys and models.

Elestio ↗ Lesson → AI-generated
How-to Everyone

Need to call different AI models from one app

Within LiteLLM you register each provider as a “model” with its own credentials. The gateway then forwards calls to the correct upstream API based on the model selected in the request.

Elestio ↗ Lesson → AI-generated
How-to Everyone

Need to cap a dev team’s monthly budget and request speed

Teams group users and can be assigned spending caps (daily/weekly/monthly) and tokenrate limits. This enforces governance policies automatically, returning HTTP 429 when a limit is exceeded.

Elestio ↗ Lesson → AI-generated
How-to Everyone

Need to hand out LLM credentials safely

Virtual keys are scoped to a team and optionally to specific models, letting you hand out credentials without exposing real provider keys. They inherit the team’s budget and rate limits.

Elestio ↗ Lesson → AI-generated
How-to Everyone

Can't tell which AI provider costs less

The built‑in analytics tab logs every request with model, token count, and cost. By filtering per team or key you can see which provider is cheaper for your workload and adjust routing accordingly.

Elestio ↗ Lesson → AI-generated
How-to Everyone

Want different AI requests to hit the right model

A gateway sits between your app and external LLM APIs, letting you decide per request which model to use based on task type or cost constraints. By configuring routing rules in the gateway, you can automatically send translation jobs to a specialized model and cheap chat to a smaller one.

TensorOps ↗ Lesson → AI-generated
How-to Everyone

Need to enforce a spend cap on AI requests

The gateway can inspect each outgoing request, look up the cost of the target model, and reject or downgrade requests when a predefined budget is exceeded. This turns your governance policy into an enforceable rule that returns HTTP 429 when spending caps are hit.

TensorOps ↗ Lesson → AI-generated
How-to Everyone

My main LLM stops responding

By configuring secondary endpoints, the gateway can detect failed calls (timeouts, 5xx) and transparently retry the request against an alternative vendor or region, preserving uptime without code changes in the application.

TensorOps ↗ Lesson → AI-generated

The same set on /recipes, filtered by tool and role.

5See also

💬 Discuss this chapter

Ask, share, or report — over on the Heidelberg AI community forum.