Dev.to AI πŸ€– Ai πŸ‘ 3 πŸ“– 9 min read

Your LLM Bill Says $865.26. Your Dashboard Says $966.58. Here's Where the Difference Comes From

The invoice is one number. The dashboard that is supposed to explain it is a sum() over log lines. Between the two sit three decisions nobody remembers making: which grain you count at, whether cached tokens were priced,

The invoice is one number. The dashboard that is supposed to explain it is a sum() over log lines. Between the two sit three decisions nobody remembers making: which grain you count at, whether cached tokens were priced, and what happens to rows that have no tenant on them. Together they are worth more than the rounding error everyone worries about.

I built a 30-day log to make the gap visible and measurable. It has 200,000 logical requests across 40 tenants, six features and three model tiers, with retries, cache hits, one 45-minute provider incident, 4.5% of rows missing a tenant tag, and 0.3% of lines truncated by the shipper. Because the log is generated, the invoice and the true per-tenant spend are known exactly, so every estimate below has a right answer to be compared against. Everything is standard-library Python 3.12 on a 2-vCPU Linux box, seed 20261204, and the whole run takes under ten seconds.

The same table has two grains

A request that times out and succeeds on retry produces two log lines. Both were billed. Only one is the user's experience.

That single fact breaks most home-made dashboards, because they aggregate rows and call the result "requests". In this log, 210,827 attempt rows belong to 199,419 logical requests β€” 10,590 requests were retried, and the extra attempts alone cost $94.52, 10.95% of the $865.26 bill.

Metric Per attempt row Per logical request
Rows counted 210,827 199,419
Success rate 93.95% 99.32%
p50 latency 944 ms 957 ms
p95 latency 3,477 ms 3,730 ms
Max latency 37,545 ms 70,372 ms

Read the top two rows together. A dashboard that divides successful rows by all rows reports a 6.05% failure rate; the failure rate a user experiences is 0.68%. The same data says "we are in trouble" and "we are fine", depending on the denominator. Neither number is wrong β€” they answer different questions, and shipping the row-based one into a status page is how a team spends a quarter on an outage that never happened.

The latency rows flip the bias the other way. Retries add waiting that only the request-level number sees: the p95 of first-try requests is 3,019 ms, the median of retried requests is 3,443 ms, and their p95 is 32,788 ms because a share of them hit 30-second timeouts. If you compute p95 over rows, the worst thing a user waited for (70.4 seconds) is missing entirely, because the two attempts that produced it are each unremarkable rows.

So the rollup keeps two sets of counters in one pass:

for row in rows:                       # row == one attempt
    key = (row.tenant or "__unattributed__", row.feature)
    a = agg.setdefault(key, TenantFeature())
    a.attempts += 1
    a.cost_micro += cost_micro(row)     # billing grain: every attempt
    a.prompt_tokens += row.prompt_tokens
    a.cached_attempts += row.cached

    req_lat[row.request_id] = req_lat.get(row.request_id, 0) + row.latency_ms
    req_meta[row.request_id] = key
    req_ok[row.request_id] = req_ok.get(row.request_id, False) or row.status == "ok"

for rid, total_ms in req_lat.items():  # outcome grain: one entry per request
    a = agg[req_meta[rid]]
    a.requests += 1
    a.successes += 1 if req_ok[rid] else 0

Two dicts, one pass, 2.7 Β΅s per row for the full rollup (0.57 s for 210,827 rows). The cost of getting this right is one extra dictionary.

The cache discount is 12% of your bill and 0% of your code

Prompt tokens are 60.8% of the cost in this log ($588.14 of $966.65 at list prices). If your cost function ignores the cache flag, you overpay the provider on paper by exactly the cached share of that. Measured: $103.68, or 11.71% above the invoice.

Because cache reuse is not uniform, the error is not uniform either. Tenants with high cache-hit rates are overcharged most: the worst here is overcounted by 15.3% ($6.17 true, $7.12 reported), and even the least affected tenant is overcounted by 5.8%. A per-tenant table with this bug does not just inflate the total β€” it reorders the middle of the table.

The fix is three lines and one integer base:

PRICES = {"cheap": (150_000, 600_000), "mid": (500_000, 1_500_000),
          "frontier": (3_000_000, 15_000_000)}   # micro-USD per 1M tokens

