If you’re building a multi-tenant AI app, you’ve probably hit this kind of mismatch: every customer pays the same plan price, but at the end of the month the bill never adds up. One or two accounts eat half the monthly budget, and all you can see in the console is one grand total. Tracking LLM costs per customer and setting spend limits isn’t really a finance job — it’s a small piece of metering logic on your server.
This breaks down into three moves: attach your own customer ID to the request, multiply the token count in the response by your current unit price, and set a cap in your own ledger. None of these steps relies on any special platform-side capability — you can do all of it in your own code. The examples in this article all go through APIYI (apiyi.com)’s OpenAI-compatible endpoint. Switch to a different endpoint and the metering method stays exactly the same.

Why tracking LLM costs per customer matters more than watching the grand total
The grand total only tells you how much was spent, not who spent it. When plan prices are uniform, cost distribution is naturally long-tailed: most customers use a steady amount, a handful use a huge amount, and the average lands right between the two, so everything looks fine. Spendline’s analysis on 2026-10-04 pointed out that per-user cost masks the heaviest account — in their example, the heaviest account cost about 52 times the median. That 52x is the original article’s illustrative number, not anyone’s real bill, but the problem it illustrates is universal: using the average as your limit baseline is basically leaving the biggest opening for your most expensive customer.
The first benefit of per-customer metering is attribution. You can answer “which three customers drove this month’s incremental cost,” instead of vaguely saying model invocations went up. The second benefit is pricing: you finally learn which customer tier your current plan price is losing money on.
The third benefit is the limit itself. The value of a limit isn’t in blocking everyone — it’s in cutting off abnormal usage the moment it happens, rather than discovering it during month-end reconciliation.
Which Fields to Track for Per-Customer LLM Costs
You don’t need many bookkeeping fields—five core ones plus two auxiliary ones is plenty. Fewer fields means every row can be written to the database, aggregated, and reconciled. More fields usually just means nobody maintains them.
| Field | Where it comes from | What it’s for | Common pitfalls |
|---|---|---|---|
| Customer ID | You issue it yourself, carried with the request | Primary key for grouping and aggregation | Using email or phone as the primary key—when the customer changes it, the chain breaks |
| Model ID | Request parameter, but trust the value echoed back in the response | Determines which price tier to multiply by | Using an alias or routing, so records don’t match the real model |
| Input tokens | The usage field in the response |
Multiply by input price | Estimating by character count—big error margin in Chinese scenarios |
| Output tokens | The usage field in the response |
Multiply by output price | Streaming responses don’t capture the final usage |
| Cache read tokens | The usage field in the response |
Multiply by cache-read price | Double-counted with input tokens, inflating costs |
| Timestamp | You generate it yourself | Slicing windows by day and by month | Using only server local time—cross-timezone reconciliation won’t line up |
| Request ID | You generate it yourself | Idempotency and deduplication | Retried requests get billed twice |
For the customer ID, go with an internally generated, immutable identifier—not an email, phone number, or a nickname the customer can change. It needs to appear on both the request side and the log side so that a single usage record can be traced back to the specific request. The model ID should be the one echoed back in the response, not the alias you sent in the request. Otherwise, once upstream applies model routing, your costs get calculated at the wrong unit price.
One point worth calling out: we couldn’t verify whether the APIYI console supports aggregating bills by a custom customer ID, nor whether the response directly returns a converted amount field. So the entire approach in this article doesn’t depend on either of those capabilities—billing records and quota limits all live in your own service.
How to Calculate LLM Costs: Token Counts × Listed Unit Price
The pricing API returns three tiers of unit prices per model: input, output, and cache read. The values below come from a sample response from the APIYI (apiyi.com) pricing API dated 2026-12-04; units and conversion conventions follow the API field descriptions.
| Model ID | Input unit price | Output unit price | Cache read unit price |
|---|---|---|---|
| ergo-1.0 | 1 | 3 | 0.03 |
| claude-opus-5-5 | 4 | 20 | 0.2 |
| deepseek-v4.1-flash | 0.30 | 1.20 | 0.006 |
Two things stand out from this table. First, output costs more than input — ergo-1.0 has a 3x ratio, claude-opus-5-5 has a 5x ratio — so looking at each customer’s output token distribution explains cost differences better than looking at total tokens. Second, the cache read unit price is significantly lower than the input unit price: if the same repeated context hits the cache, the cost structure is completely different. That’s exactly why cache reads need their own column.
The cost formula for a single request is: input token count × input unit price, plus output token count × output unit price, plus cache read token count × cache read unit price.
If the API prices per million tokens, remember to convert the unit price to per-token first — otherwise you’ll be off by six orders of magnitude. Don’t hardcode unit prices as code constants: fetch the pricing API at startup or once a day, cache the result as a dictionary, and your ledger will automatically keep up when models are added or retired.

