40What a request costs
40 What a request costs
An Airbnb ML round asked about trading off precision, recall, latency and infrastructure cost (1 report). For an LLM feature, the cost side comes down to three questions this problem asks in code: what one request costs, what caching its shared prompt saves at a given traffic, and when renting GPUs beats paying per token. This is practice in that shape, not a leaked question.
Set a 40-minute timer. Read one level at a time, and run only that level's tests until they pass:
pytest problems/40_request_cost -k level1. Earlier levels must keep passing.
A price is a dict of dollars per million tokens: input, output, read (a cache hit), write_5m and
write_1h (writing the cache with a 5-minute or a 1-hour lifetime).
Level 1. One request. request_cost(price, input_tokens, output_tokens, read=0, write=0, ttl="5m") returns the
dollars one request costs. read and write count how many of the input_tokens were served from the cache or
written to it, and ttl says which write price applies. The rest of the input is priced as plain input.
Level 2. Caching at a given traffic. hit_rate(per_hour, ttl_minutes) returns the share of a prompt prefix's
requests that find its cache still warm, when requests for it arrive at random at per_hour an hour. A hit refreshes
the cache, so a request hits when the one before it came at most ttl_minutes earlier, and with random arrivals that
happens with probability 1 - e^(-rate × ttl), with the rate and the lifetime in the same unit.
expected_cost(price, shared, own, output_tokens, per_hour, ttl) returns the average dollars per request when the
first shared input tokens are cached with ttl of "none", "5m" or "1h", and own tokens follow them. With
"none" every input token is plain input. Otherwise a hit reads the shared tokens and a miss writes them.
best_ttl(price, shared, own, output_tokens, per_hour) returns the cheapest of "none", "5m" and "1h", and a
tie goes to the one earlier in that order.
Level 3. Rent or pay per token. cheaper(api_per_mtok, hourly, capacity_tps, demand_tps, min_gpus=2) compares
serving demand_tps output tokens a second through an API at api_per_mtok dollars per million, against rented GPUs
at hourly dollars each that each produce up to capacity_tps tokens a second. Rent at least min_gpus, so one
failure doesn't take the service down, and enough whole GPUs to carry the demand (round up). Return ("api", dollars an hour) or
("gpus", dollars an hour) for the cheaper one, and a tie goes to the API. Count output tokens only.
Things to get right: which price each kind of input token pays, the units in the hit rate, a miss pays the write price for its own lifetime, and the minimum fleet. Follow-ups from the lesson: routing easy requests to a smaller model, batch discounts, agent loops that re-send their context, and why a cheaper GPU price isn't the same as a cheaper model.