KatInterview

Build an Exact Usage Ledger for Chunked LLM Responses

Data Structure DesignModel answer
HardModel answerData Structure Designdesign-dshash-mapvalidation

Last 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:

  1. One-shot requests send a single record carrying the final token counts.
  2. 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

FieldTypeNotes
request_idstrnon-empty
modelstrnon-empty, must be a key of rates
is_streamboolwhether this event belongs to a streamed request
prompt_tokensint>= 0
completion_tokensint>= 0
is_finalbooloptional, defaults to False; True closes a streamed request

When to raise ValueError

  1. A required field is missing, has the wrong type (a bool or a float where an integer count is expected counts as wrong), or a string field is empty.
  2. Either token count is negative.
  3. The model is not in rates.
  4. A non-streaming event arrives for a request_id that already exists, or any event arrives for a stream that has already been finalized.
  5. The event's is_stream disagrees with the mode the request was first recorded with.
  6. The event names a different model than the one already attached to that request_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_id has 1 to 128 characters.
  • record_event, get_request_cost, and get_request_tokens must 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.