All writing

Article ยท LLM cost control

An LLM budget that checks spend after the request is a report

Under concurrent traffic, post-hoc budget checks let every request through. Reserve the maximum cost first, settle the real cost after, the way payment systems hold funds.

By Ali Raza, Senior AI Engineer

A monthly LLM budget that only checks spend after the request is not a budget. It is a report.

The race

Under concurrent traffic, ten requests can all read "$4 left" at the same moment, all decide they fit, and all spend $1. The check passed ten times and the cap is gone. Nothing was wrong with any single request. The design was wrong.

Reserve, then settle

  1. Before calling the provider, reserve the maximum possible cost for that request atomically: input tokens plus the output token limit, at the model's price.
  2. If the reservation would exceed the cap, reject before any tokens are spent.
  3. After the response, settle: replace the reservation with the exact cost from real token counts.
  4. If the call fails or the client disconnects mid-stream, release the reservation or settle what was actually used.

This is how payment systems hold funds. A card authorization holds an amount before the final charge, and LLM spend deserves the same treatment.

Details that matter

  • The reservation must be one atomic operation in the store that holds the balance, not a read followed by a write.
  • Streaming responses need settlement on every exit path, including a client that closes the connection.
  • A retried request must not reserve or bill twice. Give it the same request key as the original.

I built this into llm-gateway as per-key budgets that hold under concurrent traffic, together with failover that never double-bills.

Building something like this?

I am open to remote AI engineering roles and contract work. Tell me about the system you need.