Schedule icon
Webhook icon
Request icon
Script icon
Set icon
If icon
SlackIncomingWebhook icon
Fail icon
Log icon
OutputValues icon

LiteLLM Proxy Budget Quota & RPM Fallback Circuit Breaker

Audit LiteLLM Proxy budgets and RPM quotas. Detect 429 errors or budget exhaustion, route traffic to fallback models, and record circuit state in Kestra KV.

Categories
AICloud

LiteLLM Proxy is an open-source OpenAI-compatible gateway that centralizes authentication, load balancing, cost tracking, and rate limits across more than 100 large language models (such as Anthropic Claude, OpenAI GPT-4o, and DeepSeek).

Production AI architectures require automated safeguards against sudden token cost surges and upstream provider rate limit spikes. When an engineering team exhausts its allocated monthly budget or encounters HTTP 429 rate limit rejections from foundational model providers, downstream client applications experience cascading timeouts and degraded user experiences.

This blueprint provides an automated circuit breaker and FinOps quota controller that polls LiteLLM Proxy admin endpoints, audits active user key spend against assigned caps, detects rate limit errors, immediately trips the circuit to OPEN, switches traffic to fallback model endpoints, updates Kestra KV store routing state, and dispatches incident alerts to Slack.

How it works

  1. Admin Endpoint Polling: Queries LiteLLM Proxy administration endpoints (/user/info, /model/info, /spend/user, and /health/services) via io.kestra.plugin.core.http.Request with allowFailed: true to prevent workflow crashes during partial API degradation.
  2. Quota & Rate Limit Evaluation: An isolated Python script calculates budget consumption percentages (spend / max_budget * 100), checks for HTTP 429 status codes, and audits model deployment requests-per-minute (RPM) limits.
  3. Circuit Breaker State Machine:
    • CLOSED: Normal operation; routes traffic to primary_model (e.g., claude-3-5-sonnet).
    • OPEN (Budget Warning): Spend reaches or exceeds 90% of budget cap; reroutes traffic to fallback_model (e.g., gpt-4o).
    • OPEN (Hard Cap Exhausted): Spend reaches 100% of budget; switches routing to high-throughput low-cost model (e.g., deepseek-chat).
    • OPEN (Rate Limited): Primary provider returns HTTP 429; trips circuit breaker and switches traffic to fallback_model.
    • HALF_OPEN: Probes recovery during subsequent scheduled execution cycles once error conditions clear.
  4. KV Store State Persistence: Writes litellm_circuit_state, litellm_active_model, and structured spend telemetry into Kestra KV store using io.kestra.plugin.core.kv.Set. Downstream microservices and Kestra subflows read these values to direct prompt requests to healthy endpoints.
  5. Slack Incident Alerting: Dispatches actionable Slack alerts via io.kestra.plugin.slack.notifications.SlackIncomingWebhook with spend figures, active routing targets, and root-cause indicators.

Architecture diagram

flowchart TD
    A[Schedule or Webhook Trigger] --> B[get_user_info HTTP]
    A --> C[get_model_info HTTP]
    A --> D[get_spend_user HTTP]
    A --> E[probe_primary_model_health HTTP]
    B --> F[evaluate_circuit_breaker Python Script]
    C --> F
    D --> F
    E --> F
    F --> G[set_circuit_state_kv KV Set]
    F --> H[set_active_model_kv KV Set]
    F --> I[set_spend_metrics_kv KV Set]
    G --> J{check_circuit_trip_alert Flowable If}
    H --> J
    I --> J
    J -- Circuit OPEN --> K[notify_slack_circuit_trip Slack Webhook]
    K --> L{check_hard_cap_exhaustion Flowable If}
    L -- Hard Cap Breached --> M[fail_on_hard_cap Fail]
    L -- Normal Fallback --> N[export_circuit_breaker_telemetry OutputValues]
    J -- Circuit CLOSED --> O[log_nominal_state Log]
    O --> N

Architecture components

  • HTTP Polling Tasks (get_user_info, get_model_info, get_spend_user, probe_primary_model_health): Collect real-time spend, key allocation, model metadata, and health signals from the LiteLLM Proxy admin API.
  • Circuit Evaluation Engine (evaluate_circuit_breaker): Deterministic Python script that evaluates budget thresholds, detects 429 status codes, and transitions circuit breaker state.
  • KV Store Tasks (set_circuit_state_kv, set_active_model_kv, set_spend_metrics_kv): Persist state in Kestra KV store to decouple gateway monitoring from client application routing.
  • Notification & Protection Gate (check_circuit_trip_alert): Dispatches Slack alerts when circuit state changes and optionally halts executions when hard spending caps are reached.
  • Output Manifest (export_circuit_breaker_telemetry): Emits structured JSON outputs for upstream orchestrators and monitoring dashboards.

Key capabilities

  • Multi-Model Fallback Routing: Dynamically directs downstream calls across Anthropic Claude, OpenAI GPT-4o, and DeepSeek deployments based on real-time availability and spend.
  • Proactive Budget Guardrails: Flags budget exhaustion before total cut-off occurs, allowing graceful degradation rather than hard application failure.
  • Zero-Downtime KV State Management: Decouples monitoring frequency from runtime inference queries by using Kestra KV store as a centralized routing source of truth.
  • Dual Trigger Support: Runs on a continuous 5-minute schedule or receives inbound webhook events from LiteLLM proxy event hooks.

