LLM cost optimization: budgets and alerts in production

LLM cost optimization in production comes down to four controls: budgets that alert at 50%, 75% and 90% of a principal's monthly limit, anomaly detection on daily spend, hard caps with real kill switches, and gateway routing that degrades to a cheaper model instead of failing. Without them your bill can still triple overnight. A runaway agent loop, a forgotten batch job or a prompt that quietly grew to 8k tokens will do it, and you will find out when the invoice lands. This is the operational reference for building that control plane, on any OpenAI-compatible gateway, whether it sits in front of hosted providers, your own GPUs, or both.

Why LLM cost optimization in production breaks the ordinary FinOps playbook

Traditional cloud spend grows when you provision things and stays flat when you stop. LLM spend grows every time someone speaks to it. The unit is a token, the volume is set by your users and your prompts, and the price list is rich in traps. On OpenAI's published standard pricing at the time of writing, a GPT-5.4 request costs $2.50 per million input tokens and $15.00 per million output tokens at context lengths up to 272K tokens. Cross 272K and the same request re-prices at $5.00 and $22.50. A prompt that creeps over the boundary does not just add tokens, it raises the price of every token in the request.

Three failure modes account for most of the surprise bills we see:

  1. Loops. An agent that retries a tool call, or a summarisation job that re-ingests a whole corpus because incremental indexing was harder to build, multiplies request volume with no human in the loop.
  2. Prompt growth. A system prompt that started at 800 tokens is now 8k because someone kept appending policy text. Nobody re-priced the workload.
  3. Orphaned workloads. An experiment endpoint, a nightly job or a staging deployment that still receives traffic. The CloudRPS AI FinOps write-up opens with exactly this: a $340,000 monthly bill for a team that had shipped nothing significant, with forgotten endpoints and a batch pipeline quietly consuming GPU hours.

The second problem is that the invoice is not the whole cost. Thread Transfer's breakdown of hidden LLM costs puts direct API spend at roughly 70% to 85% of the true total. The submerged part is data transfer, orchestration infrastructure, observability tooling, retry overhead (typically 5% to 10% of requests fail and retry at least once) and the engineering time to run it all. Mature teams add 20% to 30% on top of API spend to budget for total cost of ownership. Teams that skip this habitually under-budget by half or more and then cut mid-quarter.

The third problem is visibility. Token spend arrives through API keys and provider consoles, not through your cloud billing file. As Finout's FinOps-for-AI analysis puts it, showback reports break precisely when AI spend scales, because consumption behaves more like SaaS than infrastructure and is invisible to the cost allocation model built for VMs.

Why this matters now in the UAE and the wider GCC: the pilots are finishing. MIT Sloan Management Review Middle East's enterprise readiness white paper, produced with Pure Storage, found 46% of regional organisations moving beyond pilot phases to broader implementation. Every one of those deployments converts an engineering experiment into a line item someone has to explain. The controls below are what turn that line item into something predictable.

The three-tier budget system: inform at 50%, review at 75%, escalate at 90%

Set a monthly budget per principal (an application, a team, or a service account), not one budget for the whole company. A single global number tells you nothing until it is too late. Then attach three thresholds, each with a named owner and a defined response. The tiering itself comes from the CloudRPS AI FinOps playbook, which recommends alerting at 50%, 75% and 90% of each cost category's budget, with separate categories for training, inference and API costs.

ThresholdWhat happens automaticallyWho must actDeadline
50%Message posted to the owning team's channel. No action required.NobodyNone
75%Owner receives a spend breakdown by model and feature and must reply with a reviewBudget owner for that principal24 hours
90%Escalation to head of engineering or CTO; platform team prepares the degrade or kill switchBudget owner plus platform lead4 hours
100%Hard stop, or automatic degrade to a local or cheap tierAutomaticImmediate

The rules that make this work are unglamorous:

If you run an open-source gateway, most of this is configuration rather than code. LiteLLM, for example, supports per-key budget alert thresholds mapped to recipients, which is exactly the tiering above:

curl -X POST 'http://0.0.0.0:4000/key/generate' \
  -H "Authorization: Bearer $LITELLM_MASTER_KEY" \
  -H 'Content-Type: application/json' \
  -d '{
    "max_budget": 5000,
    "metadata": {
      "max_budget_alert_emails": {
        "50": ["platform@yourcompany.ae"],
        "75": ["platform@yourcompany.ae", "finops@yourcompany.ae"],
        "90": ["cto@yourcompany.ae", "oncall@yourcompany.ae"]
      }
    }
  }'

Each threshold fires at most once per key per 24-hour suppression window, which is what stops alert storms during a genuine incident while preserving one notification per level. Team-level thresholds work the same way and sum spend across all of the team's keys.

Anomaly detection on daily spend

Tiered budgets tell you how much of the month you have burned. Anomaly detection tells you that today is wrong, which matters more, because a bad Tuesday discovered on the 30th is a bad month.

Two useful signatures:

If your gateway exports Prometheus metrics (most production gateways do, and any OpenAI-compatible gateway that reports usage can be instrumented this way), the alert is a rule, not a project. The metric name follows whatever your gateway emits; the comparison is the point:

groups:
  - name: llm-spend
    rules:
      - alert: LLMDailySpendAnomaly
        expr: |
          sum(increase(gateway_request_cost_usd_total[24h]))
            > 1.2 * sum(increase(gateway_request_cost_usd_total[24h] offset 1d))
        for: 15m
        labels:
          severity: page
        annotations:
          summary: "LLM spend up more than 20% day over day"

      - alert: LLMPrincipalSpendVelocity
        expr: |
          gateway_budget_remaining_usd
            / gateway_spend_7d_mean_usd < 5
        labels:
          severity: ticket

The second rule is the one people forget: days-to-exhaustion. Remaining budget divided by the trailing seven-day mean daily spend. If that falls below five days on the 20th of the month, you have a planning conversation now rather than an incident later.

Route alerts to somewhere that pages. LiteLLM emits webhook events for budget crossings (budget_crossed, soft_budget_crossed and threshold_crossed), and gateway-based alerting in general lets you fan out to Slack, Microsoft Teams or an on-call tool without polling.

One honest limitation: anomaly detection is retrospective. It fires after money has moved. Budgets cap before money moves. You need both, and you should never let "we have anomaly detection" delay setting the caps.

Hard limits and kill switches for experiments, batches and agents

This is the tier that turns policy into physics. Three rules cover almost every case.

Rule 1: every experimental workload gets an envelope, and the envelope enforces itself. A researcher's fine-tuning job or a team's eval sweep gets a fixed budget. When it is spent, the job stops or requires explicit approval to continue. This sounds restrictive; in practice it forces better experimental design, and it is the direct answer to the "$340,000 month with nothing shipped" failure.

Rule 2: cap in two time windows at once. A single monthly cap cannot stop a bad night from burning the month. Gateways that support concurrent budget windows solve this directly. LiteLLM's budget_limits field on a key does it in one request:

curl -X POST 'http://0.0.0.0:4000/key/generate' \
  -H "Authorization: Bearer $LITELLM_MASTER_KEY" \
  -H 'Content-Type: application/json' \
  -d '{
    "team_id": "batch-pipelines",
    "budget_limits": [
      {"budget_duration": "24h", "max_budget": 200},
      {"budget_duration": "30d", "max_budget": 1000}
    ]
  }'

Each window tracks and resets independently (the 24-hour window resets daily at midnight UTC, the 30-day window on the first of the month). A runaway job now stops at $200 in a day regardless of how much monthly headroom remains.

Rule 3: cap agents per session, not just per month. An agent loop is a session-scale failure and needs a session-scale kill switch. LiteLLM's agent gateway exposes max_iterations and max_budget_per_session per session alongside rate limits; the documented example caps a research agent at 25 iterations and $5.00 per session and returns 429 when either is exceeded. Twenty-five iterations is a sensible default ceiling for most tool-using agents; raise it only with evidence from traces.

Two operational gotchas worth writing into your runbook:

Define the kill switch itself before you need it: who may pull it, what it stops (a key, a frontend model, a provider), what the fallback behaviour is for live user traffic, and where the audit trail goes. Rehearse it once. The first live run of a kill switch should not also be the first time anyone has thought about it.