Quick Start: Three Steps to Per-Customer Limits in Your Own Service
Step 1: Include Your Own Customer ID in the Request
Don’t stuff the customer ID into the prompt — that burns tokens and isn’t reliable anyway. The right move is to put it in your own request headers or metadata, let your gateway validate it, and then forward it. Use https://api.apiyi.com/v1 as your base_url across the board — the OpenAI-compatible way of calling stays the same, you’re just adding one custom header.
headers = {
"Authorization": f"Bearer {api_key}",
"X-Customer-Id": customer_id, # Issued by you — don't use an email
"X-Request-Id": request_id, # Used for retry deduplication
}
The gateway layer needs to do two things: check that the customer ID belongs to the current session, and run a balance pre-check before forwarding. If the pre-check fails, return the limit message right away — don’t wait until the call finishes to find out you’ve gone over budget.
Step 2: Multiply the token count from the response by the listed price
Use the usage reported in the response as the source of truth—don’t estimate based on character count. A single Chinese character can map to one or more tokens, and in long-document scenarios the estimation error can grow to 20–30%. Field names aren’t fully consistent across providers; cache-read tokens are called cached tokens or cache read tokens in some implementations, so go by what the response actually returns.
price = PRICES[response.model] # Per-token unit price, from the pricing API
cost = (usage.input_tokens * price["in"]
+ usage.output_tokens * price["out"]
+ usage.cache_read_tokens * price["cache"])
When writing to the usage table, store the customer ID, model ID, all three token counts, converted cost, timestamp, and request ID together. Add a unique index on the request ID so retries don’t double-bill. Be especially careful with streaming calls: always take the final usage after the stream ends, and don’t bill on the first chunk.
Tip: If you don’t have usable test credits yet, you can sign up at APIYI (apiyi.com) to get free test credits. Use a few dozen requests to get the billing pipeline working end to end, then connect real customer traffic. The platform provides OpenAI-compatible endpoints—just change the base_url to switch.
Step 3: Set spending limits on your own account
Put the limits in your own service, not on the platform side. The minimum viable version has three actions: check the balance before the call, deduct after the call, and decide whether to trigger an alert or block after the deduction. In multi-instance deployments, there’s a timing window between the balance check and the deduction. Tighten that window with a database row lock or Redis atomic counter; otherwise ten concurrent requests from the same customer can break through the limit.
Pre-authorization and settlement is more robust than post-hoc deduction: reserve an amount based on average historical cost, then reconcile with the actual cost after you get the response. That way, even if the upstream times out and doesn’t return usage, the quota won’t be overdrawn indefinitely.
| Limit strategy | Trigger condition | Customer experience | Use case |
|---|---|---|---|
| Hard cap | Reject when balance is below zero | Direct error; manual credit increase required | Free credits, trial accounts |
| Soft cap | Alert at threshold without blocking | Seamless; ops team steps in | Primary limit for paying customers |
| Rate limit | Requests or tokens per unit time exceed limit | Brief queueing or degradation | Burst traffic protection, script abuse prevention |
| Model downgrade | Switch to a cheaper model near the limit | Slight quality drop but service continues | Cost-sensitive long-tail customers |
These four strategies are usually combined rather than chosen one at a time. A common combination is a soft cap plus rate limit for day-to-day protection, a hard cap only for trial accounts, and model downgrade as the last buffer.

