Immutable measurement of model/tool consumption with tenant, run, provider request, meter dimensions, source, and dedupe identity.
Before the clock
A dashboard estimates; a ledger accounts.
The live UI can show provisional token/cost estimates. Budget enforcement and invoices require immutable usage identity, effective-dated prices, reservations, provider receipts, double-entry entries, and explicit adjustments. Never mutate a closed financial fact.
Temporary budget hold created before uncertain usage. It prevents concurrent work from spending the same remaining allowance.
Effective-dated rate card that defines unit, currency, region, tier, token category, minimums, and rounding.
Comparison of platform estimates with authoritative provider receipts; differences append corrections instead of rewriting history.
Opening promptDesign a multi-tenant AI usage and billing service for model calls, streaming tokens, cached tokens, images/audio, and external tools across many providers. Enforce project/user/org budgets and quotas before and during work, show near-real-time spend, reconcile late provider records, and produce auditable invoices.
Money is an invariant, not an analytics query
Assume 3,000 organizations, 400,000 users, 60 million model requests/day, 12 providers, and 25,000 usage events/second at peak. Design the service.
I will separate admission, measurement, pricing, accounting, and presentation. Before a call, admission reserves budget and checks hard quotas. During/after the call, the gateway emits idempotent usage events. Pricing applies the rate card effective for that request contract. A double-entry ledger records provisional and finalized value. Provider receipts reconcile differences. Dashboards and invoices are projections of the ledger, not parallel sources of truth.
I need to clarify whether we bill pass-through cost or markup, prepaid versus postpaid, currency/tax, provider contract time basis, token categories, streaming cancellation, free tiers/credits, hard versus soft budgets, maximum tolerated overspend, invoice close/reopen policy, and which source is authoritative when local and provider counts disagree.
Define units and money before storage
What usage types and user journeys are in scope?
Units include input, cached-input, output, reasoning, image, audio seconds, embeddings, batch discounts, tool invocations, data egress, and fixed operation fees. Each provider adapter maps native receipts to canonical meter dimensions without erasing provider detail. Users see per-run estimates; admins set monthly org budgets plus project/user/model/tool quotas, alerts, and approval thresholds; finance closes invoices, posts credits, and audits discrepancies.
Functional flows: quote/reserve, stream usage, extend reservation, finalize/release, ingest provider receipts/files, price, reconcile, aggregate, alert, invoice, correct, export. NFRs: P99 admission under 50 ms, usage durability 99.999%, dashboard lag under two minutes, hard-budget overspend bounded to a configured exposure, invoice error under one basis point, seven-year ledger retention, and tenant/currency isolation. Payment collection and tax filing are outside the first design.
Write the accounting rules down
Which invariants do you make transactional?
- One logical provider request maps to one canonical usage identity even if gateways/reconcilers retry.
- Money uses integer minor units or micros with explicit currency; token quantities use integers; no binary floating-point accounting.
- A price is selected by a documented business timestamp and contract/rate-card version pinned to the request.
- Reservation + posted charges cannot exceed a hard budget except the explicitly configured in-flight exposure.
- Ledger entries append and balance debits/credits; corrections and invoice adjustments never edit prior entries.
- A closed invoice pins its line aggregation and ledger cutoff. Late facts create a credit/debit memo or controlled reopen—not silent change.
- Every customer-facing amount traces to usage events, price calculation, provider receipt status, and ledger entries.
Estimate cost and event amplification
Use mock prices of $2 per million input tokens and $8 per million output tokens, with 3,000 input and 1,200 output tokens per request. What load and exposure do we get?
Sixty million requests/day is 694 requests/s average. Per request mock cost is 3,000/1M × $2 + 1,200/1M × $8 = $0.0156. Daily provider cost is about $936,000. With a 1.30 reservation headroom, admission may hold $0.02028 per expected request, or $1.217M total if every request were simultaneously reserved—which it is not; reservations follow concurrency and expiry.
If each request emits start, two streaming increments, terminal estimate, and provider-reconciliation event, that is 300 million events/day or 3,472/s average; the supplied 25,000/s peak is plausible. At 700 bytes/event, raw event log is ~210 GB/day. Hot online budget state is small; immutable event/ledger retention and high-cardinality aggregation dominate storage.
daily cost = 60,000,000 × $0.0156 = $936,000
usage events/s avg = 60,000,000 × 5 ÷ 86,400 = 3,472
AI cost and reservation lab
All prices are invented mock inputs in USD per one million units.
The calculator is a planning model. Real providers distinguish token classes, regions, batch/caching, minimums, commitments, currencies, taxes, and negotiated rates.
Keep measurement, price, and accounting distinct
Show your schema and the critical APIs.
ProviderRequest owns the platform/provider correlation and pinned rate contract. UsageEvent is immutable, dimensioned, and deduplicated by provider/gateway sequence. PriceVersion maps canonical meter dimensions to integer micros and rounding/minimum rules. Reservation holds a maximum liability against a hierarchical budget. LedgerTransaction contains balanced entries such as customer accrued usage, provider cost accrual, reserved liability release, credit, and adjustment.
Admission is a command with an idempotency key and estimated maximum units. It returns one reservation and signed permit. Streaming increments reference monotonically increasing cumulative counters so retries are differences, not double charges. Finalize closes the local estimate and releases unused hold. Provider ingestion records raw receipt plus normalized facts. Invoice close pins ledger cutoff and query manifest.
Fast admission, durable accounting
Walk a streaming model call from preflight through the invoice.
The model gateway asks the admission service with org/project/user, model/provider, maximum token/tool plan, and run idempotency key. Policy computes hierarchy and price estimate, atomically reserves allowance in the budget shard, and returns a short-lived permit. The gateway invokes the provider and emits cumulative usage snapshots through a durable regional collector, then finalizes with local tokenizer/provider fields and response status.
The canonicalizer validates dimensions and dedupe sequence, the pricing service selects the request’s pinned rate version, and accounting posts balanced provisional ledger entries plus releases unused reservation. Provider receipt ingestion arrives by API/file/webhook later, normalizes exact provider units, and a reconciler posts variance entries. Materialized aggregates feed alerts/dashboard. Invoice close reads finalized ledger entries up to cutoff, applies contract/tax/credit rules, stores line lineage, and signs the invoice manifest.
Prevent concurrent overspend
Ten thousand agents start in three regions when an organization has only $5,000 left. Each might cost up to $1. How do you enforce the budget without a global lock on every token?
I distinguish a hard financial budget from high-rate operational quotas. The authoritative budget shard owns available = limit + credits − posted − active_reservations. Admission performs compare-and-set/transactional decrement for the requested maximum, with idempotency and expiry. Only 5,000 one-dollar reservations succeed; the rest queue, downgrade, require approval, or fail according to policy. Regions route that organization to one budget authority or consume preallocated bounded regional escrow.
Streaming usage is cumulative. When actual use approaches the hold, the gateway requests an extension before allowing more output/tool calls. Failure to extend stops generation safely and records why. Cancellation/finalization posts actual charge and releases the difference. Expiry alone cannot release an active call: gateway heartbeats or lease ownership prevent double release; a sweeper reconciles abandoned reservations after a grace period.
For token-rate limits, local token buckets can tolerate bounded drift. For money, any regional escrow is part of the explicit maximum overspend envelope and is periodically rebalanced—never unlimited eventual counters.
The stream ends without a final receipt
A client disconnects after 70,000 output tokens. The provider may continue generating and sends its final record 48 hours later. What is billed and when?
The gateway emits cumulative observed usage throughout the stream, so the ledger has a provisional lower bound even if the terminal callback is lost. It actively cancels the provider request on client disconnect when supported, records cancellation acknowledgment or UNKNOWN_PROVIDER_STATE, and retains enough reservation for the configured worst-case continuation until reconciliation or timeout policy.
We post provisional usage to the dashboard but mark it estimated. When the provider receipt arrives with the final cumulative units, its idempotency identity is provider account + request ID + receipt version. Reconciliation compares the exact canonical dimensions and appends a variance: debit for additional usage or credit for overestimate. If the customer invoice closed, policy either creates an adjustment on the next invoice or controlled credit/debit memo; the old invoice remains immutable.
Alerts distinguish missing terminal receipt from real cost anomaly. Repeated provider lag can increase reservation factor or disable hard-budget use for that provider.
70K tokens, disconnect, cancel response missing. Local value is provisional lower bound.
Hold worst-case continuation, query provider status, and block/restrict new spend if account exposure grows.
Append receipt variance and, if closed, a linked adjustment—never mutate usage or invoice history.
Price by contract time, not dashboard time
A provider changes prices at midnight UTC, the customer contract changes at midnight local time, and a six-hour agent spans both. Which price applies?
There are at least two valuations: provider cost and customer charge. Each has an effective-dated rate contract and explicit selection basis. I prefer pinning the price version when a logical provider request starts; if contract says per-usage chunk time, each cumulative delta carries provider event time and is priced accordingly. The rule is data, not worker-local clock.
The six-hour agent may create several provider requests and tool calls; each usage event stores occurred_at, recorded_at, region, provider request, run, and pinned price IDs. Bitemporal storage handles backdated contract corrections. Currency conversion pins an approved FX rate/version and rounding order. Invoice lines aggregate integer micros by meter/price/currency before final minor-unit rounding.
We test exact boundaries, daylight-saving transitions, cached versus input tokens, batch discounts, minimum charges, canceled calls, and provider pricing revisions. “Current price × total tokens” is not auditable.
Duplicates and contradictory receipts
A gateway retries usage events, the provider sends the same receipt twice with a corrected version, and local tokenization differs by 3%. How do you reconcile?
Gateway snapshots use (request_id, meter, cumulative_sequence); duplicate/out-of-order snapshots collapse to the maximum accepted cumulative value, with negative deltas rejected or treated as explicit corrections. Provider receipts use their immutable receipt/version IDs; duplicate same-version events are no-ops, while corrected versions append a supersession and variance.
The source-authority matrix is meter-specific. Provider invoiceable units usually win for provider cost. Customer charging may use provider units or a contractually defined local tokenizer; the decision and tolerance are versioned. A 3% discrepancy opens a reconciliation case, blocks finalization above threshold, and tracks tokenizer/model/provider version. We never overwrite local observation to make the books match.
Invariant monitors compare total provider cost accrual to provider statements, customer charges to contract rules, reservations to active runs, and every ledger transaction’s debits to credits.
Protect money and sensitive prompts separately
What security and multi-tenancy controls are required?
Usage records should reference prompt/response hashes and classification, not raw content. Tenant/account IDs live in every partition and ledger key. Provider credentials remain in the model gateway; metering sees request identity and units, not secrets. Fine-grained roles separate budget admin, price admin, invoice close, credit issuance, support view, and audit. High-value adjustments use dual approval.
Ledger/event stores use encryption, append-only writer roles, integrity checkpoints, WORM exports, and account-level reconciliation. Idempotency keys are tenant-scoped and unguessable. Audit captures who changed rate cards, budgets, credits, invoice state, and policy. Regional usage collectors persist locally through control-plane outage and never route EU content; only privacy-safe meter dimensions replicate globally where policy allows.
Measure accounting quality, not event throughput
How do you operate and roll out the system?
Health: admission latency/denial, reservation contention/age/leaks, usage collector lag/loss/duplicates, pricing failures, unpriced events, provider receipt lag, reconciliation variance, ledger imbalance, aggregate lag, alert delivery, invoice close duration, and regional escrow exposure. Quality: percentage finalized from provider truth, cost/charge variance, invoice dispute and correction rate, budget overspend envelope, per-provider tokenizer difference, orphan requests, and line-level audit completeness.
Rollout shadows gateway counts against provider bills, shows estimates without enforcement, enables soft alerts, then hard budgets for low-risk providers, then invoices in parallel with finance reconciliation. Rate-card changes run historical test vectors and canary accounts. Every stage retains old projections, rollback, manual override with reason, and a global stop on new reservations.
Close the books clearly
Give me your concise summary and the major trade-off.
The Token Ledger reserves budget before a provider call, meters cumulative usage idempotently during and after it, prices each dimension under a pinned effective-dated contract, and posts balanced append-only ledger entries. Provider receipts arrive later and append reconciliation variances. Dashboards are provisional projections; closed invoices pin a cutoff and receive explicit adjustments rather than history edits.
Hard budgets use one authority per account or bounded regional escrow; token quotas can be looser. The central trade-off is admission availability versus overspend certainty: I make the exposure explicit and bounded rather than pretending eventually consistent counters enforce money exactly.
Complete reference
Data model: keys, invariants, access paths
| Entity | Primary key / fields | Invariant | Primary access path |
|---|---|---|---|
ProviderRequest | (tenant_id, request_id); provider/account/model, external_request_id, price IDs, run, state | One logical request and pinned valuation context | Gateway finalize; receipt match; audit |
UsageEvent | (tenant_id, source, request_id, meter, sequence/version); cumulative units, occurred/recorded time | Immutable; retries cannot double-count; corrections explicit | Canonicalize; price; diagnose |
PriceVersion | (contract_id, meter, effective_from, version); currency, micros/unit, minimum, rounding | No mutation after use; explicit time basis | Quote; price event; invoice explain |
BudgetAccount | (tenant_id, scope_type, scope_id, period); limit, posted, active_reserved, version | available = limit + credits − posted − reserved | Admission and admin view |
Reservation | (tenant_id, reservation_id); idempotency key, max micros, lease, state, run/request | Finalize/release exactly once in business terms | Extend, cancel, sweep, reconcile |
LedgerTransaction / Entry | (tenant_id, transaction_id)/(transaction_id,line_no); accounts, micros, currency | Entries append; debits equal credits per currency | Invoice, audit, balance/reconcile |
ProviderReceiptVersion | (provider_account, receipt_id, version); raw ref, normalized units, statement period | Duplicate is no-op; correction supersedes and posts variance | Cost reconciliation; dispute |
Invoice | (tenant_id, invoice_id, version); cutoff, line manifest, status, signature | Closed line set immutable; later memo links back | Customer PDF/API; finance audit |
Concrete API surface
/v1/usage:quote-and-reserveTenant/scope/model/max units + Idempotency-Key → reservation, permit, price estimate, expiry./internal/usage/{request}:snapshotMonotonic cumulative meter counters; duplicate/out-of-order behavior defined./internal/usage/{request}:extendCompare-and-set reservation extension before more generation/tool execution./internal/usage/{request}:finalizeTerminal local observations, response status; post provisional charge and release unused hold./v1/provider-receipts/{provider}Signed API/file ingestion; raw immutable receipt + normalized version./v1/usage?scope=&from=&to=&status=Cursor/snapshot aggregate with provisional/finalized split and price lineage./v1/invoices/{id}:closeFinance role + expected version; pins ledger cutoff/line manifest; dual approval as configured./v1/invoices/{id}/adjustmentsAppend credit/debit memo linked to original lines and reason; never rewrite closed invoice.Usage metering and financial control architecture
Admission protects budget before uncertain work. Immutable measurement flows through pricing and a balanced ledger; provider truth reconciles later.
Reservation is not revenue; estimate is not final
One provider call moves through explicit financial states. Each arrow appends facts; it does not edit the prior state.
Consistency ledger
Operational scorecard
Platform health
Outcome quality
Visual values are illustrative. In production, every metric needs a unit, time window, tenant/slice dimension, owner, alert threshold, and prescribed action.
Phased rollout
Shadow count
Compare gateway token/tool observations with provider files; no enforcement or customer charge.
Estimate
Near-real-time provisional dashboard and soft alerts with clear reconciliation status.
Enforce
Hard budgets for selected providers/accounts; bounded exposure, extensions, stop semantics, support playbook.
Close books
Parallel invoices, finance sign-off, then production close with adjustment/appeal workflow.
Interview traps
- 01Using floating-point dollars or rounding every streaming chunk independently.
- 02Treating local token estimate, provider cost, and customer charge as one number.
- 03Enforcing a hard budget with eventually consistent counters and unlimited regional drift.
- 04Charging duplicate streaming snapshots instead of using cumulative monotonic counters.
- 05Releasing an expired reservation while the provider call is still active.
- 06Pricing historical usage with the current public rate card.
- 07Overwriting usage or a closed invoice when a corrected provider receipt arrives.
- 08Blindly trusting either provider or local tokenizer without a meter-specific authority policy.
- 09Putting raw prompts, secrets, or model outputs in broad billing logs and exports.
- 10Measuring event throughput but not orphan requests, reconciliation variance, or budget exposure.
Glossary
- Accrual
- Accounting recognition of cost/charge when incurred, even if the provider invoice or cash payment arrives later.
- Bitemporal price
- Tracks when a price is contractually effective and when it was recorded/corrected in the system.
- Double-entry
- Every financial transaction has balanced debit and credit entries per currency.
- Escrow quota
- Preallocated regional allowance bounding overspend without synchronously calling one global authority per event.
- Idempotent cumulative meter
- Each event reports total units through sequence N; retries do not re-add prior units.
- Integer micros
- Represent money as whole millionths of a currency unit to avoid binary floating-point error.
- Price version
- Immutable rate-card contract selected by an explicit time and dimension policy.
- Provisional
- Useful estimate not yet reconciled with the designated authoritative receipt.
- Reconciliation
- Match platform observations to provider statements and append explicit differences.
- Reservation
- Temporary hold against spend limit before uncertain work begins.
- Rounding order
- Contractual sequence for aggregating micros, applying discounts/tax/FX, and rounding to invoice minor units.
- Usage dimension
- Canonical billable category such as input token, cached token, image, audio second, or tool invocation.
One-minute spoken recap
Admission atomically reserves budget under a pinned price estimate. Measurement emits cumulative idempotent usage events. Pricing uses effective-dated provider and customer contracts in integer micros. Accounting posts balanced append-only entries and releases unused holds. Reconciliation appends variances from late provider receipts. Presentation clearly separates provisional dashboards, finalized ledger value, and closed invoices. Availability may use bounded escrow; money never relies on unbounded eventual counters.