What you get

  • Automated detection of LiteLLM budget exhaustion and provider rate limits.
  • Instant fallback routing across configured model tiers (claude-3-5-sonnet -> gpt-4o -> deepseek-chat).
  • Centralized routing state and spend metrics published to Kestra KV store.
  • Formatted Slack incident alerts with spend figures and root-cause summaries.
  • Configurable circuit breaker thresholds for early warning and hard quota enforcement.

Who it's for

  • Platform Engineers managing enterprise LLM gateway infrastructure and API keys.
  • FinOps Practitioners enforcing departmental AI spend quotas and cost caps.
  • AI / MLOps Engineers requiring automated failover across competing foundational model providers.

Why orchestrate this with Kestra

  • Native KV Store Integration: Stores circuit state and active model endpoints directly in Kestra namespace KV store without requiring external Redis or DynamoDB instances.
  • Reliable Secret Management: Injects LITELLM_MASTER_KEY and SLACK_WEBHOOK_URL securely at runtime via encrypted secrets.
  • Built-in Resilience: Employs allowFailed: true and workflow-level errors handlers to prevent transient network issues from crashing the control loop.
  • Declarative Concurrency: Limits concurrent evaluations using concurrency.limit: 1 and behavior: QUEUE to prevent race conditions during circuit state updates.

Inputs

Name Type Default Description
litellm_proxy_url STRING "http://localhost:4000" Base URL of the LiteLLM Proxy administration endpoint.
user_id STRING "team-data-science" Target user ID or team identifier to audit for spend and rate limits.
primary_model STRING "claude-3-5-sonnet" Default LLM deployment prioritized for production routing.
fallback_model STRING "gpt-4o" First fallback LLM deployment routed during primary rate limit or budget warning.
secondary_fallback_model STRING "deepseek-chat" High-throughput, cost-effective fallback LLM routed during hard budget exhaustion.
budget_exhaustion_threshold_pct FLOAT 90.0 Percentage of budget consumption that trips the warning circuit breaker.
rpm_headroom_threshold_pct FLOAT 10.0 Minimum percentage of remaining RPM capacity required before tripping breaker.
fail_on_exhaustion BOOL false Raise an execution failure when user spend reaches or exceeds 100% of budget cap.
slack_channel STRING "#ai-gateway-ops" Target Slack channel for incident alerts and routing notifications.

Expected outputs

  • {{ outputs.export_circuit_breaker_telemetry.values.circuit_state }}: Current circuit breaker state (CLOSED, OPEN, HALF_OPEN).
  • {{ outputs.export_circuit_breaker_telemetry.values.active_model }}: Active routed model deployment (e.g., claude-3-5-sonnet, gpt-4o, deepseek-chat).
  • {{ outputs.export_circuit_breaker_telemetry.values.trip_reason }}: Explanation for current circuit breaker state.
  • {{ outputs.export_circuit_breaker_telemetry.values.current_spend_usd }}: Current cumulative spend for the target user in USD.
  • {{ outputs.export_circuit_breaker_telemetry.values.max_budget_usd }}: Maximum budget limit assigned to the user in USD.
  • {{ outputs.export_circuit_breaker_telemetry.values.budget_utilization_pct }}: Percentage of maximum budget consumed.
  • {{ outputs.export_circuit_breaker_telemetry.values.rate_limit_detected }}: Boolean flag indicating whether HTTP 429 was detected.
  • {{ outputs.export_circuit_breaker_telemetry.values.evaluated_at }}: ISO-8601 UTC timestamp of the circuit evaluation.

Prerequisites

  • LiteLLM Proxy instance running with Admin API enabled and accessible over HTTP/HTTPS.
  • LiteLLM Master Key configured with administrative permissions for /user/info and /model/info.
  • Slack Incoming Webhook URL configured for incident alerts.

Secrets

  • LITELLM_MASTER_KEY: Master API key for authenticating against LiteLLM Proxy admin endpoints.
  • LITELLM_WEBHOOK_KEY: Secret authentication key for the inbound webhook trigger.
  • SLACK_WEBHOOK_URL: Webhook URL for dispatching incident notifications to Slack.

Quick start

  1. Configure secrets LITELLM_MASTER_KEY, LITELLM_WEBHOOK_KEY, and SLACK_WEBHOOK_URL in your Kestra namespace.
  2. Import this blueprint into your Kestra instance under namespace company.ai.
  3. Set litellm_proxy_url to your LiteLLM Proxy gateway address.
  4. Run a manual execution to audit current spend and initialize litellm_active_model in the KV store.
  5. Enable the periodic_litellm_audit schedule trigger to establish automated 5-minute monitoring.

How to extend

  • Automated LiteLLM Config Patching: Add an io.kestra.plugin.core.http.Request task using POST /model/fallbacks to dynamically update LiteLLM router fallbacks directly inside the proxy daemon.
  • Multi-Tenant Team Iteration: Wrap the inspection tasks inside an io.kestra.plugin.core.flow.Loop loop to evaluate spend caps across all active LiteLLM user accounts in a single run.
  • PagerDuty Incident Escalation: Integrate io.kestra.plugin.pagerduty.notifications.PagerDutyAlert when hard budget exhaustion occurs to alert on-call engineering leads.

Links

See How

New to Kestra?

Use blueprints to kickstart your first workflows.