def cost_micro(row, discount_cache=True):
    p_in, p_out = PRICES[row.model]
    pt = int(row.prompt_tokens * 0.10) if (discount_cache and row.cached) else row.prompt_tokens
    return pt * p_in // 1_000_000 + row.completion_tokens * p_out // 1_000_000

Micro-dollars as integers, always. Floating-point dollars in an attribution pipeline produce totals that do not reconcile, and a cent that nobody can explain trains everyone to accept a gap that is dollars wide.

The aggregate can look fine while every row is wrong

Here are the three numbers this log produces for the same month:

Number Value What it hides
Provider invoice $865.26 the truth
Sum of per-tenant rows $823.62 4.81% of rows had no tenant tag
Sum with list-price prompts $966.58 11.71% cache overcount

The middle one is short by $41.64 because 4.5% of rows are background jobs and internal calls that never got a tag. Drop them silently and the dashboard is quietly missing a tenant-sized hole; the top tenant's share looks 5% larger than it is. The bottom one is long by $101.32. Notice that these two mistakes point in opposite directions and partially cancel: if you only check "does the total roughly match the invoice", the answer is "close enough", and both per-tenant columns are wrong.

The rule I now apply is boring and effective: print invoice, attributed and unattributed every time, and make the unattributed bucket a first-class row in the table β€” not a WHERE tenant IS NOT NULL.

def reconcile(invoice_micro, attributed_micro):
    gap = invoice_micro - attributed_micro
    return {"invoice_usd": invoice_micro / 1e6,
            "attributed_usd": attributed_micro / 1e6,
            "unattributed_pct": 100 * gap / invoice_micro}

If the unattributed share is above ~2%, the answer is not a better estimator. It is to tag the caller.

Percentiles, priced like the rest of your infrastructure

Exact percentiles mean holding every value: 1.6 MB for 199,419 latencies, which is fine until it is 40 services times 30 days. The honest thing is to pick an estimator and state its error. Measured against the exact request-level p95 (3,730 ms) and p99 (30,757 ms):

Estimator Memory p95 error p99 error Time for 200k
Exact list 1.6 MB 0.00% 0.00% β€”
PΒ² (5 markers) 120 B 0.07% 0.05% 0.18 s
Log histogram, 10% buckets 63 buckets, ~6 KB 2.04% 0.73% 0.07 s
Log histogram, 5% buckets ~120 buckets, 12 KB 0.30% 1.46% 0.07 s
Reservoir, 2,000 samples 16 KB 1.30% 0.62% 0.07 s

Two things are worth saying out loud. PΒ² is absurdly good for 120 bytes β€” 0.07% at p95 over 199,419 request latencies β€” but it assumes a stationary stream, so restart it at your aggregation window boundary and never feed it a month of data whose distribution changed mid-way. And the histogram's error is not monotonic in bucket width: 5% buckets do better at p95 (0.30% vs 2.04%) and worse at p99 (1.46% vs 0.73%), because p99 sits on the 30-second timeout spike and the wider bucket happens to bracket it better. Quantization error is luck at the edges; report the width, not a promise.

If log volume forces sampling, sample and measure the damage rather than guessing. Twenty replicates at each rate:

Sampled p95 error (median / p90) p99 of successful calls (median / p90)
10% (19,941 requests) 0.98% / 2.12% 1.53% / 3.67%
5% (9,970) 1.55% / 3.06% 1.19% / 2.90%
1% (1,994) 3.04% / 8.75% 4.18% / 7.02%

Cost totals survive sampling far better than percentiles do: a sum is linear, so a 1% sample times 100 is unbiased, and the noise averages out over thousands of rows. Percentiles do not: at 1%, two teams looking at two different days can disagree by 9% on p95 and both be reading the same system. Keep 10% of request-level rows and you get p95 within ~2%.

The change that shows up on the invoice three weeks later

On day 22, tenant-07 moved its agent traffic to the frontier model. Nothing failed, nothing alerted. The month's p95 moved 7.6% (3,466 β†’ 3,730 ms), which is inside normal weekly variation.

What actually changed:

tenant-07 Days 1–21 Days 22–30
Cost per request $0.0041 $0.0245
Cost per attempt $0.0039 $0.0214
Mean attempt latency 1,628 ms 3,080 ms
Share of the invoice 2.2% 5.9%

