The interview problem

Practice prompt

Meter a streaming model service by input and output tokens. Customers can set a hard spending limit. Requests retry, streams disconnect, workers crash and final usage sometimes arrives late. Design reservations, an auditable usage ledger and reconciliation.

Original practice question, not a reported company prompt. Reviewed September 26, 2026. Prices and workload figures are invented for arithmetic; they are not vendor rates.

1. Define billable work before designing counters

Clarify whether billing counts generated tokens, delivered tokens or successfully completed responses. Assume actual generated output is billable even if the client disconnects, but infrastructure retries initiated by the service are not charged twice for the same logical request. Cached input, tool calls and other resources have separate meters if the contract includes them.

Separate three concepts: resource consumption, customer charges and cash collection. They may differ after credits or service failures. A usage ledger is not a substitute for a general accounting ledger. Spend 5 interview minutes on the contract, 10 on reservations, 10 on durable events, 10 on failure reconciliation and 10 on scale and billing boundaries.

2. Reserve before starting expensive work

A proposed request API includes tenant, logical request ID, model, maximum output tokens and an idempotency key. Determine the price version and an upper bound on billable work. Atomically reserve that amount against the tenant's available allowance. Define available balance as funded allowance minus settled charges minus active reservations. Reject or queue work when there is insufficient capacity.

Logical flow: authenticated request → reservation transaction → model execution → durable usage events → settlement → billing export. Persist request status, reservation, execution attempts and pricing version. An outbox dispatches admitted work after reservation commit, avoiding a request running with no corresponding budget record.

Retries with the same key and request parameters return the existing logical operation. Reusing a key with different parameters is an error. Execution attempt IDs remain distinct from billing request IDs so operational retries can be measured without automatically becoming extra customer charges.

3. Work a reservation and settlement example

Assume 8,000 input tokens priced at $2 per million and a maximum 2,000 output tokens at $8 per million. Reserve 8,000 × 2 / 1,000,000 + 2,000 × 8 / 1,000,000 = $0.032. If only 750 output tokens are generated, the settled charge is $0.016 + $0.006 = $0.022 and $0.010 is released.

With $1 available, at most 31 such maximum reservations can start concurrently: 31 × $0.032 = $0.992. A 32nd would require $1.024. Checking the balance independently on 32 gateways before incrementing a counter violates the limit. Use integer micro-units or exact decimal arithmetic with explicit rounding rules; binary floating-point totals are unsuitable for an auditable bill.

A hard cap requires a real upper bound, including every billable category. If hidden work or tools can exceed the reservation, constrain execution or obtain additional reservation before that work starts. An advisory dashboard limit based on asynchronously reported usage is a different promise.

4. Make usage events replayable

Workers emit authenticated usage records with logical request, attempt, meter, sequence, cumulative quantity and event time. Persist them durably at bounded intervals and on completion. Within one attempt, accept monotonically increasing cumulative totals and ignore duplicate or older sequences; do not add every cumulative value as if it were a delta.

The ledger stores raw observations and immutable settlement entries. A terminal usage observation can settle a reservation once, using a unique settlement key. Atomically replace the hold with the actual charge and release the difference; a crash between independent balance updates must not create extra spending capacity. If later reconciliation reveals an error, append a linked adjustment rather than rewriting history invisibly. Pin price and policy versions so replay months later produces the same interpretation.

For multiple execution attempts, explicitly select which work is customer-billable under the retry policy. Summing every attempt charges service failures to the user; taking the maximum across all attempts can also be wrong if the logical request contains separately billable stages. Model the contract rather than relying on a convenient aggregation rule.

5. Treat an unknown outcome as unknown

A client disconnect is not evidence that generation stopped. Signal cancellation, then settle from authoritative worker/provider usage after execution ends. If a worker crashes before the final record, reconcile persisted observations against execution records. Mark the request unresolved while evidence is incomplete; do not invent a precise charge from the requested maximum.

Likewise, reservation expiry must not release funds while an old worker can continue incurring billable work. Fence execution, confirm termination or retain a conservative unresolved hold. Leases alone do not stop an external model provider. If the system cannot stop or bound that provider's work, it cannot promise a strict instantaneous cap.

If the budget store is unavailable, fail closed for new hard-cap work. Existing bounded reservations may continue. In a regional partition, a single authoritative tenant balance or disjoint preallocated regional budgets can preserve the cap; independently writable full balances cannot. Transfers between regional budgets must avoid temporarily granting the same funds twice.

6. Scale the ledger and reconcile exports

At 10 million requests per day and three 300-byte records per request, raw event payload is 9 GB/day, or 270 GB per 30 days before replication and indexes. Average ingestion is about 347 records/second; a 20× peak is roughly 6,944/second. Long streams emitting frequent checkpoints can dominate these estimates, so measure records per request rather than assuming three forever.

Partition event ingestion for throughput, but serialize balance-affecting operations per tenant or budget bucket. Very large tenants need carefully bounded sub-budgets rather than one global row lock for every token. Meter at request/checkpoint granularity, not with a remote balance transaction per generated token.

Export settled usage through an outbox with stable export IDs. An external billing API can acknowledge receipt before aggregation is reflected in a dashboard. Track accepted, rejected, pending and reconciled exports separately. Compare internal meter totals with provider billing totals at a defined cutoff and investigate mismatches before finalization.

Late events across a billing boundary need a documented grace period or adjustment policy. Event time, settlement time and export time should all be retained. A new invoice period must not silently erase unresolved prior-period work or duplicate it in both periods.

7. Defend the trade-off

Large conservative reservations simplify caps but reduce concurrency. Smaller reservations improve utilization only if execution can pause before exceeding them. Synchronous accounting gives stronger admission guarantees at latency cost; asynchronous billing export is acceptable because it is not the admission authority.

Foundation: distinguish reservation from charge. Senior: handle a completed stream whose settlement response was lost. Staff: defend strict caps during regional partitions and late provider usage. Score 0–2 each for contract clarity, atomic reservations, replay safety, unknown-outcome handling and reconciliation. Full credit needs mechanisms and limitations. Continue with streaming inference and reliable event delivery.

Sources and next steps

The proposed reservation protocol, pricing example, failure analysis and rubric are original educational material.

Continue your preparation

Choose a connected learning path or browse more System design questions. Read our editorial method and attribution policy.