Routing and fallback: degrade to a cheaper model, never to an error

Cost control is not only about spending less per request. It is about which model answers the request at all. The default behaviour of most teams is to send everything to the most capable model, because that is what the engineer had open when they built the feature. The production rule is: the cheapest model that clears the quality bar for that specific task, measured on your own evaluation set.

Current OpenAI standard pricing shows the spread available inside one provider:

ModelInput ($/1M tokens)Output ($/1M)Cached input ($/1M)Typical role
gpt-5.4 (short context)$2.50$15.00$0.25Complex reasoning, hard cases
gpt-4.1$2.00$8.00$0.50General production traffic
gpt-5.4-mini$0.75$4.50$0.075Summarisation, drafting
gpt-4.1-mini$0.40$1.60$0.10Classification, extraction, routing
gpt-5.4-nano$0.20$1.25$0.02High-volume boilerplate

The gap between the first and last row is 12.5x on input and 12x on output. Cached input pricing in the table runs 75% to 90% below the standard input rate, which makes a stable system prompt effectively cheap on every call after the first, and is a cost argument for cache-affinity routing: send the request to the server that already holds the shared prefix.

The policy you want the gateway to enforce looks like this (shape, not one product's syntax):

# Illustrative policy shape for a gateway
routes:
  - frontend_model: "assistant"        # the only name applications know
    match:
      caller: "support-copilot"
      prompt_tokens_max: 4000
    targets:
      - "gpt-5.4"                      # primary
      - "gpt-4.1"                      # failover on 429 / 5xx / timeout
    degrade_at_budget_pct: 80          # caller near its budget
    degrade_to: "gpt-4.1-mini"         # cheaper tier, not an error
    fallback_last_resort: "gpt-5.4-nano"

Three properties matter here:

  1. Failover happens before the client sees a byte. On a server error, a rate limit or an unreachable provider, the next target is tried inside the gateway. Applications keep the standard OpenAI API and one endpoint address.
  2. Degrade instead of refusing. When a caller passes (say) 80% of its budget, switch it to a cheaper or local model. Users get slightly lower quality instead of a hard failure, and the budget survives. LiteLLM supports the same idea from the other direction: keys at their limit can still reach models explicitly priced at zero cost, which is how a self-hosted model acts as the safety net.
  3. Failover chains are per rule, not global. A finance assistant's chain may end on a model that runs on your own GPUs inside your network; a marketing tool's chain may end on a cheap hosted model. This is the pattern FastLLM Proxy is built on: one OpenAI-compatible endpoint where applications request a single model name and the gateway decides where the request goes, with an ordered failover chain behind each routing rule and a deployment-wide fallback when every chain has run dry. Routing, budgets and access control all live in the one place, so spend is attributed at the point of decision rather than reconstructed afterwards.

Worked example: a batch job that would have cost $6,875

The scenario: a Dubai e-commerce company runs a support copilot on a gateway. One principal, support-assistant, budget $5,000 per month.

Baseline. 300,000 conversations per month, each roughly 2,000 input tokens and 400 output tokens on GPT-5.4 at standard pricing.

The incident. A nightly summarisation batch normally processes 5,000 documents at 2k tokens each, around $30 per night. On a Tuesday, a retrieval change inlines full documents into the prompt (8k tokens each) and the job reprocesses the entire 250,000-document corpus instead of the delta.

Cost per document at 8k input and 500 output tokens:

Without controls. The job completes in a few hours. The month lands near $10,200 against a $5,000 budget: more than double, discovered when finance asks why the invoice doubled. The 50/75/90 alerts fire in one burst overnight, nobody is on-call for them, and the only remedy left is explaining.

With controls. Four layers act in sequence:

  1. Daily cap. The batch key runs with budget_limits: [{24h, $200}, {30d, $1,000}]. The job is stopped after 7,272 documents ($200 / $0.0275). Damage: $200, not $6,875.
  2. Anomaly alert. Day-over-day spend crosses +20% (from roughly $140 to $168 total) early in the run. The Prometheus rule pages the on-call engineer, who sees batch-pipelines in the gateway console and confirms the job is capped. Elapsed time to understanding: minutes, because the spend is attributed to a principal and a model.
  3. Monthly tiers. Cumulative spend never passes 50% of the principal budget, so the 75% and 90% tiers are never triggered. Escalation is a scalpel, not a fire alarm.
  4. Session caps. If the same failure had appeared as an agent loop rather than a batch job, max_iterations: 25 and max_budget_per_session: 5.00 would have bounded a single runaway session at about the price of two coffees.

The engineering follow-up takes an afternoon: fix the delta logic, and keep the caps. The month closes at roughly $3,500, and the incident becomes a Slack thread rather than a board slide.

The metrics that tell you the controls are working

Budgets and alerts are controls. These numbers tell you whether they are tuned correctly:

MetricFormula or definitionWhy it matters
Cost per business outcomeSpend / resolved tickets, marked exams, processed casesThe only number a CFO should judge AI on
Tokens per request (p50, p95)From gateway usage recordsCatches prompt growth before it re-prices the workload
Spend velocityRemaining budget / 7-day mean daily spendForecasts exhaustion in days, not percentage
Retry rateRetried requests / total5% to 10% is industry-typical; spikes mean provider or client misconfiguration
Cache hit rateCached input tokens / input tokensIf this falls, you are paying frontier prices for boilerplate
Fallback and degrade rateRequests served by a non-primary target / totalHigh rates mean your primary is undersized or overpriced
Cost by principal, model and dayFrom the gateway's usage reportingThe basis of monthly showback and chargeback

Review these weekly with team leads. Finout's point about forecasting is the right frame: token usage does not forecast linearly, so blend historical usage with model choice and prompt shape, and revisit whenever volume grows 50% or more, or when you add a model or provider. Recalculate total cost of ownership quarterly with the 20% to 30% hidden-cost uplift from Thread Transfer's breakdown applied to raw API spend, so budget conversations stay honest.

Chargeback makes this real. Give every department or application its own key and budget and, at month end, you can report exactly what each one used and spent. The first time a team sees what their experiment cost, the behaviour change is immediate. That is the case for putting routing, budgets and access control in a single gateway rather than bolting spend tracking on afterwards.

What to do next

If your bill surprised you last month, do these in order, and do not start with a platform procurement:

  1. This week: map every LLM call to a principal (application, team or service account) with its own key. If you cannot attribute spend, you cannot cap it. Export usage to one dashboard.
  2. This week: set monthly budgets with the 50/75/90 tiers and named owners. Enforcement may be alerts only at first; the tiering is the point.
  3. Next week: add the daily anomaly rule (20% day over day) and the spend-velocity rule, routed to whoever is actually on-call.
  4. Next two weeks: cap every experimental and batch workload with a 24-hour window alongside the monthly one, and cap agents per session (max_iterations, per-session budget).
  5. Month two: measure your top three use cases on an evaluation set and move traffic to the cheapest model that clears the bar, with a failover chain and a degrade-at-budget rule behind it.

We are a Dubai-based team, and we do this work for UAE and GCC organisations: the assessment, the gateway deployment and the running of it. If you want a control plane over both your own GPU-hosted models and hosted providers, our FastLLM Proxy puts routing, budgets and access control in one OpenAI-compatible endpoint. If what you need first is a plain answer on where AI spend pays off in your organisation and what it will take, start with AI strategy. Either way, the sequence above is the same: attribute, tier, alert, cap, then route. The bill becomes boring, which is exactly what a production bill should be.

LLM costsFinOpsAI gatewaybudgetsproduction AIcost optimisation
Found this useful? Share it.

Link to this article

Citing this in your own writing? Use the permanent link below.
Permalink
https://www.azrty.com/blog/llm-cost-optimization-budgets-and-alerts-in-production
HTML
<a href="https://www.azrty.com/blog/llm-cost-optimization-budgets-and-alerts-in-production">LLM cost optimization: budgets and alerts in production</a> (Azrty)
Get a readiness assessmentOne call to find where AI will pay off in your business.
Related
LLM cost optimization: budgets and alerts in production | Azrty