Six times the unit cost, hidden inside a tenant that was already the third-largest spender. The detector is not a fancy model; it is a daily series of cost per successful request, compared with its own trailing seven-day median. The snippet below prints anything above 2x, and on this log that fires 15 times in 30 days across 11 tenants β€” 14 of those alerts are ordinary daily noise. The rule I actually run requires 3x on two consecutive days, and that leaves exactly one tenant: tenant-07, from day 22, at 6.4x.

daily = {}                                  # (tenant, day) -> [cost_micro, successes]
for row in rows:
    if row.tenant:
        d = daily.setdefault((row.tenant, row.day), [0, 0])
        d[0] += cost_micro(row)
        d[1] += 1 if row.status == "ok" else 0

for tenant in {t for t, _ in daily}:
    series = [daily[(tenant, d)] for d in sorted(day for t, day in daily if t == tenant)]
    for i in range(7, len(series)):
        base = sorted(c / max(s, 1) for c, s in series[i-7:i])[3]
        today = series[i][0] / max(series[i][1], 1)
        if base and today > 2 * base:
            print(tenant, i + 1, round(today / base, 2))

A fixed fee is a policy decision, not an accounting fact

The last gap is the one that starts arguments. Your platform costs $1,200 a month in seats, observability and egress, and it has to land somewhere. Four defensible bases, same data:

Allocation basis Smallest tenant ($5.88 of model spend) Fee as % of its model spend
Equal $29.27 498%
Per request $8.73 149%
Per successful request $8.77 149%
Proportional to spend $8.18 139%

Equal allocation makes the smallest tenant's bill 5x its own usage, which is a fine way to lose a small customer. Per-request versus per-success differs by 0.5% for that small tenant, because success rates are clustered at 99%+. For the tenant with 1.087 attempts per request the two still land within 0.3% of each other ($40.12 vs $40.00), while the spend basis charges it $97.67 β€” because it is 8.5% of the bill. No basis is correct. What matters is that the basis is written down next to the number, because "your share is $40" is a customer-facing claim.

The pipeline, end to end

stats = ParseStats()
rows = list(parse_log("log.jsonl", stats))          # 0.88 s, 239k rows/s
agg, naive, req_lat, req_ok = rollup(rows)          # 0.57 s

totals = tenant_totals(agg)
attributed = sum(t.cost_micro for t in totals.values() if t is not totals["__unattributed__"])
print(stats.as_dict())                              # 636 bad lines, not zero
print(reconcile(invoice_micro, attributed))         # gap shown, not hidden
for name, t in sorted(totals.items(), key=lambda kv: -kv[1].cost_micro)[:5]:
    print(name, t.cost_micro / 1e6, t.cost_micro / 1e6 / t.successes)

Checklist, in the order the bugs actually happen:

  1. Cost is per attempt; latency and success are per logical request.
  2. Keep an __unattributed__ bucket and alert when it exceeds 2%.
  3. Price cached prompt tokens at the discounted rate, in integer micro-dollars.
  4. Report invoice, attributed and gap side by side, every run.
  5. Unit cost is per successful request, not per call.
  6. State the estimator and its measured error; prefer PΒ² for a window, histograms for a fleet.
  7. Sample logs only after measuring p95 error at that rate.
  8. Compare each tenant's daily unit cost with its own trailing median, not with the fleet's.
  9. Write the fixed-fee allocation basis next to the number.
  10. Count malformed lines: 0.3% here is 636 rows, about $2.60 of spend, and 581 requests that vanish from every count.

None of this requires a vendor. It requires deciding, once, which of the two grains each column belongs to β€” and refusing to let a total that happens to match the invoice stand in for numbers that don't.

Environment: Python 3.12.16, 2 vCPU (Xeon Platinum 8488C), no third-party packages. Synthetic 30-day log: 200,000 requests, 211,463 attempt rows, seed 20261204; generation takes 3.6 s and the aggregation plus every experiment above takes 4.3 s. All figures above come from the measured run, including the ones that make my estimator look worse than a wider bucket would.

Disclosure: the link below is my own store page. The code and numbers in this article are free to copy and reproduce; the paid workbook is an optional packaged version of the same workflow.

If you want the runnable version of this pipeline β€” the generator, the rollup, the estimator comparisons and the checklist as a single workbook β€” it is here: AI automation workbooks and templates.

πŸ“° Read the original article on Dev.to AI

Originally published by Dev.to AI. Aggregated on AIWithGhost for educational purposes β€” full credit and traffic to the original publisher.