Sub topic 15
Set budgets and monitor in production
This chapter assumes you can call an LLM API in Python and that you already have a baseline from the measurement chapter: per-request latency, token counts, and cost. Here you turn that baseline into limits and alerts so regressions show up in hours, not on the monthly invoice.
Why budgets and monitoring
Every lever in this tutorial can be undone by a small change. A prompt edit adds 800 tokens. A retrieval setting returns twice as many chunks. A retry loop multiplies calls. Nobody notices until the bill arrives. A budget is a number you agree on in advance. Monitoring is the loop that tells you when you cross it.
What to record per request
Log one structured record for every model call. Keep it small and free of user content.
- Timestamp, feature name, and model name.
- Input tokens, output tokens, and cached input tokens if the provider reports them.
- Time to first token and total time.
- Computed cost in USD.
- Outcome: success, error, timeout, or retry count.
- A prompt version label, so you can tie a change to a shift.
Tag each record with the feature that made the call. A total spend number cannot tell you which feature caused a jump.
Choose budgets you can enforce
Set budgets at three levels.
| Level | Example budget | Action when exceeded |
|---|---|---|
| Per request | Max 6,000 input tokens, max 500 output tokens | Reject or truncate before the call |
| Per feature, per day | $40 per day | Alert, then throttle or fall back to a cheaper model |
| Per user or tenant | 200 requests per hour | Return a rate-limit response |
Latency budgets work the same way. Pick a target for a high percentile, such as p95 time to first token under 1.5 seconds. Averages hide the slow tail that users feel.
A simple budget guard
This guard tracks spend per feature per day and refuses calls once the budget is gone. It is in memory, so use a shared store such as Redis if you run several processes.
import datetime
from collections import defaultdict
DAILY_BUDGET_USD = {"summarize": 40.0, "chat": 150.0}
_spend = defaultdict(float)
class BudgetExceeded(Exception):
pass
def _key(feature):
return (feature, datetime.date.today().isoformat())
def check_budget(feature):
if _spend[_key(feature)] >= DAILY_BUDGET_USD[feature]:
raise BudgetExceeded(f"{feature} is over its daily budget")
def record_spend(feature, cost_usd):
_spend[_key(feature)] += cost_usd
check_budget("summarize")
record_spend("summarize", 0.0042)
print(round(_spend[_key("summarize")], 4))Call check_budget before each request and record_spend after it, using the cost from your log record. A hard stop is risky for user-facing features. Many teams prefer to switch to a cheaper model at 80 percent of budget and stop only at 100 percent.
What to alert on
Alert on changes, not just limits. Useful signals:
- Daily cost per feature compared with the trailing seven-day average.
- Mean input tokens per request, which catches prompt growth.
- p95 time to first token and p95 total time.
- Error and retry rates, since retries add cost and delay.
- Cache hit rate, if you use response or prompt caching.
- Quality score from a small scheduled evaluation run.
The last signal matters. A cheaper model or shorter prompt can lower cost while quality quietly drops, so run your evaluation set on a schedule.
Common mistakes
- Tracking only total spend, so the cause of a spike is unknown.
- Alerting on averages, which hide tail latency.
- Hard-coding prices. Keep them in one config and update them when the provider changes them.
- Logging full prompts, which creates a privacy risk.
Exercise
A feature's daily cost rises 30 percent, but request count is unchanged and p95 latency is flat. Which logged fields do you check first, and what is the likely cause?
Show answer
Check mean input tokens and output tokens per request, and the prompt version label. Cost rose with no change in volume, so each request got more expensive. The likely cause is a longer prompt, more retrieved context, or longer outputs after a prompt change. A model change would also show in the model name field.