Build an Exact Usage Ledger for Chunked LLM Responses
Data Structure DesignModel answerLast updated
Design a billing ledger that merges streamed token deltas and one-shot totals, validates events strictly, and keeps all money as integer nano-USD to avoid floating-point drift.
Usage Ledger for a Metered Text-Generation Service
A text-generation service charges per token, with different prices for input (prompt) tokens and output (completion) tokens. Usage records reach your billing code in one of two ways:
- One-shot requests send a single record carrying the final token counts.
- Streamed requests send several partial records (deltas) while text is being produced. The request's usage is the sum of its deltas. A delta flagged as final closes the request.
Write a class TokenBillingManager that accepts these records, rejects bad ones, and reports exact costs.
Money representation
Never use floats for money. Every amount is an integer count of nano-USD (1 USD = 1,000,000,000 nano-USD). For instance, $3.00 per million tokens is 3,000 nano-USD per token.
Interface
class TokenBillingManager:
def __init__(self, rates: dict[str, dict[str, int]]):
# rates[model] = {"input_nano_per_token": int,
# "output_nano_per_token": int}
...
def record_event(self, event: dict) -> None:
# Raises ValueError for any malformed or disallowed event.
...
def get_request_cost(self, request_id: str) -> int:
# Accumulated cost in nano-USD. KeyError if the id is unknown.
...
def get_request_tokens(self, request_id: str) -> tuple[int, int]:
# (prompt_tokens, completion_tokens). KeyError if the id is unknown.
...
def get_total_cost(self) -> int:
# Sum of the costs of all recorded requests, in nano-USD.
...
Event fields
| Field | Type | Notes |
|---|---|---|
request_id | str | non-empty |
model | str | non-empty, must be a key of rates |
is_stream | bool | whether this event belongs to a streamed request |
prompt_tokens | int | >= 0 |
completion_tokens | int | >= 0 |
is_final | bool | optional, defaults to False; True closes a streamed request |
When to raise ValueError
- A required field is missing, has the wrong type (a
boolor afloatwhere an integer count is expected counts as wrong), or a string field is empty. - Either token count is negative.
- The model is not in
rates. - A non-streaming event arrives for a
request_idthat already exists, or any event arrives for a stream that has already been finalized. - The event's
is_streamdisagrees with the mode the request was first recorded with. - The event names a different
modelthan the one already attached to thatrequest_id.
Example
rates = {"claude-sonnet": {"input_nano_per_token": 3000,
"output_nano_per_token": 15000}}
m = TokenBillingManager(rates)
m.record_event({"request_id": "a", "model": "claude-sonnet",
"is_stream": False,
"prompt_tokens": 100, "completion_tokens": 50})
assert m.get_request_cost("a") == 1_050_000
m.record_event({"request_id": "b", "model": "claude-sonnet",
"is_stream": True, "prompt_tokens": 200,
"completion_tokens": 10, "is_final": False})
m.record_event({"request_id": "b", "model": "claude-sonnet",
"is_stream": True, "prompt_tokens": 0,
"completion_tokens": 40, "is_final": True})
assert m.get_request_tokens("b") == (200, 50)
assert m.get_request_cost("b") == 1_350_000
assert m.get_total_cost() == 2_400_000
Constraints
- Up to 100,000 events.
- Each token count is between 0 and 1,000,000,000.
request_idhas 1 to 128 characters.record_event,get_request_cost, andget_request_tokensmust be O(1) on average.
What to deliver
Implement the class, explain how you keep state consistent when an event is rejected, and justify why exact integer arithmetic and incremental accumulation give correct totals.
Hints
Hint 1
Cost is linear in token counts and the model is fixed per request, so the cost of a request equals the sum of the costs of its individual events. You can add each event's cost to a running total immediately instead of recomputing later.
Hint 2
In Python, isinstance(True, int) is True. To reject booleans and floats as token counts, compare type(x) is int rather than using isinstance.
Hint 3
Do every check first and only then write to state. If a rejected event leaves even one counter changed, the per-request cost and the global total will drift apart.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This is a small stateful ledger. The arithmetic is trivial; the difficulty lies in strict validation and keeping state consistent when events are rejected.
State
_rates: a private copy of the price table, stored asmodel -> (input_rate, output_rate). Copying means later mutation of the caller's dict cannot change billing._requests:request_id -> recordwith fieldsmodel,is_stream,prompt,completion,cost,finalized._total: a running integer sum of all request costs.
Why incremental accumulation is correct
Cost per event is p * r_in + c * r_out. Because the model, and hence the rates, never change for a request, the sum over events equals (sum p) * r_in + (sum c) * r_out, which is the cost of the accumulated token counts. So each event just adds its delta to the request's cost and to _total. Nothing needs recomputing, and _total always equals the sum of per-request costs because both are updated on the same code path.
Why integers
Floats cannot represent most decimal prices exactly and lose precision when many small amounts are summed. Integer nano-USD is exact. Python ints have arbitrary precision, so there is no overflow. In a fixed-width language you must note that int64 tops out near 9.2e18 nano-USD (about $9.2B). The worst case here (1e5 events x 1e9 tokens x a rate in the thousands, for both token types) can exceed that, so you would use 128-bit integers or checked arithmetic.
Validation order
- Shape: the event is a dict and contains all required keys.
- Types:
request_idandmodelare non-emptystr;is_streamandis_final(if present) arebool; token counts satisfytype(x) is int, which rejectsTrue,5.0, and numpy ints. - Range: both counts are
>= 0. - Model: the model is registered.
- State (only if the id exists):
- existing request is non-streaming: reject, since it is complete on arrival;
- existing stream is finalized: reject;
- incoming
is_streamisFalse: reject (this also covers a mode mismatch); - incoming model differs from the stored one: reject.
Every one of these raises ValueError, so which branch fires first for overlapping cases does not affect observable behavior.
Atomicity
All raise statements happen before the first write. The commit step only does arithmetic and dict writes, which cannot fail. A rejected event therefore leaves no trace: not in the request's tokens, not in its cost, not in the total, and no phantom request entry is created.
Code
class TokenBillingManager:
_REQUIRED = ("request_id", "model", "is_stream",
"prompt_tokens", "completion_tokens")
def __init__(self, rates):
self._rates = {}
for model, r in rates.items():
a, b = r["input_nano_per_token"], r["output_nano_per_token"]
if type(a) is not int or type(b) is not int or a < 0 or b < 0:
raise ValueError(f"invalid rates for {model!r}")
self._rates[model] = (a, b)
self._requests = {}
self._total = 0
def record_event(self, event):
if not isinstance(event, dict):
raise ValueError("event must be a dict")
for k in self._REQUIRED:
if k not in event:
raise ValueError(f"missing field: {k}")
rid = event["request_id"]
model = event["model"]
is_stream = event["is_stream"]
p = event["prompt_tokens"]
c = event["completion_tokens"]
is_final = event.get("is_final", False)
if type(rid) is not str or not rid:
raise ValueError("bad request_id")
if type(model) is not str or not model:
raise ValueError("bad model")
if type(is_stream) is not bool or type(is_final) is not bool:
raise ValueError("flags must be bool")
if type(p) is not int or type(c) is not int:
raise ValueError("token counts must be int")
if p < 0 or c < 0:
raise ValueError("negative tokens")
if model not in self._rates:
raise ValueError("unknown model")
st = self._requests.get(rid)
if st is not None:
if not st["is_stream"]:
raise ValueError("request already complete")
if st["finalized"]:
raise ValueError("stream finalized")
if not is_stream:
raise ValueError("mode mismatch")
if st["model"] != model:
raise ValueError("model changed")
# commit: no failures possible below
r_in, r_out = self._rates[model]
delta = p * r_in + c * r_out
if st is None:
st = {"model": model, "is_stream": is_stream,
"prompt": 0, "completion": 0,
"cost": 0, "finalized": False}
self._requests[rid] = st
st["prompt"] += p
st["completion"] += c
st["cost"] += delta
self._total += delta
# a one-shot request is complete immediately
st["finalized"] = (not is_stream) or is_final
def get_request_cost(self, request_id):
return self._requests[request_id]["cost"]
def get_request_tokens(self, request_id):
s = self._requests[request_id]
return (s["prompt"], s["completion"])
def get_total_cost(self):
return self._total
Complexity
- Time: every method is O(1) average (hash lookups and constant arithmetic). Construction is O(M) for M models.
- Space: O(M + R) for R distinct request ids. Individual events are not stored.
Edge cases and common mistakes
prompt_tokens=Trueorcompletion_tokens=5.0must raise;isinstancealone lets booleans through.is_stream=0is an int, not a bool, and must be rejected.- A missing
is_finalmeansFalse; a non-boolis_finalis invalid. - Zero-token deltas are valid. A zero-token chunk with
is_final=Trueis a natural way to close a stream. - A stream that never receives a final chunk still reports its accumulated cost; billing does not wait.
- Creating the request record before validation finishes leaves a ghost entry after a rejection. Validate first, create later.
- Updating the request cost but not
_total(or vice versa) is the classic half-applied bug. - Querying an unknown id raises
KeyError; with no events,get_total_cost()returns 0. - Rates should also be validated at construction (integers, non-negative) so bad configuration fails early.
Possible follow-ups
- Thread safety: guard
record_eventwith a lock per request id, or a single lock if contention is low, so the check-then-commit sequence is atomic. - Idempotency: add an event id to deduplicate retried deliveries.
- Persistence: append accepted events to a write-ahead log so the ledger can be rebuilt after a crash.
- Price changes: store the rate version on the request at creation so mid-stream price updates do not reprice earlier tokens.