How High Should You Set the Spending Limit?
The absolute number depends on your plan price and gross margin target, but the tiering approach is universal. Treat the plan price as the denominator and historical per-customer cost as the numerator, work out the cost ratio for each tier, and set your warning and cap lines from there.
| Tier | Warning line | Cap line | Over-limit action |
|---|---|---|---|
| Trial customers | 60% of plan quota | The plan quota itself | Block outright, guide them to upgrade |
| Standard paid | 80% of plan quota | 1.2x plan quota | Warn and degrade, don’t block immediately |
| High-value customers | 90% of plan quota | Negotiated individually | Customer success steps in |
The cap line sits a little above the plan quota so a normal customer doesn’t get burned at month-end by a single batch job. Trial customers don’t need that buffer — their whole value is proving they’re willing to pay.
Once the limits are live, you absolutely need a reconciliation step: every week, compare your own ledger against the platform bill on total volume. Deviations usually come from three places: cached-read tokens being counted again as input, streaming responses missing usage, and retried requests being billed twice.
| Deviation symptom | Possible cause | Fix |
|---|---|---|
| Own ledger higher than platform bill | Cached-read tokens and input tokens accumulated twice | List them separately; deduct cache hits from input tokens |
| Own ledger lower than platform bill | Final usage not captured for streaming responses | Read usage once after the stream ends; no per-chunk accounting |
| A single customer’s cost spikes abnormally | Retries causing duplicate accounting | Build a unique index on request ID; discard on write conflict |
| Model dimension doesn’t line up | Accounting by request alias instead of response echo | Use the model ID in the response as the source of truth |
Frequently Asked Questions (FAQ)
Q1: What is per-customer LLM cost tracking?
It means recording the token usage returned with each model response at the customer level, then multiplying that by the model’s current list price to get a dollar figure — so you see what each customer actually spent, instead of just one account-wide total.
Q2: Why isn’t the platform bill’s total, or the per-user average, good enough?
A total can’t be attributed to anyone, and an average hides the long tail. In the example Spendline published in its 2026-10-04 analysis, the heaviest account came in at roughly 52 times the median. Those numbers only illustrate the shape of the distribution — they aren’t a real bill — but they’re enough to show that using an average as your limit baseline leaves a big gap.
Q3: Can APIYI bill directly against my own customer IDs?
We weren’t able to confirm whether the platform console supports aggregating bills by custom customer ID, or whether responses include a converted cost field. The safe approach: put your customer ID in your own request headers, record both usage and cost in your own database, and treat the platform bill purely as a reference for reconciling the total.
Q4: Where should the limit sit relative to the plan price?
For trial customers, you can cap straight at the plan quota itself. For standard paying customers, leave some headroom — up to 1.2× the plan quota — paired with a downgrade path. For high-value customers, negotiate individually. The key is to have an alert threshold in place before a hard cap, so operations has time to step in before a customer gets blocked.
Q5: How do I quickly pull the current list prices and validate the accounting pipeline?
The pricing endpoint returns per-model prices for input, output, and cache reads — just cache them in a dictionary. During testing you can get free credits through APIYI (apiyi.com), run the three-step pipeline against real responses, and then calibrate the drift against the platform bill.
Q6: What are the known limitations of this approach?
Unit prices shift as models are added and retired, so you have to refresh them regularly rather than hardcode them; the field name for cache-read tokens varies by implementation, so adapt to what the response actually returns; with multiple instances there’s a time window between the balance check and the deduction, so you need an atomic operation as a safety net; and because pre-authorization amounts depend on historical averages, the first few requests from a new customer will be less accurate.
Key Points for Tracking LLM Costs Per Customer and Setting Spending Limits
- Attribution comes before limits: First be able to clearly account for how much each customer spent—then talk about whether to block.
- Five core fields: Customer ID, model ID, input tokens, output tokens, cache-read tokens.
- Usage should follow the response: Don’t estimate tokens by character count—the error gets amplified in long Chinese-text scenarios.
- Pull unit prices dynamically: The pricing API returns three tiers of unit prices per model; cache them into a dictionary and update it automatically as models come and go.
- Put limits in your own service: Look up balance, deduct, alert—three steps; for multiple instances, use atomic operations to tighten the time window.
- Don’t skip reconciliation: Compare your own ledger against the platform bill weekly; deviations usually come from cache reads, streaming, and retries.
Summary
Tracking LLM costs per customer isn’t complicated—what’s hard is keeping at it. Chain the three actions together and you get a complete closed loop: attach your own customer ID to the request, then once the response comes back, multiply the token count by the current unit price and write it to the database, and after deducting, check whether the limit line has been reached.
It’s worth emphasizing that this whole logic is built on your side, because we haven’t verified any platform-side capability to bill by custom customer ID—treating that as an external dependency introduces design risk. The unit-price layer can be read directly from APIYI’s (apiyi.com) pricing API, and the unified entry point stays OpenAI-compatible, so the retrofit cost is low.
We recommend using APIYI (apiyi.com) to first run the bookkeeping and limit chain through with a small amount of traffic, then gradually open it up to real customers, so reconciliation deviations can be caught before the impact grows.
References
-
APIYI Pricing API: returns per-model unit prices for input, output, and cache reads
- Link:
apiyi.com - Note: The unit prices in this article are sample values returned by the API on 2026-12-04. Actual billing is based on what the API returns in real time.
- Link:
-
APIYI unified entry point: an OpenAI-compatible interface with a
base_urlofapi.apiyi.com/v1- Note: You can include custom fields in request headers, which makes it easy to aggregate usage on your own service side.
-
Spendline Cost Distribution Analysis (2026-10-04): points out that per-capita cost can mask the heaviest accounts
- Note: The 52x figure in this article is a sample number from the original text, used to illustrate the shape of the distribution — it’s not real billing data.
Author: APIYI Technical Team
Technical discussion: Feel free to reach out to us on the APIYI homepage at apiyi.com. For more documentation, visit the docs center at docs.apiyi.com.