Cost Attribution for Shared LLM Gateways
· 19 min read
A shared LLM gateway without attribution becomes a black hole: one provider invoice and no join key to product surfaces. Staff engineers require tenant, product, and caller tags on every call, emit normalized usage events, version price tables, roll agent fan-out with correlation ids, and wire budgets to policy—not slide-deck chargeback.
Untagged traffic is unowned spend
Shared gateways earn their keep by centralizing auth, model routing, retries, and safety filters. They fail when usage lands in one provider invoice with no join key back to product surfaces. Without request-level tags—tenant id, workspace, feature flag, caller service, model tier—you cannot answer whose prompt burned the budget or whether a regression doubled completion tokens.
Treat attribution as a gateway contract, not a BI afterthought. Reject or quarantine calls that omit required metadata in staging; in production, default tags must still be unambiguous enough for chargeback and incident response.
Anonymous internal scripts and forgotten cron jobs are frequent offenders. Require service identity on every path, including batch eval runners that share the same API key as customer traffic.
When finance asks for a single monthly number, push back with dimensional breakdowns—rollup without dimensions is how opaque spend returns.
Mobile and web clients should not choose model routes that bypass the gateway; shadow keys hide tenant burn from the team that owns quotas.
Audit quarterly for API keys without tag enforcement—keys outlive owners and become untagged firehoses.
Shadow billing reports to integrators before hard enforcement—teams fix tags faster when they see hypothetical chargeback than when prod suddenly returns 400.
Partner with security on key rotation: every rotated key should inherit tag policy automatically—manual spreadsheet key lists always drift.
Treat missing tags as a reliability bug with the same urgency as missing auth—both break trust in shared infrastructure.
Make attribution a gateway contract
Publish a schema for required headers or signed JWT claims: tenant, product area, environment, caller id, optional user session hash (never raw PII in tags). Document optional tags for experiments and A/B routes.
Validate at the edge before the provider call. Fail closed in non-production when tags are missing; in production, apply safe defaults only when caller id is a known platform service—not for arbitrary user tokens.
Version the contract like an API. Breaking tag renames require migration windows and dual-write to analytics until dashboards update.
Platform teams own the contract; product teams own tag vocabulary for features. Without that split, every squad invents incompatible product names.
Log rejected requests with reason codes so integrators fix tags without opening tickets guessing why calls fail.
Supabase edge functions and Cloudflare Workers should attach the same tag set whether the caller is Expo mobile or a nightly cron—consistency beats perfection.
Map tag vocabulary to your permission model—tenant ids in auth tokens should match tenant ids in usage events without manual copy-paste in app code.
Meter tokens, price dollars, reconcile both
Providers bill on input tokens, output tokens, cached tokens, tool calls, and sometimes image or audio units. Your gateway should emit normalized usage events: token splits, model id, latency class, cache hit flag, and provider request id for dispute resolution.
Convert to dollars with a versioned price table keyed by model and effective date so historical reports stay auditable when list prices change. Never rewrite past dollar totals silently when prices update—store both tokens and priced amount per event.
Reconcile gateway totals to provider invoices weekly. Small drift is normal; persistent gaps mean shadow traffic, wrong model mapping, or double-counting retries.
| Field | Why finance cares | Why engineering cares | | --- | --- | --- | | Tenant id | Chargeback | Quota enforcement | | Model id | Rate changes | Routing regressions | | Cached tokens | Discount proof | Cache ROI | | Correlation id | One user session | Agent fan-out |
Include eval and CI traffic in separate product tags so production dashboards exclude synthetic load unless intentionally compared.
Retention policy for raw usage events should match finance audit needs—often ninety to three hundred sixty-five days—without storing prompt bodies unless debug mode explicitly allows sampled retention.
Model fallback chains should emit separate events per hop so you see when cost spikes come from retries to premium models—not from traffic volume alone.
Correlation ids for agent fan-out
Agents that fan out to multiple model calls need a correlation id that rolls child costs into a parent session. Otherwise product dashboards under-count agent workflows and over-count leaf microservices.
Propagate correlation from the user session through tool calls, retrieval hops, and sub-agents. Each hop appends a span id so flamegraphs of spend match flamegraphs of latency.
When a parent job retries, inherit the same correlation root so finance does not see three unrelated spikes for one user action.
Batch jobs should emit batch id plus item index tags so map-reduce LLM spend is attributable per tenant dataset.
Incident response for cost spikes starts from correlation: filter top tenants by summed child events, not by single leaf service names alone.
Publish p95 tokens per correlation id so product sees when a single user session triggers expensive multi-hop plans—not only aggregate tenant totals.
Chargeback views engineering can act on
Finance-friendly monthly rollups are necessary but insufficient. Engineering needs daily spend by feature and model so they can cut temperature, shrink context, or switch tiers. Product needs per-tenant burn rates for pricing and fair-use enforcement. Publish both views from the same usage stream—never two pipelines that disagree.
Credit semantic-cache hits and prompt-cache discounts explicitly in engineering dashboards. If you hide savings, teams stop investing in cache keys; if you over-credit, finance disputes the model.
Document who pays for shared platform overhead versus tenant-driven traffic—eval infrastructure, shared rerankers, and safety classifiers need a line item.
Expose self-serve dashboards to feature owners with drill-down to top prompts by token volume—not to raw prompt text unless debug policy allows sampled access.
Align chargeback granularity with how teams actually ship: feature flag id often beats org-chart cost center for day-to-day decisions.
Offer export APIs so finance can pull CSV with the same dimensions engineering uses—duplicate manual exports breed mistrust between teams.
Quotas, caps, and cache credits
Expose soft quotas and hard caps per tenant with clear 429 semantics and Retry-After headers. Soft limits warn product owners; hard limits protect shared provider accounts from one tenant exhausting rate limits for everyone.
Quota policy should distinguish interactive traffic from batch backfills—same tenant may have different buckets.
Cache credits belong in attribution: record pre-cache versus post-cache token counts separately so ROI math is honest.
When tenants buy prepaid credits, ledger events must tie to usage events with idempotency keys to avoid double deduction on retries.
Document escape hatches: break-glass keys for incidents still require tags so postmortems can exclude emergency spend from SLA chargeback if policy allows.
Review quota thresholds after model price changes—token caps that made sense at old rates may block legitimate usage silently.
Prepaid enterprise contracts should surface remaining balance in the gateway response headers for integrators building admin UIs—surprise hard stops erode trust.
Budgets, alerts, and quality
Attribution without enforcement is a report. Wire budgets to gateway policy: warn at seventy percent of monthly envelope, throttle non-critical routes at ninety percent, and page owners on runaway fan-out detected by correlation id velocity.
Pair cost alerts with quality metrics so teams do not silently degrade answers to hit a number—track deflection, task completion, or eval score alongside spend for the same feature slice.
Alert on tag cardinality explosions—a misconfigured caller spamming unique product ids can break metrics storage as surely as token spikes break budget.
Instrument tag validation failures as a first-class metric—spikes often precede billing incidents by days when integrators deploy bad releases.
Run game days that simulate tenant quota exhaustion and verify UX degrades honestly rather than failing open to unlimited provider spend.
A shared LLM gateway is an internal product. Cost attribution is part of its SLA—same as availability and latency—not a quarterly spreadsheet export.
Compare cost-per-successful-outcome when routing changes—not only cost per request—so cheaper routes that trigger extra regenerations do not win on dashboards while losing in invoices.
Executive summaries should show top three tenants by dollar delta month-over-month with named owners—anonymous top-spender lists never get prioritized fixes.
Review attribution after every acquisition or tenant merge—duplicate tenant ids in usage streams double-charge or hide spend until someone reconciles manually.
Keep a single canonical tenant registry linked to billing and gateway tags.
Operational checklist for cost attribution
Before calling attribution done, confirm owners and automated checks—not slide bullets.
Every authenticated route requires tenant, product, and caller tags validated at the gateway. Usage events land in a durable stream with model, token splits, cache flags, and correlation ids. Price table version stored on each priced event.
Weekly reconciliation to provider invoice within agreed tolerance. Dashboards for finance rollup and engineering daily feature spend share one pipeline. Quotas documented with 429 behavior and break-glass procedure.
Agent and batch workloads use correlation or batch ids. Cache savings visible without inflating credits. Budget alerts tied to quality metrics for the same feature slice.
Review checklist after each pricing or routing change; add one item that would have caught the last surprise bill faster. Publish internal runbook: where to query spend for a tenant, how to trace a spike, who approves quota overrides.
Escalate repeated untagged traffic to the same severity as untagged production deploys—both are unowned risk.
Train new service owners with a worked example: trace one user session from gateway log through priced events to dashboard row—documentation without a trace example rarely sticks.
Add attribution readiness to gateway launch checklists alongside auth and rate limits—shipping routes without tags creates debt finance remembers longer than engineering does.
Frequently asked questions
What is the minimum tag set on every LLM request?
Should dashboards show tokens or dollars?
Who pays for shared safety and eval traffic?
Can we throttle to save cost without hurting quality?
Sources
- OpenAI — Managing costs — openai.com
- Anthropic — Rate limits — anthropic.com
- Cloudflare Workers AI — Pricing — cloudflare.com
- FinOps Foundation — What is FinOps — finops.org
Related on this site
Related service
AI-powered product development
Ship AI features to production: tooling, retrieval, evaluation, safety boundaries, and operable backends.
Published on September 14, 2026 by Berktug Berke Ates.