How to Monitor LLM API Costs Before They Spike
If you're asking how to monitor LLM API costs, the short answer is: track token usage per request, break it down by key/team/feature, and set alerts before you hit a billing threshold — not after. Most teams find out about cost spikes when the monthly invoice lands, which is too late to do anything but wince.
This article covers the practical mechanics: what to log, how to attribute spend to the right source, which tools make this easier, and how to set up alerts so you're never surprised again.
Why LLM costs are hard to monitor by default
Unlike a fixed-price SaaS subscription, LLM API spend is usage-based and highly variable. A few things make it harder than monitoring, say, database or hosting costs:
- Token counts aren't intuitive. A "short" prompt with a long system prompt or large context window can cost far more than it looks.
- Output tokens cost more than input tokens on most providers, and verbose model responses can quietly inflate bills.
- Usage is often shared across one API key. If your whole team or app uses a single key, you have no idea which feature, customer, or teammate is driving cost.
- Retries and errors still cost money in some setups, especially if you're not checking response status before counting tokens.
- Provider dashboards are often delayed by hours, so by the time you see a spike, it's already happened.
The fix isn't a single tool — it's a monitoring habit built from logging, attribution, and alerting.
Step 1: Log token usage on every request
Every reasonable LLM API returns token counts in the response metadata. Capture them immediately, don't estimate them after the fact.
const res = await fetch("https://api.subtoapi.app/v1/messages", {
method: "POST",
headers: {
"Authorization": `Bearer ${process.env.SUBTOAPI_KEY}`,
"Content-Type": "application/json"
},
body: JSON.stringify({
model: "claude-sonnet-4",
max_tokens: 500,
messages: [{ role: "user", content: "Summarize this ticket." }]
})
});
const data = await res.json();
logUsage({
feature: "ticket-summary",
input_tokens: data.usage.input_tokens,
output_tokens: data.usage.output_tokens,
model: data.model,
timestamp: Date.now()
});
Store this in whatever you already use for logs or analytics — a database table, a logging service, or even a flat file for a side project. The point is consistency: every request gets logged, no exceptions.
Step 2: Attribute spend to a source
Raw token counts are useless without context. You need to know which feature, customer, or team member generated the cost. The most reliable way to do this is per-key or per-tag attribution rather than trying to reconstruct it from logs later.
Two common patterns:
- One API key per environment or team. Separate keys for staging, production, and internal tools make it obvious where spend is coming from on the provider's own usage page.
- Tag requests at the application level. Pass a feature or customer identifier alongside the request and store it with your usage log, then aggregate by tag.
If you're issuing keys to multiple team members or customer-facing features, having separate application keys with individual usage visibility saves you from writing this attribution layer yourself. SubToAPI issues scoped sub_live_... keys per team member or app, and usage metadata comes back with every response — see the docs for the exact fields.
Step 3: Aggregate daily, not just monthly
Monthly totals tell you there was a problem. Daily or hourly aggregates tell you when it started, which is what you need to actually fix it.
A simple approach:
SELECT
DATE(timestamp) as day,
feature,
SUM(input_tokens) as total_input,
SUM(output_tokens) as total_output
FROM usage_logs
GROUP BY day, feature
ORDER BY day DESC;
Run this daily and eyeball the trend. If a feature's token usage doubles overnight, you want to know within a day, not at the end of the billing cycle.
Step 4: Set budget alerts, not just reports
Monitoring without alerting is just a dashboard nobody checks. Set hard thresholds:
- Daily spend ceiling per feature or team — alert if exceeded.
- Per-request token ceiling — catch runaway prompts or infinite loops before they rack up cost.
- Rate of change alert — flag if daily spend grows more than, say, 50% day-over-day.
A basic cron-based check:
const todayTotal = await getTodaySpend();
if (todayTotal > DAILY_BUDGET) {
await sendAlert(`Daily LLM spend exceeded budget: $${todayTotal}`);
}
This doesn't need to be sophisticated. A Slack webhook firing on a threshold breach is enough to stop a bad deploy or an abusive user from draining your budget overnight.
Step 5: Review prompt and model choice regularly
Monitoring surfaces the data; acting on it is where the savings happen. Common fixes once you see where cost concentrates:
- Switch a high-volume, low-complexity feature to a cheaper/faster model.
- Trim system prompts and few-shot examples that are padding every request.
- Cap
max_tokenson features where verbose output isn't needed. - Cache repeated prompts or responses where the input doesn't change often.
None of this requires guessing — it requires the per-feature breakdown from Step 2 to tell you where to look first.
Where SubToAPI fits
If you're building on Claude and want this monitoring without building the logging pipeline yourself, SubToAPI gives you per-key usage metadata on every response, so you can attribute cost by team member or application key out of the box. Plans start at €9/month for Solo, with Team and Scale tiers for multi-seat usage tracking. You can try it with a free trial at signup, and the quickstart guide covers getting your first key issued and logging usage in a few minutes.
questions
Do I need a special tool to monitor LLM API costs, or can I just use provider dashboards? Provider dashboards work for a rough total but rarely give per-feature or per-team breakdowns, and updates are often delayed. For anything beyond a single-person project, logging usage yourself or using a layer that returns per-key metadata gives faster, more actionable data.
What's the single biggest cost driver to watch? Output token count. Output tokens are typically priced higher than input tokens, and verbose model responses compound quickly across high request volumes. Capping max_tokens is often the fastest cost fix.
How often should I check LLM API costs? Daily at minimum for production systems. Set automated alerts for budget thresholds so you're not relying on manually checking a dashboard — by the time you remember to look, the spike may already be a week old.