Enforcing model access, budgets, and RPM limits in LiteLLM
Configure LiteLLM Proxy v1.112.0 teams and virtual keys to enforce model allowlists (403), RPM limits (429), and budgets (422), verified against PostgreSQL.
When multiple backend services share one LiteLLM Proxy, pairing teams (
/team/new) with service-scoped virtual keys (/key/generate) blocks unauthorized models (403), excess request rates (429), and exhausted budgets (422) before traffic reaches upstream models. Onghcr.io/berriai/litellm:v1.112.0withpostgres:17-alpine, in-memory budget blocking fired in0.009swhile PostgreSQL-backed/key/inforeflected the updated spend after13.2s.
Every config and output below was verified on
ghcr.io/berriai/litellm:v1.112.0,postgres:17-alpine, and a local deterministic OpenAI-compatible upstream server returning fixed100/40token usage. This setup covers a single proxy replica; multi-replica Redis rate-limit sync and Enterprise SSO/RBAC are out of scope.
How team and virtual key boundaries work
Suppose a platform team runs a shared LLM gateway for two internal workloads: a customer ticket classifier (support-triage-svc) and a pull request bot (code-review-bot). Without per-service boundaries, three failure modes show up quickly: the low-cost classifier accidentally calls an expensive reasoning model, a retry loop burns through the gateway’s rate limit, or one noisy bot drains the entire team’s monthly budget.
LiteLLM Proxy models these boundaries in two PostgreSQL-backed layers under the master key: a Team (/team/new) and Virtual Keys (/key/generate). When a request hits /v1/chat/completions, the proxy checks key authentication, the key’s model allowlist, its requests-per-minute cap (rpm_limit), and both key and team budgets (max_budget) before forwarding anything upstream.
flowchart TD
A["Client Request<br/>(Bearer Virtual Key)"] --> B["Auth & Model Allowlist"]
B -->|"Model denied"| B1["HTTP 403<br/>key_model_access_denied"]
B -->|"Allowed"| C["RPM Limit Check<br/>(rpm_limit)"]
C -->|"Exceeded"| C1["HTTP 429<br/>throttling_error"]
C -->|"Within limit"| D["Key & Team Budget Check<br/>(max_budget)"]
D -->|"Exceeded"| D1["HTTP 422<br/>budget_exceeded"]
D -->|"Within budget"| E["Upstream LLM Call"]
Putting these controls in a proxy trades extra infrastructure for centralized policy management. Here is how it compares against simpler alternatives:
| Option | Direct provider API keys | Per-service app limiters | LiteLLM Proxy teams & virtual keys |
|---|---|---|---|
| Model access control | Requires separate vendor projects | Needs code/config changes and redeploys | Scoped immediately via models per key |
| Shared budget & RPM | Hard to isolate per service | Cannot sum spend across services easily | Enforces per-key caps and team budgets together |
| Operational overhead | None | Low (grows if adding shared Redis) | Requires proxy container + PostgreSQL |
| Best fit | Single app or quick prototype | Short-term guardrails before a gateway | Two or more services sharing models and spend |
Don’t add LiteLLM Proxy and PostgreSQL if you only run one backend service against a single model provider. You’ll introduce an extra network hop and a database dependency when the provider’s own project budget cap is enough. The same applies to latency-critical streaming paths where you don’t need cross-service quota isolation or centralized spend accounting.
Setting up LiteLLM Proxy with PostgreSQL
Virtual keys and team budgets require a persistent database. The compose.yaml below waits for postgres:17-alpine to pass pg_isready, then starts ghcr.io/berriai/litellm:v1.112.0 on port 14001. Keep the master key and database password in environment variables rather than committing them to the file.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# compose.yaml
services:
postgres:
image: postgres:17-alpine
environment:
POSTGRES_DB: litellm
POSTGRES_USER: litellm
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
healthcheck:
test: ["CMD-SHELL", "pg_isready -U litellm -d litellm"]
interval: 2s
timeout: 3s
retries: 20
litellm:
image: ghcr.io/berriai/litellm:v1.112.0
depends_on:
postgres:
condition: service_healthy
ports:
- "14001:4000"
environment:
LITELLM_MASTER_KEY: ${LITELLM_MASTER_KEY}
DATABASE_URL: postgresql://litellm:${POSTGRES_PASSWORD}@postgres:5432/litellm
volumes:
- ./config.yaml:/app/config.yaml:ro
command: ["--config", "/app/config.yaml", "--port", "4000"]
extra_hosts:
- "host.docker.internal:host-gateway"
Next, config.yaml defines two logical model aliases: triage-fast and review-deep. To make token counts and upstream hit counts 100% deterministic, both aliases point to a local Python OpenAI-compatible upstream server on port 18101. That server returns prompt_tokens: 100 and completion_tokens: 40 on every 200 response and records exact call counts per model ID.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# config.yaml
model_list:
- model_name: triage-fast
litellm_params:
model: openai/triage-fast-v1
api_base: http://host.docker.internal:18101/v1
api_key: dummy-upstream-key
model_info:
id: triage-fast-v1
input_cost_per_token: 0.000001
output_cost_per_token: 0.0000045
- model_name: review-deep
litellm_params:
model: openai/review-deep-v1
api_base: http://host.docker.internal:18101/v1
api_key: dummy-upstream-key
model_info:
id: review-deep-v1
input_cost_per_token: 0.000001
output_cost_per_token: 0.0000045
general_settings:
master_key: os.environ/LITELLM_MASTER_KEY
database_url: os.environ/DATABASE_URL
store_model_in_db: false
With input pricing at $0.000001 per token and output pricing at $0.0000045 per token, every completed call costs exactly 100 × 0.000001 + 40 × 0.0000045 = $0.00028. That fixed cost lets us verify the exact request where budget enforcement trips.
Creating the team and service virtual keys
Once the proxy is healthy, use the master key to create the platform-ai team and issue two service keys under it:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# 1. Create the shared team (both models allowed, $1.00 team budget)
TEAM_ID=$(curl -sS -X POST http://127.0.0.1:14001/team/new \
-H "Authorization: Bearer $LITELLM_MASTER_KEY" \
-H "Content-Type: application/json" \
-d '{
"team_alias": "platform-ai",
"models": ["triage-fast", "review-deep"],
"max_budget": 1.0
}' | jq -r '.team_id')
# 2. Issue support-triage-svc key (triage-fast only, 2 requests/min)
TRIAGE_KEY=$(curl -sS -X POST http://127.0.0.1:14001/key/generate \
-H "Authorization: Bearer $LITELLM_MASTER_KEY" \
-H "Content-Type: application/json" \
-d "{
\"team_id\": \"$TEAM_ID\",
\"key_alias\": \"support-triage-svc\",
\"models\": [\"triage-fast\"],
\"rpm_limit\": 2
}" | jq -r '.key')
# 3. Issue code-review-bot key (both models, $0.0005 key budget)
REVIEW_KEY=$(curl -sS -X POST http://127.0.0.1:14001/key/generate \
-H "Authorization: Bearer $LITELLM_MASTER_KEY" \
-H "Content-Type: application/json" \
-d "{
\"team_id\": \"$TEAM_ID\",
\"key_alias\": \"code-review-bot\",
\"models\": [\"triage-fast\", \"review-deep\"],
\"max_budget\": 0.0005
}" | jq -r '.key')
A key’s models array narrows access inside the team’s allowed set. support-triage-svc can only reach triage-fast at up to 2 requests per minute, while code-review-bot can call both aliases until its $0.0005 key cap runs out.
Verifying 403, 429, and 422 enforcement
I ran three checks against the live proxy using refund-classification and PR-review prompts, comparing both the HTTP responses and the upstream server’s /_admin/stats counter after each step.
1. Model allowlist (403 key_model_access_denied)
Querying GET /v1/models with each key confirms that discovery matches enforcement: $TRIAGE_KEY only lists ["triage-fast"], whereas $REVIEW_KEY lists ["triage-fast", "review-deep"].
Calling review-deep with $TRIAGE_KEY immediately returns HTTP 403, and the upstream counter for review-deep-v1 stays at 0. Sending the same request with $REVIEW_KEY returns HTTP 200 with x-litellm-response-cost: 0.00028 and increments review-deep-v1 to 1.
1
2
3
4
5
6
7
8
{
"error": {
"message": "The requested model 'review-deep' is not available for this API key, or the model name is invalid. Check the models available to you and try again.",
"type": "key_model_access_denied",
"param": "model",
"code": "403"
}
}
2. Requests-per-minute cap (429 throttling_error)
With rpm_limit: 2 on support-triage-svc, sending three consecutive requests to triage-fast within one minute produces 200 on calls #1 and #2 ($0.00028 each) and HTTP 429 on call #3. The upstream server’s triage-fast-v1 count stops at 2, confirming the proxy drops the third request before it ever leaves the gateway.
1
2
3
4
5
6
7
8
{
"error": {
"message": "Rate limit exceeded for api_key: <key_hash>. Limit type: requests. Current limit: 2, Remaining: 0. Limit resets at: 2026-12-02 13:12:25 UTC",
"type": "throttling_error",
"param": null,
"code": "429"
}
}
3. Key and team budget caps (422 budget_exceeded) and DB sync lag
code-review-bot has max_budget: 0.0005, and each call costs $0.00028. Its second call still succeeds with HTTP 200, pushing in-memory cumulative spend to $0.00056—above the $0.0005 cap.
A third call sent 0.009s later doesn’t return 400 or 429 as some older docs suggest. On v1.112.0, LiteLLM Proxy blocks it immediately with HTTP 422 (type: "budget_exceeded"), and the upstream review-deep-v1 counter remains at 2:
1
2
3
4
5
6
7
8
{
"error": {
"message": "Budget has been exceeded! Key=code-review-bot (sk-...<redacted>) Current cost: 0.0005600000000000029, Max budget: 0.0005",
"type": "budget_exceeded",
"param": null,
"code": "422"
}
}
What surprised me most was the gap between enforcement and database visibility. Even though the proxy blocked the third request in 0.009s using in-memory tracking, polling GET /key/info every second returned spend: 0.0 from t=0s through t=10s. The PostgreSQL-backed value flipped to $0.00056 at t=13.2s, matching the proxy’s background batch-write cycle. Once flushed, GET /team/info for platform-ai reported $0.00112—the exact sum of both keys ($0.00056 + $0.00056).
To verify team-level blocking independently, I also created a separate qa-sandbox team with max_budget: 0.0002 and a key without its own cap. Call #1 returned 200 ($0.00028), and call #2 failed with the same HTTP 422 (Budget has been exceeded! Team=...).
Figure 1. Verification run against LiteLLM Proxy v1.112.0 and the local OpenAI-compatible upstream server showing 403 model denial, 429 RPM throttling, 422 budget blocking, and the 13.2s /key/info DB sync delay.
Production caveats and checklist
Running the full sequence exposed three details that can trip up production rollouts if you only read the quickstart.
Watch out for pre-call budget reservations on tiny team caps: In an earlier run where
platform-aihadmax_budget: 0.005, LiteLLM rejected a second request with422(team budget exceeded) even though actual cumulative spend was only$0.00056. The proxy reserves an estimated max cost before executing the call, so tiny team caps can block valid traffic prematurely. Always size team and key budgets well above the worst-case cost of a single request.
- Expect
422, not429, for budget exhaustion: Onv1.112.0, rate limits return429(throttling_error) while budget exhaustion returns422(budget_exceeded). Branch your client retry logic and alerts onerror.typeso you retry rate limits with backoff but stop immediately on budget errors. - Treat
max_budgetas a soft cap: Any request admitted before the threshold crosses—like call #2 pushing$0.00028to$0.00056against a$0.0005limit—still finishes. Under high concurrency, several in-flight calls can land simultaneously and overshoot the cap slightly. - Account for async DB flush in tests and dashboards: In-memory enforcement fires within milliseconds, while
/key/infoand/team/infolag by the proxy’s batch-write interval (13.2sin this test). Don’t assume spend tracking is broken if an integration test reads0.0right after a call completes.
Before rolling this setup into production, verify these four items:
- Assign each service its own
key_aliasand least-privilegemodelslist so background jobs can’t call expensive models by mistake. - Set team
max_budgetwell above single-request worst-case cost, and pair it with per-keyrpm_limitandmax_budgetcaps. - Distinguish
403(key_model_access_denied),429(throttling_error), and422(budget_exceeded) in client interceptors and alerting rules. - Back up PostgreSQL with health checks, and plan Redis-backed state sync before scaling LiteLLM Proxy beyond a single replica.