12Token Ledger
30:00 MOCK

8090-oriented system design rehearsal · mock 12

Count every call. Balance every cent.

A 30-minute mock for multi-provider token and tool metering, online reservations, hierarchical budgets, quotas, invoice correctness, and late or contradictory provider data.

System
Multi-provider AI/tool usage accounting + controls
Actors
User, agent, org admin, finance, provider, support, auditor
Deep dives
Online reservation · reconciliation and invoice close
Clock
12 questions · 00:00–30:00
Money rule
Integer micros + append-only double-entry adjustments
Practice-only numbers. Every volume, latency, cost, and organization count on this page is an invented mock constraint—not an 8090 company fact.

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.

Research dossier ↗
Usage event

Immutable measurement of model/tool consumption with tenant, run, provider request, meter dimensions, source, and dedupe identity.

Reservation

Temporary budget hold created before uncertain usage. It prevents concurrent work from spending the same remaining allowance.

Price version

Effective-dated rate card that defines unit, currency, region, tier, token category, minimums, and rounding.

Reconciliation

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.
Starting question

Money is an invariant, not an analytics query

Interviewer

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.

Candidate

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.

Clarification

Define units and money before storage

Interviewer

What usage types and user journeys are in scope?

Candidate

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.

Correctness

Write the accounting rules down

Interviewer

Which invariants do you make transactional?

Candidate
  1. One logical provider request maps to one canonical usage identity even if gateways/reconcilers retry.
  2. Money uses integer minor units or micros with explicit currency; token quantities use integers; no binary floating-point accounting.
  3. A price is selected by a documented business timestamp and contract/rate-card version pinned to the request.
  4. Reservation + posted charges cannot exceed a hard budget except the explicitly configured in-flight exposure.
  5. Ledger entries append and balance debits/credits; corrections and invoice adjustments never edit prior entries.
  6. A closed invoice pins its line aggregation and ledger cutoff. Late facts create a credit/debit memo or controlled reopen—not silent change.
  7. Every customer-facing amount traces to usage events, price calculation, provider receipt status, and ledger entries.
Estimation

Estimate cost and event amplification

Interviewer

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?

Candidate

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.

cost/request = 3,000 × $2 / 1,000,000 + 1,200 × $8 / 1,000,000 = $0.0156
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.

Interactive
Mock cost / request$0.0156
Mock provider cost / day$936K
Reserve / request$0.0203
Average usage events/s3,472

The calculator is a planning model. Real providers distinguish token classes, regions, batch/caching, minimums, commitments, currencies, taxes, and negotiated rates.

Data contracts

Keep measurement, price, and accounting distinct

Interviewer

Show your schema and the critical APIs.

Candidate

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.

High-level design

Fast admission, durable accounting

Interviewer

Walk a streaming model call from preflight through the invoice.

Candidate

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.

Deep dive A

Prevent concurrent overspend

Interviewer

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?

Candidate

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.

Failure injection 01

The stream ends without a final receipt

Interviewer

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?

Candidate

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.

Failure injection 01 · late provider truth
Observed now

70K tokens, disconnect, cancel response missing. Local value is provisional lower bound.

Exposure control

Hold worst-case continuation, query provider status, and block/restrict new spend if account exposure grows.

Forty-eight hours later

Append receipt variance and, if closed, a linked adjustment—never mutate usage or invoice history.

Deep dive B

Price by contract time, not dashboard time

Interviewer

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?

Candidate

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.

Failure injection 02

Duplicates and contradictory receipts

Interviewer

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?

Candidate

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.

Tenant and financial controls

Protect money and sensitive prompts separately

Interviewer

What security and multi-tenancy controls are required?

Candidate

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.

Observability and rollout

Measure accounting quality, not event throughput

Interviewer

How do you operate and roll out the system?

Candidate

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.

Closing minute

Close the books clearly

Interviewer

Give me your concise summary and the major trade-off.

Candidate

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.

Study appendix

Complete reference

Data model: keys, invariants, access paths

EntityPrimary key / fieldsInvariantPrimary access path
ProviderRequest(tenant_id, request_id); provider/account/model, external_request_id, price IDs, run, stateOne logical request and pinned valuation contextGateway finalize; receipt match; audit
UsageEvent(tenant_id, source, request_id, meter, sequence/version); cumulative units, occurred/recorded timeImmutable; retries cannot double-count; corrections explicitCanonicalize; price; diagnose
PriceVersion(contract_id, meter, effective_from, version); currency, micros/unit, minimum, roundingNo mutation after use; explicit time basisQuote; price event; invoice explain
BudgetAccount(tenant_id, scope_type, scope_id, period); limit, posted, active_reserved, versionavailable = limit + credits − posted − reservedAdmission and admin view
Reservation(tenant_id, reservation_id); idempotency key, max micros, lease, state, run/requestFinalize/release exactly once in business termsExtend, cancel, sweep, reconcile
LedgerTransaction / Entry(tenant_id, transaction_id)/(transaction_id,line_no); accounts, micros, currencyEntries append; debits equal credits per currencyInvoice, audit, balance/reconcile
ProviderReceiptVersion(provider_account, receipt_id, version); raw ref, normalized units, statement periodDuplicate is no-op; correction supersedes and posts varianceCost reconciliation; dispute
Invoice(tenant_id, invoice_id, version); cutoff, line manifest, status, signatureClosed line set immutable; later memo links backCustomer PDF/API; finance audit

