<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Yusuf Can Ekin on Medium]]></title>
        <description><![CDATA[Stories by Yusuf Can Ekin on Medium]]></description>
        <link>https://medium.com/@yusufcanekiin?source=rss-7ead6ef1c996------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*3bVqjc1F7lu_Dsq3</url>
            <title>Stories by Yusuf Can Ekin on Medium</title>
            <link>https://medium.com/@yusufcanekiin?source=rss-7ead6ef1c996------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 18:44:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@yusufcanekiin/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Scaling LLM Usage with LiteLLM: Monitoring, Quotas, and Spend Management]]></title>
            <link>https://engineering.getmidas.com/scaling-llm-usage-with-litellm-monitoring-quotas-and-spend-management-04b7d818a782?source=rss-7ead6ef1c996------2</link>
            <guid isPermaLink="false">https://medium.com/p/04b7d818a782</guid>
            <dc:creator><![CDATA[Yusuf Can Ekin]]></dc:creator>
            <pubDate>Tue, 03 Feb 2026 15:44:20 GMT</pubDate>
            <atom:updated>2026-02-03T15:44:20.177Z</atom:updated>
            <content:encoded><![CDATA[<p>LLMs quickly became a core part of how we build at <strong>Midas. </strong>First for internal prototypes, then for production features, and eventually for everything in between. The problem was simple: <strong>our infrastructure didn’t scale with our curiosity.</strong></p><p>At some point, we realized we couldn’t answer the most basic questions:<br> <strong>How much are we spending? Where is it coming from? Which team owns it?</strong></p><p>Local experiments and production workloads looked the same. Provider keys were shared across projects. Logs lived in different places. When spend spiked, we couldn’t trace it to a team, a deployment, or even a single model. And when we tried optimizations — smaller models, prompt tweaks, batching — we had no reliable way to confirm whether any of it actually worked.</p><p>In order to address all these, we built a unified LLM control plane using LiteLLM. In this guide, we’ll show how LiteLLM helped us <strong>centralize observability</strong>, <strong>track spend in real time</strong>, <strong>enforce per-environment limits</strong>, and <strong>standardize every provider behind one gateway</strong>. The result is an LLM platform at Midas that you can measure, govern, and improve with confidence.</p><h3>What is LiteLLM?</h3><p>LiteLLM is an <strong>open-source AI gateway</strong> that sits between our applications and multiple LLM providers, giving Midas a <strong>single, consistent entry point</strong> for all LLM traffic.</p><p>It supports familiar <strong>OpenAI-style APIs </strong>such as /chat/completions, /completions, /embeddings, /audio, and the newer Responses API—so most existing OpenAI clients and SDKs can be used with <strong>minimal or no code changes</strong>.</p><p>At the same time, LiteLLM does not force a single API style. It can also act as a drop-in endpoint for <strong>native provider clients</strong>. Anthropic, Gemini, and other official SDKs can be pointed to LiteLLM by changing only the base URL and API key. From the client’s perspective, it still talks to the original provider.</p><pre>import anthropic<br><br>client = anthropic.Anthropic(<br>    api_key=&quot;LITELLM_VIRTUAL_KEY&quot;,<br>    base_url=&quot;https://litellm.your-domain.com&quot;<br>)</pre><p>Under the hood, LiteLLM routes requests to providers like OpenAI, Anthropic, Google Gemini, and AWS Bedrock, handling provider-specific parameters, retries, and routing logic.</p><p>In our setup at Midas, this also includes internally hosted models, which LiteLLM exposes through the same interface and governance layer as external providers.</p><p>LiteLLM also ships with a built-in <strong>dashboard</strong> that we actively use to understand how LLM traffic behaves across environments. It gives us a clear view of total requests, success rates, token consumption, and spend trends.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A-EfsA6dTjnthm6hOJLcXw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uycANQzn-s0sNk0cljJ_hA.png" /></figure><p>For full details on capabilities, configuration, and advanced features, you can check out:</p><ul><li><strong>GitHub repo:</strong> <a href="https://github.com/BerriAI/litellm">https://github.com/BerriAI/litellm</a></li><li><strong>Documentation:</strong> <a href="https://docs.litellm.ai/">https://docs.litellm.ai</a></li></ul><h3>High-Level Architecture</h3><p>Before getting into Helm charts, values files, or autoscaling, it’s worth stepping back to see <strong>how LiteLLM fits into Midas’s platform as a whole</strong>. The diagram below shows the end-to-end path of an LLM request as it moves through our infrastructure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EptLRUWa4vZxRz3zwccwWQ.png" /></figure><p>On the left side of the system, a variety of internal Midas workloads generate LLM traffic, <strong>llm-powered microservices/workers, ai-agent applications, scheduled background jobs, data-science projects</strong>. All of these send their requests through the <strong>cluster ingress</strong>, which routes traffic to a <strong>load balancer</strong> and then into the <strong>LiteLLM proxy deployment</strong>. Each environment (development, staging, production) runs its own fully isolated LiteLLM stack, managed through <strong>Helm and ArgoCD</strong>.</p><p>Every request to LiteLLM is authenticated using a <strong>virtual key</strong>. These keys let us enforce <strong>per-environment budgets and quotas</strong>, and — just as importantly — distinguish <strong>local development</strong>, <strong>staging workloads</strong>, and <strong>real production traffic</strong> across Midas teams. Behind the proxy, LiteLLM connects to two core infrastructure components:</p><ul><li><strong>PostgreSQL</strong>, powering request logs, spend tracking, and analytics</li><li><strong>Redis</strong>, used for caching responses and reducing unnecessary provider calls</li></ul><p>Once a request is validated and processed, LiteLLM forwards it to the correct provider based on the configured model. These providers include <strong>OpenAI, Anthropic, Google Gemini, AWS Bedrock, Perplexity, XAI, Azure</strong>, and others — all accessible through a <strong>single gateway</strong>. Authentication is handled with a mix of <strong>API keys</strong> and <strong>IAM roles</strong>. Bedrock models, for example, are accessed entirely through IAM, which removes the need for long-lived secrets.</p><p>Overall, this architecture gives Midas a <strong>single, consistent, and highly observable path</strong> for all LLM traffic. It centralizes <strong>monitoring and cost visibility</strong>, simplifies <strong>provider integrations</strong>, and ensures that each environment behaves predictably. Most importantly, it forms the foundation we rely on to build <strong>rate limits</strong>, <strong>budgets</strong>, <strong>model governance tools</strong>, and <strong>production-grade reliability</strong> on top of LiteLLM.</p><h3>Why We Separated Environments</h3><p>As LiteLLM became the <strong>single entry point for all LLM traffic at Midas</strong>, we needed strict isolation between experimentation, development, staging, and real production usage. Mixing these workloads would lead to <strong>noisy metrics</strong>, <strong>unpredictable performance</strong>, and unnecessary operational risk. To avoid this, we deployed LiteLLM into <strong>four fully separate environments</strong>, each serving a distinct purpose.</p><h4>Testing — Load &amp; Stress Experiments</h4><p>Our testing cluster is dedicated entirely to high-load scenarios: <strong>Locust traffic generation, WireMock simulations, and concurrency experiments</strong>. It uses fake models, reduced logging, and a separate node group so that load tests <strong>never impact real workloads</strong>. This is where we intentionally try to break things.</p><h4>Development — Local &amp; Internal Usage</h4><p>The dev environment is reachable from developer laptops and internal tools. It supports <strong>prototyping, debugging, and early-stage feature experiments</strong> with softer rate limits and lower budgets. This keeps experimentation <strong>cheap, fast, and safe</strong>, without risking shared resources.</p><h4>Staging — Pre-Production Validation</h4><p>Staging mirrors production as closely as possible but remains isolated from user traffic. <strong>Model changes, configuration updates, quota adjustments, and LiteLLM version upgrades</strong> are validated here before rollout. Only staging applications can reach this environment, ensuring that what we deploy to production has already survived a realistic rehearsal.</p><h4>Production — Real User Traffic Only</h4><p>Production is strictly isolated by design:</p><ul><li><strong>Not reachable from local machines</strong></li><li><strong>No peering with non-prod clusters</strong></li><li><strong>Enforced budgets, quotas, and strong alerting</strong></li><li><strong>Limited access to the control plane</strong></li></ul><p>This prevents accidental load from internal tools or experiments and ensures <strong>consistent reliability for Midas users</strong>. Production is quiet, predictable, and guarded, exactly how we want it.</p><h3>Configuration Deep Dive</h3><p>This section covers how we configure LiteLLM in different environments: models, alerting, caching, databases, resources, environment differences and advanced features like budgets and virtual keys.</p><h4>Configuration File Structure</h4><p>LiteLLM uses a layered configuration with a few core sections:</p><pre>proxy_config:<br>  model_list: []        # AI models configuration<br>  general_settings: {}  # Proxy behavior settings<br>  litellm_settings: {}  # LiteLLM specific settings<br>  router_settings: {}   # Timeouts and routing behavior<br>db: {}                  # Database configuration<br>resources: {}           # Kubernetes resource limits<br>serviceAccount: {}      # AWS IAM integration<br>replicaCount: 3        # Number of LiteLLM pods</pre><h4>1. Secrets &amp; Credential Management (Vault + Kubernetes)</h4><p>All sensitive configuration in our LiteLLM setup is <strong>never committed to Git</strong> and <strong>never stored directly in Helm values</strong>.</p><p>Instead, Midas follows a consistent pattern across all environments:</p><ul><li><strong>HashiCorp Vault</strong> is the source of truth for secrets</li><li>Secrets are synced into <strong>Kubernetes Secrets</strong></li><li>LiteLLM consumes them <strong>only via environment variables</strong></li></ul><p>This keeps our deployments reproducible, auditable, and safe, while still allowing per-environment isolation.</p><h4>What We Treat as Secrets</h4><p>Examples include:</p><ul><li>LLM provider API keys (OpenAI, Anthropic, Google, etc.)</li><li>LiteLLM master_key</li><li>PostgreSQL credentials</li><li>Redis credentials</li><li>Any internal model authentication tokens</li></ul><h4>How Secrets Flow</h4><ol><li><strong>Vault</strong></li></ol><ul><li>Secrets are stored under environment-scoped paths</li><li>Access is controlled via Kubernetes auth</li></ul><p><strong>2. Kubernetes Secrets</strong></p><ul><li>Secrets are synced into each cluster as Secret objects</li><li>Each environment (dev / staging / prod) has its own namespace and secret set</li></ul><p><strong>3. LiteLLM Pods</strong></p><ul><li>Secrets are exposed as environment variables</li><li>Helm values reference them using os.environ/...</li></ul><p>This means the same Helm chart can be reused everywhere, while behavior changes purely based on injected secrets.</p><p><strong>Rotating credentials </strong>is also straightforward: update Vault, sync, and roll pods. Just like that, no Helm changes required.</p><h4>2. Model Configuration</h4><p>The heart of LiteLLM is proxy_config.model_list, where you define all available AI models.</p><h4>Basic Model Configuration</h4><pre>proxy_config:<br>  model_list:<br>    # Simple OpenAI model<br>    - model_name: gpt-4o<br>      litellm_params:<br>        model: gpt-4o<br>        api_key: &quot;os.environ/OPENAI_API_KEY&quot;<br>    # Anthropic Claude with specific version<br>    - model_name: claude-3-5-sonnet<br>      litellm_params:<br>        model: anthropic/claude-3-5-sonnet-20241022<br>        api_key: &quot;os.environ/ANTHROPIC_API_KEY&quot;<br>    # Google Gemini<br>    - model_name: gemini-2.0-flash<br>      litellm_params:<br>        model: gemini/gemini-2.0-flash<br>        api_key: &quot;os.environ/GOOGLE_AI_API_KEY&quot;</pre><h4>AWS Bedrock (No API Keys Needed)</h4><p>We use IAM Roles for Service Accounts (IRSA). Bedrock calls are authenticated via IAM instead of static keys:</p><pre>serviceAccount:<br>  create: true<br>  name: &quot;litellm&quot;<br>  annotations:<br>    eks.amazonaws.com/role-arn: &quot;arn:aws:iam::example:role/litellm-example-role&quot;<br>proxy_config:<br>  model_list:<br>    # Bedrock models use IAM authentication<br>    - model_name: bedrock/claude-sonnet-4-5<br>      litellm_params:<br>        model: bedrock/eu.anthropic.claude-sonnet-4-5-20250929-v1:0<br>    - model_name: bedrock/claude-haiku-4-5<br>      litellm_params:<br>        model: bedrock/eu.anthropic.claude-haiku-4-5-20251001-v1:0</pre><h4>Model Aliases</h4><p>We create friendly names for commonly used models to make version upgrades easier:</p><pre>proxy_config:<br>  model_list:<br>    # Primary model with specific version<br>    - model_name: claude-3-7-sonnet-20250219<br>      litellm_params:<br>        model: anthropic/claude-3-7-sonnet-20250219<br>        api_key: &quot;os.environ/ANTHROPIC_API_KEY&quot;<br>    # Alias pointing to latest<br>    - model_name: claude-3-7-sonnet<br>      litellm_params:<br>        model: anthropic/claude-3-7-sonnet-20250219<br>        api_key: &quot;os.environ/ANTHROPIC_API_KEY&quot;<br>    # Short alias for convenience<br>    - model_name: claude-3.7<br>      litellm_params:<br>        model: anthropic/claude-3-7-sonnet-20250219<br>        api_key: &quot;os.environ/ANTHROPIC_API_KEY&quot;</pre><h4>3. General Settings — Proxy Behavior</h4><h4>Master Key and Authentication</h4><pre>proxy_config:<br>  general_settings:<br>    master_key: os.environ/PROXY_MASTER_KEY</pre><h4>Spend Tracking and Logging</h4><pre>proxy_config:<br>  general_settings:<br>    # Store full prompts and responses for auditing<br>    store_prompts_in_spend_logs: true<br>    <br>    # Automatic cleanup of old logs<br>    maximum_spend_logs_retention_period: &quot;30d&quot;<br>    maximum_spend_logs_retention_interval: &quot;1d&quot;</pre><h4>Alerting Configuration</h4><p>We use multi-channel alerting (Slack and a third-party incident management webhook) for production.</p><pre>proxy_config:<br>  general_settings:<br>    alerting: [&quot;slack&quot;]<br>    alerting_threshold: 300          # 5 minutes<br>    spend_report_frequency: &quot;1d&quot;<br>alert_types:<br>      # Performance alerts<br>      - &quot;llm_too_slow&quot;<br>      - &quot;cooldown_deployment&quot;<br>      - &quot;outage_alerts&quot;<br>      - &quot;region_outage_alerts&quot;<br>      # Cost alerts<br>      - &quot;budget_alerts&quot;<br>      - &quot;spend_reports&quot;<br>      - &quot;failed_tracking_spend&quot;<br>      - &quot;daily_reports&quot;<br>      # System alerts<br>      - &quot;db_exceptions&quot;<br>      # Management alerts<br>      - &quot;new_virtual_key_created&quot;<br>      - &quot;virtual_key_updated&quot;<br>      - &quot;virtual_key_deleted&quot;<br>    # Multi channel alerting (production only)<br>    alert_to_webhook_url:<br>      &quot;llm_too_slow&quot;:<br>        - &quot;https://hooks.slack.com/services/.../EXAMPLE_CHANNEL&quot;<br>        - &quot;https://example.com/incident-management-webhook&quot;<br>      &quot;budget_alerts&quot;: <br>        - &quot;https://hooks.slack.com/services/.../EXAMPLE_CHANNEL&quot;<br>      &quot;db_exceptions&quot;:<br>        - &quot;https://hooks.slack.com/services/.../EXAMPLE_CHANNEL&quot;<br>        - &quot;https://example.com/incident-management-webhook&quot;</pre><p><strong>Environment specific alerting:</strong></p><ul><li>Dev: Slack only</li><li>Staging: Slack and third-party incident management webhook at warning level</li><li>Production: Slack and third-party incident management webhook at critical / P1 level</li></ul><h4>4. LiteLLM Settings</h4><h4>Caching with Redis</h4><p>Caching reduces latency and API costs by returning responses for repeated requests from Redis.</p><pre>proxy_config:<br>  litellm_settings:<br>    cache: true<br>    cache_params:<br>      type: redis<br>      redis_startup_nodes:<br>        - host: &quot;example.redis.cluster.host.com&quot;<br>          port: 6379<br>      ttl: 3600   # Cache for 1 hour</pre><p>How this helps:</p><ul><li>Identical requests return cached responses instantly</li><li>Avoids duplicate calls to OpenAI, Anthropic and others</li><li>Reduces latency from seconds to milliseconds</li></ul><h4>Prometheus Metrics (Native)</h4><p>LiteLLM exposes Prometheus-compatible metrics directly from the proxy. Instead of relying on OpenTelemetry auto-instrumentation for metrics collection, we scrape LiteLLM’s native /metrics endpoint and build dashboards + autoscaling signals on top of that.</p><p>This keeps observability simpler:</p><ul><li>No per-pod auto-instrumentation injection</li><li>No OTEL agent overhead</li><li>Metrics are consistent across environments and directly usable by Prometheus, Grafana, alerting rules, and KEDA</li></ul><h4>Router Settings</h4><pre>proxy_config:<br>  router_settings:<br>    timeout: 6000  # For long running requests</pre><h4>5. Database Configuration</h4><p>LiteLLM uses PostgreSQL for:</p><ul><li>Virtual key storage</li><li>Spend tracking</li><li>User and team management</li><li>Request logging</li></ul><pre>db:<br>  useExisting: true<br>  url: postgresql://$(DATABASE_USERNAME):$(DATABASE_PASSWORD)@$(DATABASE_HOST)/$(DATABASE_NAME)<br>  database: litellm<br>  endpoint: db-example.region.example.example.com<br>  secret:<br>    name: secret-name<br>    usernameKey: DB_USERNAME<br>    passwordKey: DB_PASSWORD</pre><h4>6. Resource Configuration</h4><p>Standard configuration across environments:</p><pre>replicaCount: 3   # Minimum for high availability<br>resources:<br>  limits:<br>    cpu: 2000m    # 2 CPU cores<br>    memory: 4Gi   # 4GB RAM<br>  requests:<br>    cpu: 2000m    # Guaranteed QoS<br>    memory: 4Gi</pre><p><strong>Why these values:</strong></p><ul><li>2 CPU cores and 4 GB RAM combination is what LiteLLM suggests</li><li>3 replicas ensure availability during rolling updates</li></ul><h4>7. Environment Specific Configurations</h4><h4>Testing Environment</h4><p>Focus on load testing and debugging, and we assigned a seperate node group for our test setup.</p><pre>proxy_config:<br>  model_list:<br>    # Fake endpoint for integration tests<br>    - model_name: &quot;fake-openai-endpoint&quot;<br>      litellm_params:<br>        model: openai/any<br>        api_base: http://wiremock.testing.svc.cluster.local:9021<br>        api_key: &quot;test&quot;<br>  general_settings:<br>    use_redis_transaction_buffer: true<br>    disable_error_logs: true<br>    database_connection_pool_limit: 20<br>  router_settings:<br>    timeout: 6000<br><br>nodeSelector:<br>  workload: example-deployment<br>tolerations:<br>  - key: workload<br>    operator: Equal<br>    value: example-deployment<br>    effect: NoSchedule</pre><h4>Production Environment</h4><p>Production has full alerting and observability:</p><pre>proxy_config:<br>  general_settings:<br>    store_prompts_in_spend_logs: true<br>    maximum_spend_logs_retention_period: &quot;30d&quot;<br>    alerting: [&quot;slack&quot;]<br>    alert_to_webhook_url:<br>      &quot;llm_too_slow&quot;:<br>        - &quot;https://hooks.slack.com/services/.../EXAMPLE_CHANNEL&quot;<br>        - &quot;https://example.com/incident-management-webhook&quot;</pre><h3>Load Testing LiteLLM</h3><p>Before putting LiteLLM on the critical path for production traffic, we wanted to understand how it behaves under sustained load. In particular, we were interested in three questions:</p><ul><li>How many parallel requests can a single LiteLLM pod handle comfortably</li><li>What happens to latency once that limit is exceeded</li><li>Whether we should scale on CPU, memory or on a more direct request based signal</li></ul><p>To isolate LiteLLM from external provider behavior, we decided to load test against a <strong>fake LLM backend</strong> instead of a real provider.</p><h4>Setting Up a Fake LLM Backend with WireMock</h4><p>In our testing environment, we run a WireMock service that mimics an LLM provider. Rather than sending traffic to OpenAI or Anthropic, LiteLLM forwards requests to WireMock, which returns deterministic JSON responses with configurable latency.</p><p><strong>Example mappings used in our setup:</strong></p><pre>{<br>  &quot;request&quot;: { &quot;method&quot;: &quot;POST&quot;, &quot;url&quot;: &quot;/v1/chat/completions&quot; },<br>  &quot;response&quot;: {<br>    &quot;status&quot;: 200,<br>    &quot;bodyFileName&quot;: &quot;responses/openai_v1_chat_response.json&quot;,<br>    &quot;headers&quot;: { &quot;Content-Type&quot;: &quot;application/json&quot; },<br>    &quot;fixedDelayMilliseconds&quot;: 30000<br>  }<br>}</pre><pre>{<br>  &quot;request&quot;: { &quot;method&quot;: &quot;POST&quot;, &quot;url&quot;: &quot;/v1/completions&quot; },<br>  &quot;response&quot;: {<br>    &quot;status&quot;: 200,<br>    &quot;bodyFileName&quot;: &quot;responses/openai_v1_completions_response.json&quot;,<br>    &quot;headers&quot;: { &quot;Content-Type&quot;: &quot;application/json&quot; },<br>    &quot;fixedDelayMilliseconds&quot;: 30000<br>  }<br>}</pre><p>We also mapped the legacy OpenAI-compatible endpoints:</p><pre>{<br>  &quot;request&quot;: { &quot;method&quot;: &quot;POST&quot;, &quot;url&quot;: &quot;/chat/completions&quot; },<br>  &quot;response&quot;: {<br>    &quot;status&quot;: 200,<br>    &quot;bodyFileName&quot;: &quot;responses/openai_chat_response.json&quot;,<br>    &quot;headers&quot;: { &quot;Content-Type&quot;: &quot;application/json&quot; },<br>    &quot;fixedDelayMilliseconds&quot;: 30000<br>  }<br>}</pre><pre>{<br>  &quot;request&quot;: { &quot;method&quot;: &quot;POST&quot;, &quot;url&quot;: &quot;/completions&quot; },<br>  &quot;response&quot;: {<br>    &quot;status&quot;: 200,<br>    &quot;bodyFileName&quot;: &quot;responses/openai_completions_response.json&quot;,<br>    &quot;headers&quot;: { &quot;Content-Type&quot;: &quot;application/json&quot; },<br>    &quot;fixedDelayMilliseconds&quot;: 30000<br>  }<br>}</pre><p><strong>WireMock response files</strong> contained static JSON objects shaped like real LLM responses, for example:</p><pre>{<br>  &quot;id&quot;: &quot;chatcmpl-mock-123&quot;,<br>  &quot;object&quot;: &quot;chat.completion&quot;,<br>  &quot;model&quot;: &quot;gpt-4-mock&quot;,<br>  &quot;choices&quot;: [<br>    { &quot;message&quot;: { &quot;role&quot;: &quot;assistant&quot;, &quot;content&quot;: &quot;Hello there!&quot; } }<br>  ]<br>}</pre><p>The model configuration for this looks roughly like this:</p><pre>proxy_config:<br>  model_list:<br>    - model_name: &quot;fake-openai-endpoint&quot;<br>      litellm_params:<br>        model: openai/any<br>        api_base: http://wiremock.testing.svc.cluster.local:9021<br>        api_key: &quot;test&quot;</pre><p>This setup has two advantages:</p><ul><li>We do not spend real money while testing behavior at high request rates</li><li>The backend latency and responses are controlled, so any degradation we see is coming from LiteLLM itself, not from the provider</li></ul><h4>Load Generation with Locust</h4><p>To generate load against LiteLLM, we used <strong>Locust</strong>, which allowed us to scale the number of concurrent users and control the traffic pattern. Unlike a trivial “hello world” load test, we needed a setup that created realistic pressure on LiteLLM:</p><ul><li>Each request sends a <strong>randomly generated payload</strong> ranging from 12k to 100k characters to ensure that requests are not being cached by Redis and to mimic the payloads in real use-cases</li><li>Requests hit the <strong>OpenAI-compatible </strong><strong>/chat/completions</strong> endpoint exposed by LiteLLM</li><li>Timeouts are set very high to accommodate the intentionally slow WireMock responses</li></ul><p>Below is the simplified version of the Locust user class we used in our tests:</p><pre>from locust import task, FastHttpUser<br>import os, json, random, string, logging<br><br>class LiteLLMUser(FastHttpUser):<br>    network_timeout = 3000000<br>    connection_timeout = 3000000<br>    def on_start(self):<br>        self.headers = {&quot;Content-Type&quot;: &quot;application/json&quot;}<br>        api_key = os.getenv(&quot;API_KEY&quot;)<br>        if api_key:<br>            self.headers[&quot;Authorization&quot;] = f&quot;Bearer {api_key}&quot;<br>        self.model = os.getenv(&quot;LITELLM_MODEL&quot;, &quot;custom-model&quot;)<br>        self.chat_path = os.getenv(&quot;LITELLM_PATH&quot;, &quot;/chat/completions&quot;)<br>    def generate_random_message(self):<br>        random_word = &quot;&quot;.join(<br>            random.choices(string.ascii_lowercase, k=random.randint(12000, 100000))<br>        )<br>        return {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: random_word}<br>    @task(5)<br>    def chat_completions(self):<br>        payload = {<br>            &quot;model&quot;: self.model,<br>            &quot;messages&quot;: [self.generate_random_message()],<br>            &quot;max_tokens&quot;: 150,<br>            &quot;temperature&quot;: 0.7<br>        }<br>        with self.client.post(<br>            self.chat_path,<br>            json=payload,<br>            headers=self.headers,<br>            catch_response=True,<br>            name=&quot;chat_completions&quot;,<br>            timeout=3000000<br>        ) as response:<br>            if response.status_code == 200:<br>                try:<br>                    result = response.json()<br>                    if &quot;choices&quot; in result and len(result[&quot;choices&quot;]) &gt; 0:<br>                        response.success()<br>                    else:<br>                        response.failure(&quot;No choices in response&quot;)<br>                except json.JSONDecodeError:<br>                    response.failure(&quot;Invalid JSON response&quot;)<br>            else:<br>                response.failure(f&quot;HTTP {response.status_code}&quot;)</pre><p>We then ran Locust against the LiteLLM ingress endpoint, gradually increasing the number of concurrent users. This allowed us to observe how LiteLLM behaved under realistic high-throughput conditions, including how quickly it began queueing requests, how latency evolved and how internal metrics changed as load increased.</p><h4>What We Observed</h4><p>The key finding from these tests was that <strong>LiteLLM began queueing requests at roughly 100 active requests per pod when running version v1.75.8.</strong> Newer versions have improved this threshold significantly, but they still introduce throttling once concurrency reaches a certain level.</p><p>Up to around that point:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*erSl_fBBBxCdlddYkUR2zw.png" /></figure><ul><li>Median and p95 latency remained stable</li><li>Requests completed without queuing</li><li>CPU and memory usage stayed much below the resources</li></ul><p>After we pushed concurrency beyond that level for a single pod:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tNi1GFW_sy7KnjVFdz5Xcw.png" /></figure><ul><li>Latency began to increase noticeably, and <strong>a stepwise latency increase</strong> was observed.</li><li>A set of requests was handled concurrently, while the remaining requests sat idle in a queue until the active ones completed.</li><li>Requests were effectively queued even though CPU and memory usage did not change noticeably.</li></ul><p>In other words, the bottleneck was not raw CPU or memory. It was the internal concurrency that LiteLLM could handle comfortably per pod.</p><h4>Why This Matters for Autoscaling</h4><p>These results directly influenced how we approached autoscaling:</p><ul><li>A CPU based HPA would not react to increase in active requests count</li><li>What we really care about is <strong>request throughput per pod</strong>, not just resource usage</li><li>If we let a pod go far beyond that ~100 (updated around 1000 in later versions) active request level, user facing latency degrades even though the cluster appears healthy from a CPU perspective</li></ul><p>This is why we moved to a <strong>KEDA based autoscaling strategy</strong> that uses Prometheus metrics about request rates and completions instead of only CPU. In the next section, we will describe how we used KEDA to scale LiteLLM before the internal queue becomes a problem.</p><h4>KEDA Configuration</h4><pre>apiVersion: keda.sh/v1alpha1<br>kind: ScaledObject<br>metadata:<br>  name: litellm-scaled-object<br>  namespace: data<br>spec:<br>  scaleTargetRef:<br>    name: litellm<br>  pollingInterval: 15<br>  minReplicaCount: 3<br>  maxReplicaCount: 10<br>  cooldownPeriod: 400<br>  triggers:<br>    - type: prometheus<br>      metadata:<br>        serverAddress: http://example-prometheus-server.example-cluster.svc.cluster.local:port_num<br>        query: &gt;<br>          max(<br>            sum by (k8s_pod_name) (<br>              rate(<br>                litellm_proxy_total_requests_metric_total{<br>                  service_name=&quot;litellm&quot;,<br>                  name=&quot;acompletion&quot;<br>                }[2m]<br>              ) * 60<br>            )<br>          )<br>        threshold: &quot;100&quot;</pre><h3>What This Means</h3><ul><li><strong>Trigger:</strong> KEDA reads a Prometheus metric that counts how many async completions each LiteLLM pod processes per minute.</li><li><strong>Threshold:</strong> If any pod averages more than <strong>100 requests per minute</strong>, KEDA considers the deployment overloaded and begins scaling out.</li><li><strong>Scaling behavior:</strong></li><li>Minimum <strong>3 replicas</strong> for high availability</li><li>Maximum <strong>10 replicas</strong> during heavy traffic</li><li><strong>400-second cooldown</strong> prevents rapid scale-in/out cycles</li></ul><h4>Why This Works Better Than CPU-Based Autoscaling</h4><p>CPU usage stays low even when LiteLLM is internally queuing requests. The bottleneck is not compute but <strong>concurrency inside the proxy</strong>. By scaling based on actual request throughput, we avoid queuing and maintain consistent latency under load.</p><h3>Production Reliability: Ingress and Pod Disruption Budgets</h3><p>Configuring LiteLLM correctly is only part of the story. To run it safely in production, we also needed to make sure the deployment survives node maintenance, rolling updates and long-running LLM requests without dropping traffic. Two components are critical here: <strong>Pod Disruption Budgets</strong> and a <strong>long-request-aware ingress configuration</strong>.</p><h3>Pod Disruption Budget</h3><p>Kubernetes regularly performs voluntary disruptions such as node upgrades or scaling events. Without protection, these can terminate too many pods at once.</p><p>In production, we use a Pod Disruption Budget to guarantee availability:</p><pre>apiVersion: policy/v1<br>kind: PodDisruptionBudget<br>metadata:<br>  name: litellm-pdb<br>  namespace: data<br>spec:<br>  minAvailable: 3<br>  selector:<br>    matchLabels:<br>      app.kubernetes.io/name: litellm</pre><p>This ensures that Kubernetes always keeps at least <strong>three LiteLLM pods running</strong> during maintenance or rolling updates. Nodes are drained gradually, and updates proceed without taking the service offline.</p><p>We only apply this in production. Occasional downtime in dev and staging is acceptable and keeps those environments simpler.</p><h3>Ingress Configuration for Long-Running Requests</h3><p>LLM requests behave very differently from typical HTTP traffic. Depending on the model and prompt size, a single request can take tens of seconds or even several minutes. Default ingress timeouts would cut these requests off prematurely.</p><p>Our production ingress is tuned specifically for this workload:</p><ul><li><strong>Idle timeout: 600 seconds</strong><br> Allows long-running inference and large context requests to complete without being terminated.</li><li><strong>Deregistration delay: 400 seconds</strong><br> When a pod is scaled down or replaced, in-flight requests are allowed to finish instead of being dropped mid-execution.</li><li><strong>Load balancing: least outstanding requests</strong><br> New requests are routed to the pod with the fewest active requests, which works much better than round-robin for workloads with highly variable request durations.</li><li><strong>Health checks on </strong><strong>/health/readiness</strong><br> Traffic is only sent to pods once database and Redis connections are fully established.</li><li><strong>Internal-only ingress</strong><br> LiteLLM is not exposed to the public internet. Only internal services and controlled networks can reach it.</li></ul><h3>Why We Built a Prometheus-Based Metrics Pipeline</h3><p>LiteLLM already gives strong observability out of the box, but in a real production setup we had two practical constraints: <strong>(1) our production control plane is intentionally not exposed to developers</strong>, and <strong>(2) we needed metrics that could plug into our existing SRE stack (Prometheus + Grafana) and work consistently across multiple environments and clusters</strong>. Prometheus metrics give us a low-friction, standardized way to monitor request volume, latency, errors, spend, and saturation signals — without requiring direct access to the LiteLLM UI, and without coupling every team to a specific vendor dashboard. Once these metrics flow into Grafana, we can build reliable, shared dashboards, set alerting rules, and compare trends across dev/staging/prod with the same definitions. The remaining challenge was ensuring those metrics stayed accurate as we scaled LiteLLM horizontally, which is where pod-level scraping and multi-cluster aggregation come in.</p><h4>Pod-Level Metrics Collection in Multi-Pod Deployments</h4><p>When LiteLLM runs with multiple pods behind a Kubernetes Service (and a load balancer), scraping metrics through that Service gives you an incomplete picture: each scrape hits a random pod, so you only capture one instance’s metrics at a time. That makes aggregations misleading and hides pod-specific issues (hot pods, uneven load, outliers in latency, etc.).</p><p>To fix this, we scrape <strong>each LiteLLM pod directly</strong> using <strong>Kubernetes service discovery</strong> in Prometheus. We configure kubernetes_sd_configs with role: pod to dynamically discover pods in the data namespace, then apply relabel rules to:</p><ul><li><strong>Keep only LiteLLM pods</strong> via app.kubernetes.io/name=litellm</li><li><strong>Keep only the metrics port</strong> (example: 4000)</li><li>Enrich series with pod labels like pod_name, namespace, and pod_ip</li></ul><p>This enables accurate dashboard queries, like summing or maxing across <em>all</em> pods reliably — rather than whichever pod the load balancer picked.</p><pre>- job_name: litellm<br>  scrape_interval: 30s<br>  metrics_path: /metrics<br>  kubernetes_sd_configs:<br>    - role: pod<br>      namespaces:<br>        names:<br>          - data<br>  relabel_configs:<br>    - source_labels: [__meta_kubernetes_pod_label_app_kubernetes_io_name]<br>      action: keep<br>      regex: litellm<br>    - source_labels: [__meta_kubernetes_pod_container_port_number]<br>      action: keep<br>      regex: &quot;4000&quot;<br>    - source_labels: [__meta_kubernetes_pod_name]<br>      target_label: pod_name<br>    - source_labels: [__meta_kubernetes_namespace]<br>      target_label: namespace<br>    - source_labels: [__meta_kubernetes_pod_ip]<br>      target_label: pod_ip</pre><h4>Comprehensive Single-Cluster Dashboard</h4><p>With pod-level scraping in place, we built a primary LiteLLM dashboard that provides end-to-end observability across the dimensions that matter for an LLM proxy , using LiteLLM’s exported Prometheus metrics.</p><p>The <strong>overview</strong> surfaces key health signals at a glance:</p><ul><li>Total requests, failed requests, and success rate</li><li>Cumulative spend (USD) and token consumption</li><li>Current requests per minute (RPM)</li></ul><p>From there, deeper sections break down:</p><ul><li>Request traffic by <strong>model</strong> and <strong>provider</strong></li><li>Latency percentiles (<strong>p50 / p95 / p99</strong>) for:</li><li>End-to-end request duration</li><li>Provider (LLM API) latency</li><li>Spend trends over time grouped by <strong>Model</strong>, <strong>Team</strong>, and <strong>API Key</strong></li><li>Deployment health mapped from LiteLLM’s internal status codes:</li><li>0 = Health</li><li>1 = Partial Outage</li><li>2 = Complete Outage</li></ul><p>We also added template variables such as team_alias, api_key_alias, and model to make it easy to filter the entire dashboard to a specific team, key, or workload.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0zEvXvFYDugLnnEIqN7jvA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o4ls-W6_ovNg-GD20ZBEwQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ukhwzk_samunw847XDcP2A.png" /></figure><h4>Unified Production View Across Active-Active Clusters</h4><p>In production, we run LiteLLM in an <strong>active-active</strong> setup across two clusters. To avoid splitting operational visibility, we built a unified Grafana dashboard that aggregates metrics from both clusters into a single pane of glass.</p><p>We achieve this using Grafana’s <strong>mixed datasource</strong> approach:</p><ul><li>Each panel queries both Prometheus instances</li><li>Grafana transformations merge and aggregate results into combined totals</li></ul><p>For “single number” panels (total requests, total spend, etc.) we use:</p><ul><li><strong>Merge</strong> → <strong>Reduce</strong> transformations</li><li>Reduce aggregation set to <strong>sum</strong></li></ul><p>For time-series panels (daily spend trends, RPM, etc.) we combine series using:</p><ul><li>Server-side expressions like <strong>$A + $B</strong></li><li>We hide the raw cluster A &amp; cluster B series from the legend to keep visuals clean</li></ul><p>This removes the need to mentally add numbers across dashboards, while still keeping the option to drill down per cluster when debugging.</p><p>Template variables like team_alias, api_key_alias, and model apply here as well, so teams can filter usage consistently across the combined view.</p><h3>Known Limitations &amp; Trade-offs</h3><p>Even with all of this in place, our setup is <strong>work in progress</strong>. A few things we’re consciously living with today:</p><ul><li><strong>LiteLLM still has a practical concurrency ceiling per pod.</strong><br>Newer versions pushed the limit up, but the underlying behavior is the same: beyond a certain point, latency jumps in steps as internal queues fill up. Our KEDA strategy mitigates this, it doesn’t magically remove it.</li><li><strong>Caching only shines for certain workloads.</strong><br>Redis pays off when prompts and patterns repeat. For highly unique, long-context requests (which we have a lot of), caching helps less than you’d hope.</li><li><strong>Spend attribution depends on humans behaving.</strong><br>Virtual keys and dashboards give us great visibility, but only if teams actually use the right keys, follow naming conventions, and don’t share “just for a quick test”.</li><li><strong>Adding a new model still requires a config change + deployment </strong>LiteLLM doesn’t yet support dynamically registering models at runtime.<br>Any new model such as a new Anthropic version, a Gemini variant, an OpenAI model still needs to be added to the <strong>Helm values file</strong> and rolled out through our deployment pipeline. It’s not a huge operational burden, but it does mean model updates aren’t instant and require coordination.</li></ul><h3>What We Want to Improve Next</h3><p>There are a few directions we’re already thinking about as our LLM usage at Midas keeps growing:</p><h4>Smarter Routing and Rollouts</h4><ul><li><strong>Adaptive failover and routing</strong><br>Automatically shifting traffic between regions or providers when latency or error rates spike, instead of relying purely on static config and human response.</li><li><strong>Dynamic model selection</strong><br>Routing based on cost, latency, or request type (e.g., “fast + cheap by default, upgrade to bigger models only when needed”) rather than hard-coded model names.</li><li><strong>Safer model rollouts</strong><br>Treating new Anthropic/OpenAI/Bedrock versions more like code: canaries, automated comparisons, and gradual ramp-ups instead of big-bang switches.</li></ul><h4>Chaos Testing for the LiteLLM Stack</h4><ul><li>Injecting failures at the <strong>LiteLLM proxy</strong>, <strong>Redis</strong>, <strong>PostgreSQL</strong>, and <strong>upstream provider</strong> layers</li><li>Clearly distinguishing request-serving impact from control-plane degradation</li><li>Making failure modes explicit instead of discovering them during incidents</li></ul><h3>Where This Leaves Us</h3><p>In the beginning, our LLM usage at Midas was a blur. Traffic was mixed across environments, costs were hard to attribute, and we had little sense of how systems behaved under real load. Now we have a clear control plane, predictable boundaries, and data we can actually trust. The problems that used to slow us down are no longer in the way, and the ones that remain are finally the kind you make progress on, not the kind you firefight. That shift from uncertainty to understanding is ultimately the problem we set out to solve.</p><p>We didn’t build a perfect LLM platform, and that was never the goal. What we did build is a <strong>solid control plane</strong>: one place where traffic flows, limits are enforced, and behavior is observable enough that we can keep iterating without flying blind.</p><p>LiteLLM sits at the center of that, but the real value came from everything we had to put around it — environment boundaries, load tests, autoscaling based on reality instead of CPU, and a metrics pipeline that actually reflects what our users feel.</p><p>The nice part is: the hard, unglamorous pieces are now in place. From here on, most improvements are “turning the knobs” rather than rethinking the whole system. And that’s exactly where we want to be.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=04b7d818a782" width="1" height="1" alt=""><hr><p><a href="https://engineering.getmidas.com/scaling-llm-usage-with-litellm-monitoring-quotas-and-spend-management-04b7d818a782">Scaling LLM Usage with LiteLLM: Monitoring, Quotas, and Spend Management</a> was originally published in <a href="https://engineering.getmidas.com/">Midas Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>