Sub topic 15
Set budgets and monitor in production
This chapter assumes you have read the earlier chapters on token pricing, latency anatomy, and measuring a baseline. You should be comfortable with basic Python, JSON logs, and calling an LLM API. The goal is to turn the one-off baseline into limits and alerts that run all the time, so that cost and latency regressions show up within hours instead of on the monthly invoice.
Why a baseline is not enough
A baseline describes one moment. Production changes it constantly:
- A developer lengthens the system prompt, and every request gets more expensive.
- A retrieval change returns more chunks, and input tokens double.
- A new feature calls the model in a loop, and request volume jumps.
- A provider updates a model, and latency or output length shifts.
- A bug causes retries to pile up, and you pay for failed work.
None of these raise an error. The application keeps working and the bill grows. Budgets and monitoring are how you detect this kind of silent drift.
What to record on every request
Monitoring is only as good as the data behind it. Log one structured record per model call. Include enough fields to slice the data later, and leave out the prompt text unless you have a clear privacy policy for it.
| Field | Why it matters |
|---|---|
| `timestamp` | Lets you chart trends and compare time windows |
| `feature` | Names the product feature, so you can see which one costs the most |
| `model` | Shows the effect of model changes and routing |
| `input_tokens`, `output_tokens` | The two inputs to cost, priced separately |
| `cached_input_tokens` | Shows whether prompt caching is working |
| `ttft_s`, `total_s` | Time to first token and total time |
| `status` | Success, rate limit, timeout, or error |
| `retries` | Shows hidden cost from failed attempts |
| `cost_usd` | Computed at log time from your price table |
Use the token counts that the provider returns in its response. They are what you are billed for. Local counts from a tokenizer are estimates and can differ.
import json
import time
# Placeholder prices in USD per million tokens. Replace with your provider's current prices.
PRICES = {
"small-model": {"input": 0.50, "output": 2.00},
"large-model": {"input": 3.00, "output": 12.00},
}
def request_cost(model: str, input_tokens: int, output_tokens: int) -> float:
p = PRICES[model]
return (input_tokens * p["input"] + output_tokens * p["output"]) / 1_000_000
def log_request(feature, model, input_tokens, output_tokens,
ttft_s, total_s, status="ok", retries=0):
record = {
"timestamp": time.time(),
"feature": feature,
"model": model,
"input_tokens": input_tokens,
"output_tokens": output_tokens,
"ttft_s": ttft_s,
"total_s": total_s,
"status": status,
"retries": retries,
"cost_usd": request_cost(model, input_tokens, output_tokens),
}
print(json.dumps(record)) # In production, send this to your log pipeline.
return record
log_request("summarize", "small-model", 1800, 150, 0.4, 3.1)Printing JSON lines is a simple starting point. Most log and metrics systems can ingest it directly.
Choose the right metrics
Averages hide the cases users complain about. Track these instead:
- Cost per request, by feature and model. This is the unit economics number. Also track cost per successful outcome, such as cost per resolved ticket, when you can.
- Latency percentiles. The p50 shows the typical request. The p95 and p99 show the slow tail. Track time to first token and total time separately, because they have different causes.
- Token distributions. Watch input and output tokens at p50 and p95. A rising p95 on output tokens often means the model has started to ramble or a prompt change removed a length instruction.
- Error and retry rates. Rate-limit errors (HTTP 429) and timeouts both cost time, and retried requests can cost money.
- Cache hit rates. Track both your response cache and the provider's cached input tokens. A falling hit rate means a change broke the stable prefix or the key.
- Quality score. Run your small evaluation set on a schedule or on a sample of live traffic. A cost drop that comes with a quality drop is not a saving.
The following code computes percentiles and cost totals from a list of records.
from collections import defaultdict
def percentile(values, q):
if not values:
return None
ordered = sorted(values)
index = min(len(ordered) - 1, int(round(q * (len(ordered) - 1))))
return ordered[index]
def summarize(records):
by_feature = defaultdict(list)
for r in records:
by_feature[r["feature"]].append(r)
report = {}
for feature, rows in by_feature.items():
report[feature] = {
"requests": len(rows),
"total_cost_usd": sum(r["cost_usd"] for r in rows),
"p50_total_s": percentile([r["total_s"] for r in rows], 0.50),
"p95_total_s": percentile([r["total_s"] for r in rows], 0.95),
"p95_output_tokens": percentile([r["output_tokens"] for r in rows], 0.95),
"error_rate": sum(r["status"] != "ok" for r in rows) / len(rows),
}
return reportSet budgets at three levels
A budget is a number you decide in advance, plus an action to take when you cross it. Without the action, it is only a wish.
- Per-request budget. Cap the cost and time of a single call. Set
max_tokens, trim the prompt to a token limit, and set a client timeout. This prevents one runaway request from costing far more than normal. - Per-user or per-feature budget. Limit how much one user, tenant, or feature can spend in a window, such as a day. This contains abuse, loops, and a single expensive customer.
- Global budget. A monthly or daily ceiling for the whole application, set from the finance side and checked against actual spend.
Also set latency budgets. A latency budget states, for example, that p95 time to first token for the chat feature must stay under 1.5 seconds. It gives alerts a threshold and gives you a reason to reject a change that slows the product.
The next example enforces a per-feature daily spend limit with a soft warning level and a hard stop.
import time
from collections import defaultdict
class BudgetExceeded(Exception):
pass
class DailyBudget:
def __init__(self, limits_usd, warn_fraction=0.8):
self.limits = limits_usd # {"summarize": 50.0, ...}
self.warn_fraction = warn_fraction
self.spent = defaultdict(float)
self.day = time.strftime("%Y-%m-%d")
def _roll_day(self):
today = time.strftime("%Y-%m-%d")
if today != self.day:
self.day = today
self.spent.clear()
def check(self, feature):
"""Call before a request. Raises if the hard limit is already reached."""
self._roll_day()
limit = self.limits[feature]
if self.spent[feature] >= limit:
raise BudgetExceeded(f"{feature} reached its daily limit of ${limit:.2f}")
def record(self, feature, cost_usd):
"""Call after a request. Returns 'warn' once spend passes the warning level."""
self._roll_day()
self.spent[feature] += cost_usd
if self.spent[feature] >= self.limits[feature] * self.warn_fraction:
return "warn"
return "ok"
budget = DailyBudget({"summarize": 50.0})
budget.check("summarize")
print(budget.record("summarize", 0.0012))This in-memory version works for a single process. With several servers, keep the counter in shared storage such as a database or Redis, and expect small overshoots because requests run concurrently.
Alert on change, not only on thresholds
Fixed thresholds catch big failures. Many regressions are smaller, so also compare against recent history. Useful alert rules include:
- Daily spend is more than 1.5 times the trailing seven-day average.
- p95 time to first token is above the latency budget for 15 minutes.
- Mean input tokens per request for a feature rose more than 20 percent after a deploy.
- Provider cache hit rate fell below its usual range.
- Error or retry rate is above 2 percent.
- The scheduled evaluation score fell below the bar you set when you chose the model.
Tag each record with a version, such as a prompt version or deploy ID. When an alert fires, you can then compare before and after for the same feature and find the change that caused it.
Common errors
- Counting only successful calls. Failed and retried requests may still consume tokens or time. Log every attempt.
- Alerting on averages. A mean latency can look healthy while p99 is unusable.
- No per-feature breakdown. A single total cost number cannot tell you which change caused a rise.
- Stale price tables. Providers change prices and add models. Keep the table in one place and review it regularly.
- Budgets with no owner. An alert that no one is responsible for is ignored. Name an owner per feature.
- Logging full prompts by default. Prompts can hold personal data. Log sizes and identifiers, and store text only under a deliberate policy.
- Ignoring quality. Cost and latency alerts do not notice a model that got worse. Include an evaluation signal.
Exercises
Exercise
A feature's mean latency is unchanged, but users report slow answers. Which metric would you check first, and why?
Show answer
Check p95 or p99 total latency, and p95 time to first token. Averages hide a slow tail, so a small share of very slow requests can leave the mean almost unchanged while affecting real users.
Exercise
Daily spend doubled after a deploy, but request count is flat. List two likely causes you can confirm from the logs in the table above, and the field you would check for each.
Show answer
First, the prompt or retrieved context grew, so check input_tokens (and cached_input_tokens if caching stopped working). Second, outputs got longer or retries increased, so check output_tokens and retries. Grouping by prompt version or deploy ID shows which change started it.
Exercise
Two servers each run the DailyBudget class above with a $50 daily limit for the same feature. What goes wrong, and how do you fix it?
Show answer
Each process keeps its own counter, so combined spend can reach about $100 before either one stops. Store the counter in shared storage, such as Redis or a database, so all servers update one total. Small overshoots can still happen because concurrent requests check before others record.