Concrete API surface

POST/v1/usage:quote-and-reserveTenant/scope/model/max units + Idempotency-Key → reservation, permit, price estimate, expiry.
POST/internal/usage/{request}:snapshotMonotonic cumulative meter counters; duplicate/out-of-order behavior defined.
POST/internal/usage/{request}:extendCompare-and-set reservation extension before more generation/tool execution.
POST/internal/usage/{request}:finalizeTerminal local observations, response status; post provisional charge and release unused hold.
POST/v1/provider-receipts/{provider}Signed API/file ingestion; raw immutable receipt + normalized version.
GET/v1/usage?scope=&from=&to=&status=Cursor/snapshot aggregate with provisional/finalized split and price lineage.
POST/v1/invoices/{id}:closeFinance role + expected version; pins ledger cutoff/line manifest; dual approval as configured.
POST/v1/invoices/{id}/adjustmentsAppend credit/debit memo linked to original lines and reason; never rewrite closed invoice.
END-TO-END MAP

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.

Usage metering and financial control architecture Users and agents call model and tool gateways. Admission reserves budgets. Usage collectors send events to pricing and accounting. Provider receipts reconcile and invoices aggregate ledger entries. EDGE / INTAKE AUTHORITATIVE CONTROL ASYNC / EXECUTION / DERIVED User / agentrun intentModel gatewaystream + cancelTool gatewaypriced effectsProvider receiptslate truthAdmission policyquota + reservationUsage collectordurable cumulative eventsPrice registryeffective contractsReconcilervariance + casesBudget shardsauthoritative exposureDouble-entry ledgerappend + balanceUsage aggregatesprovisional/finalInvoice servicecutoff + adjustments Cross-cutting: tenant policy · audit · metrics · lineage · replay
ACCOUNTING FLOW

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.

Usage accounting lifecycleA quote reserves funds, streaming usage posts provisional charges, provider receipt reconciles, and invoice close or adjustment follows.RESERVE− availableSTREAMcumulative unitsextend or stopFINALIZEpost provisionalrelease remainderRECONCILEappend varianceINVOICEclose or memoevery amount traces to request → usage → price → balanced entries → receipt status

Consistency ledger

Invariant
Consistency
Why
Safe degraded behavior
Budget reserve/finalize
Transactional per budget shard
Concurrent work cannot spend same allowance
Queue/deny or bounded preallocated regional escrow
Usage collection
At-least-once cumulative events
Gateways retry and disconnect
Durably buffer; mark dashboard provisional
Pricing
Deterministic effective version
Same usage must always value the same way
Quarantine unpriced event; do not guess current price
Ledger
Append-only balanced transaction
Financial audit and corrections
Stop affected posting; preserve raw events for replay
Dashboard/invoice projection
Eventual / close is transactional
Analytics may lag; closed books may not mutate
Show lag/status; append adjustment

Operational scorecard

Platform health

Admission P99
41ms
Collector lag
19s
Unpriced events
0.006%
Reservation leaks
0.02%

Outcome quality

Provider variance
0.07%
Invoice accuracy
99.992%
Audit lineage
99.9%
Hard-budget exposure
$82 max

Visual values are illustrative. In production, every metric needs a unit, time window, tenant/slice dimension, owner, alert threshold, and prescribed action.

Phased rollout

GATE 01

Shadow count

Compare gateway token/tool observations with provider files; no enforcement or customer charge.

GATE 02

Estimate

Near-real-time provisional dashboard and soft alerts with clear reconciliation status.

GATE 03

Enforce

Hard budgets for selected providers/accounts; bounded exposure, extensions, stop semantics, support playbook.

GATE 04

Close books

Parallel invoices, finance sign-off, then production close with adjustment/appeal workflow.

Interview traps

  1. 01Using floating-point dollars or rounding every streaming chunk independently.
  2. 02Treating local token estimate, provider cost, and customer charge as one number.
  3. 03Enforcing a hard budget with eventually consistent counters and unlimited regional drift.
  4. 04Charging duplicate streaming snapshots instead of using cumulative monotonic counters.
  5. 05Releasing an expired reservation while the provider call is still active.
  6. 06Pricing historical usage with the current public rate card.
  7. 07Overwriting usage or a closed invoice when a corrected provider receipt arrives.
  8. 08Blindly trusting either provider or local tokenizer without a meter-specific authority policy.
  9. 09Putting raw prompts, secrets, or model outputs in broad billing logs and exports.
  10. 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.