How to Build a Billable Usage Meter for a Partner LLM API
Un'architettura pratica per trasformare le richieste LLM del tenant in addebiti cliente verificabili senza doppi tentativi di fatturazione, perdita di utilizzo in ritardo o riscrittura della cronologia dopo la variazione dei prezzi.
A provider cost record is not a customer invoice. If a Partner LLM API treats the two as equivalent, routing changes, retries, cached tokens, tool charges, credits, and delayed provider reports can produce unstable or unauditable bills.
A defensible meter separates three facts: what the provider processed, what the customer contract defines as billable, and what the billing system received. Connect those facts with immutable identifiers, but store them as separate records. This design makes each charge reproducible even after provider prices, customer plans, or routing policies change.
Start with the billable-unit contract
Before designing event schemas, define what the customer is buying. Common choices include provider-native tokens, successful requests, tool calls, normalized credits, or a hybrid of those units.
Tokens are transparent, but token categories and cache semantics differ among providers and models. Normalized credits hide those differences and can make a multi-model catalog easier to price, but customers need a published conversion rule. Per-request pricing is simple until requests vary significantly in length or invoke separately charged tools.
The contract must answer edge cases explicitly:
- Are cached input tokens free, discounted, or charged as normal input?
- Are failed requests billable when the provider processed tokens?
- Does a gateway retry count as a second customer charge?
- Does fallback to another model create one commercial request or two?
- How are streaming cancellations and partial outputs treated?
- Are web searches, image generation, embeddings, storage, and other tools separate units?
- When and how are quantities rounded?
Recommendation: Define these rules as a versioned machine-readable policy, not only as contract prose. The rating service should be able to apply the policy without guessing what a status code or provider field means.
Use three linked ledgers
A useful architecture has a raw usage ledger, a rated usage ledger, and a billing-export ledger. Provider costs and prepaid credits should also remain distinct accounting records.
1. Raw usage ledger
Emit one canonical event after every provider attempt reaches a terminal state. Preserve provider-native quantities instead of immediately reducing them to a single token total.
{
"usage_event_id": "use_01...",
"tenant_id": "tenant_42",
"customer_key_id": "key_7",
"workload_id": "support_assistant",
"internal_request_id": "req_912",
"attempt_id": "attempt_2",
"provider_request_id": "provider_req_...",
"provider": "provider_a",
"model_revision": "model-x-2026-09",
"input_tokens": 2400,
"cached_input_tokens": 1800,
"output_tokens": 320,
"tool_units": {"web_search": 1},
"terminal_status": "succeeded",
"started_at": "2026-12-03T10:14:00Z",
"completed_at": "2026-12-03T10:14:04Z",
"deduplication_key": "tenant_42:req_912:attempt_2"
}
Do not store prompts, responses, provider credentials, or unrestricted customer metadata in the billing event. A request reference is usually enough for investigation. This is also where usage analytics by customer key becomes valuable: a scoped key provides a durable attribution dimension without exposing its secret.
2. Rated usage ledger
Rating converts raw quantities into the units and price promised to the customer. The resulting record should be immutable and should identify both its source usage event and the exact pricing rules used.
{
"rating_id": "rate_01...",
"usage_event_id": "use_01...",
"tenant_id": "tenant_42",
"commercial_request_id": "req_912",
"plan_id": "partner_pro",
"price_book_version": "pb_2026_12_01",
"billable_units": [
{"dimension": "standard_credits", "quantity": 0.92}
],
"currency": "USD",
"unit_price": "0.010000",
"rounding_rule": "period_total_to_6_decimals",
"gross_charge": "0.009200",
"rated_at": "2026-12-03T10:14:05Z"
}
Use decimal arithmetic and explicit precision. Binary floating-point arithmetic can create small discrepancies that become material across large event volumes.
Pin the price-book version using the commercial event time defined in the contract—normally request acceptance or provider execution time. Never rerate historical events using the current price table. If a price was wrong, append a reversal and a corrected rating linked to the original.
3. Billing-export ledger
The export ledger records delivery to the invoicing or marketplace system. It should not replace either of the first two ledgers because downstream ingestion may be asynchronous, rejected, deduplicated, or excluded by an invoice cutoff.
Track states such as calculated, queued, submitted, accepted, rejected, invoiced, and reconciled. A successful network response proves only the stage documented by the destination.
Separate attempts from commercial requests
Retries are one of the easiest ways to double-charge a customer. The gateway may make several provider attempts for one customer request because of a timeout, retryable error, or fallback decision.
Represent both levels:
- An
attempt_ididentifies each provider call and supports provider-cost reconciliation. - A
commercial_request_idgroups attempts according to the customer contract.
Suppose provider A returns an ambiguous timeout after processing 1,000 input tokens. The gateway then succeeds with provider B. The raw ledger should retain both attempts because both may create provider cost. The rating policy can still produce one customer charge if the contract says infrastructure retries are not separately billable.
This distinction is especially important in a multi-model AI API gateway, where provider selection is an internal implementation detail rather than part of the customer’s commercial unit.
Export charges exactly once
“Exactly once” is not a property of a network request. Build it from deterministic identifiers, durable state, idempotent submission, and reconciliation.
- Commit the rated event and an outbox record in the same database transaction.
- Derive a deterministic billing-event identifier from the rating ID and export destination.
- Submit the outbox item with that identifier as the destination’s idempotency or unique event key.
- Persist the response and destination reference before marking the item accepted.
- Retry ambiguous failures with the same identifier and unchanged quantity.
- Process asynchronous rejection notifications and return rejected items to an operational queue.
Do not retry a rejected event under a new identifier unless it represents a new compensating event. Some marketplaces deduplicate usage within a time bucket and do not treat a retry with a different quantity as an amendment. Other billing systems accept events asynchronously, which means an initial submission response may not prove that the event will appear on an invoice.
Fact: Billing destinations differ in their accepted timestamp windows, deduplication dimensions, and invoice-finalization behavior. Treat those rules as adapter capabilities and verify them against current destination documentation.
Keep credits separate from charges
Prepaid and promotional credits are movements in a customer credit ledger, not negative provider costs and not edits to raw usage.
A credit ledger should record grants, reservations, consumption, release, expiration, and manual adjustments. Each movement needs an immutable ID, effective time, amount or unit quantity, and a link to the rating or invoice that consumed it.
For prepaid accounts, synchronous rating gives the strongest balance enforcement but can add latency and make inference depend on billing availability. Asynchronous rating is more resilient, but a customer can temporarily exceed the available balance.
A practical compromise is to reserve a conservative maximum before execution, settle the reservation after terminal usage is known, and release the remainder. The reservation is an authorization control; the rated event remains the final commercial record. Broader LLM cost management controls can use the same rated quantities without merging customer balances with provider spend.
Reconcile without letting provider reports set the invoice
Provider administrative reports are valuable evidence, but they can arrive late, be revised, or aggregate usage differently from the gateway. Use them to reconcile raw events and provider-cost records rather than to generate customer charges directly.
Aggregate both sides by provider, model revision, project or key, usage category, and UTC time bucket. Compare token and tool quantities first, then monetary cost. Apply documented tolerances for rounding and an aging window for late reports.
Classify variances instead of placing all mismatches in one queue:
- gateway event missing from the provider report;
- provider usage missing from the gateway ledger;
- quantity or cache-category mismatch;
- unknown model revision or price;
- duplicate raw event;
- late provider adjustment;
- currency, tax, or committed-spend difference.
Recommendation: Close customer billing from the rated ledger under a defined cutoff policy. Reconciliation findings that affect customers should produce append-only adjustments in a later open period unless the invoice can still be safely amended.
Give customers evidence they can audit
A customer-facing usage report should match the contract’s granularity. Show the billing period, key or application, model family, billable dimension, quantity, unit price, credits, adjustments, and charge. Provide traceable request references where appropriate, but omit prompts, responses, credentials, and internal provider account identifiers.
Per-request evidence provides strong dispute resolution but increases storage, privacy exposure, and downstream cardinality. Hourly aggregation is cheaper and fits many marketplace interfaces, but it weakens request-level analysis. One workable design retains request-level records internally while exporting deterministic hourly totals. Each aggregate stores the included rating IDs or a verifiable manifest digest.
Implementation checklist
- Publish the billable-unit and edge-case contract.
- Generate immutable raw events for every terminal provider attempt.
- Separate attempt IDs from commercial request IDs.
- Preserve token categories, cache units, tools, status, and model revision.
- Rate usage into a second ledger using a pinned price-book version.
- Use decimal arithmetic and explicit rounding rules.
- Export through a transactional outbox with deterministic event IDs.
- Track submission, acceptance, rejection, invoicing, and reconciliation separately.
- Represent corrections with reversals and linked replacement entries.
- Keep provider cost, customer charge, and credit movements in separate ledgers.
- Reconcile provider reports with aging windows and variance classifications.
- Test duplicate delivery, ambiguous timeouts, fallback, delayed usage, price changes, export rejection, credit expiration, invoice finalization, and tenant cancellation.
Build the meter around reproducibility
The decisive test is simple: months later, can the system explain a charge using the original usage event, the contract rule, the pinned price book, the export record, and any subsequent adjustment?
If those elements are immutable and linked, retries do not become accidental revenue, delayed reports do not silently rewrite invoices, and customer disputes can be answered with evidence. Provider reports then serve their proper purpose: checking the meter, not defining what the customer bought.