skip to content

A model gateway checks spend caps before calls but learns costs after: how far can spend overshoot, and how do reservations bound it?

level: middleimportance: must knowfreq 50%

answer

  1. cost arrives after the response
  2. every call in flight passed the check
  3. concurrency times worst-case call cost
  4. hold the estimate, settle the actual
  5. an output limit makes the ceiling

basics

~20 s

Each call admitted under the cap can still spend, so overshoot reaches in-flight calls times their worst cost, plus settlement lag. Holding each call's maximum at admission, then settling the actual, keeps spend within the cap when that maximum is a true ceiling.

solid answer

~50 s

A model call's cost depends on how many output tokens it generates, which is known only when the response ends. If the gateway only checks `spent < cap` at admission and adds the cost on completion, every call that starts while the counter is under the cap gets through, so the worst-case overshoot is roughly the calls in flight times the most any one can cost, plus everything admitted while settled costs lag behind. A **reservation** fixes this: at admission the gateway prices an upper bound (the input tokens it can count plus the request's maximum output tokens), atomically checks `spent + reserved + estimate <= cap`, and holds the estimate. On completion it releases the hold and records the actual cost. The price is that holds at the ceiling can refuse calls that would really have fit, so routes need sensible output limits.

code

pseudocode · 23 lines
pseudocode
function admit(key, request):
    out_cap = request.max_output_tokens or route.default_max_output
    estimate = input_tokens(request) * price_in + out_cap * price_out
    fits = atomically on budget[key]:
        if budget.spent + budget.reserved + estimate > budget.cap:
            false
        else:
            budget.reserved += estimate
            true
    if not fits:
        return refuse(error = "budget_exhausted")
    hold = new_hold(key, estimate, expires_at = now() + 10 minutes)
    return forward(request with max_output_tokens = out_cap, hold)

# called on completion, or by the expiry sweep with usage = none
function settle(hold, usage):
    actual = usage present ? cost_of(usage) : hold.estimate
    atomically on budget[hold.key]:
        if hold.settled:
            return          # the other path already settled this hold
        budget.reserved -= hold.estimate
        budget.spent += actual
        hold.settled = true

go deeper

for a junior

Recall that a model call's cost is unknown until the response ends, because the number of output tokens is not known in advance.

for a middle

Explain worst-case overshoot as in-flight calls times maximum per-call cost, plus whatever is admitted while settled costs lag, and how hold-then-settle closes it.

for a senior

Name where the estimate stops being a ceiling (no output limit, per-call tool fees, a pricier fallback) and how expiring holds settle lost calls at their estimate.

for a principal

Weigh reserving at the maximum against a high percentile: false refusals near the cap versus a small, bounded overshoot the organisation agrees to absorb.

## Why a pre-call check alone leaks A **spend cap** is a limit on how much a caller (here, a team's gateway key) may spend in a period. The gateway can enforce it only at a moment it controls: **admission**, when it decides whether to forward a request. The trouble is that a model call's price is not known at admission. Input tokens can be counted in advance, but **output tokens**, usually the dearer kind on hosted models, depend on what the model generates, and the provider reports the final usage only when the response ends. The naive design checks `spent < cap` at admission and adds each call's cost to `spent` when the call completes. Every call that starts while the counter is still under the line passes, so the cap is crossed by whatever those calls go on to spend. ## How big the overshoot gets Two terms make up the worst case: - **In-flight calls**: everything admitted before the counter crosses the cap, each able to spend up to its maximum. - **Settlement lag**: if completed costs reach the counter late, for instance through an asynchronous metering pipeline, every call admitted during that lag passes too. A worked scenario, with illustrative prices of $3 per million input tokens and $15 per million output tokens. A batch job keeps 200 calls in flight, each with up to 100,000 input tokens and 8,000 output tokens: - maximum cost per call = 100,000 x $3/1M + 8,000 x $15/1M = $0.30 + $0.12 = **$0.42**; - in-flight overshoot = 200 x $0.42 = **$84**, against a $500 cap; - if each call takes about 20 seconds, the job completes about 10 calls per second, and a 5-minute metering lag admits up to 3,000 more calls: 3,000 x $0.42 = **$1,260**. Concurrency sets the size of the problem and lag can dominate it. A single-threaded loop whose costs settle at once overshoots by at most one call, which is why the leak is easy to miss in testing. ## Reservation and settlement A **reservation** (a hold) moves the charge to admission. The gateway: 1. counts the request's input tokens; 2. takes an output ceiling (the request's maximum output-token setting, or the route's default when the request has none) and forwards the request with that limit set, so the provider enforces it; 3. prices both at the model's rates to get an **estimate** that is an upper bound; 4. atomically checks `spent + reserved + estimate <= cap` and, if it fits, adds the estimate to `reserved` (the atomic check-and-increment on a shared counter belongs to rate limiting); 5. on completion, removes the estimate from `reserved` and adds the **actual** cost from the provider's reported usage to `spent`. When the estimate really is a ceiling, `spent + reserved` cannot pass the cap and the overshoot is zero. Holds also need an **expiry**: a gateway replica that crashes mid-call never settles, and a hold that never expired would block that budget forever. An expired hold is settled at its estimate. ## Where the estimate stops being a ceiling - **No output limit** on the request and no route default: the estimate has nothing to multiply. - **Charges outside tokens**: some providers bill server-side tools, searches or media per call or by size. - **Hidden reasoning tokens**: many providers count them against the output limit, but check that the limit you set actually covers them. - **A pricier model on fallback**: if the route may fail over to another model, reserve at the dearest model in the chain. - **Tokenizer mismatch**: a local input count can differ slightly from the provider's, so pad it. ## The price of reserving at the ceiling Holding the maximum is conservative by design, and that has a cost. A long-context call with a generous output limit holds dollars while it may spend cents, so a team near its cap gets refused calls that would have fit, and high concurrency is limited by holds rather than by spend. Teams manage this with **tight per-route output limits** that match what each feature really needs, and some gateways deliberately reserve at a high percentile of observed cost instead of the maximum, accepting a small, bounded overshoot in exchange for fewer false refusals. Either way, the reservation turns an open-ended leak into a number someone chose.

  • What should the gateway charge when a stream breaks mid-response, before the provider reports usage?
    Settle at the reservation, or at the full input plus the output tokens it saw streamed if it counts them, rather than at zero. The provider has usually billed for tokens generated before the break, and settling at zero turns every broken stream into free spend a misbehaving client can exploit. The same applies to holds whose settlement never arrives: they expire into spent at their estimate.
  • Why not give every request a huge output limit so the estimate is always safe?
    Because the hold is the ceiling: a huge output limit makes every call reserve a large sum, so a team near its cap is refused calls that would have cost cents, and concurrency is throttled by holds rather than spend. Gateways set per-route default output limits close to what each feature needs, and some reserve at a high percentile of observed cost, accepting a small bounded overshoot.

A hotel puts a hold on your card at check-in for the room plus a margin for extras, then charges the real bill at checkout and releases the rest. A card close to its limit can be declined at check-in even though the final bill would have fitted.

  • Checking spent against the cap before each call keeps spend under the cap.
  • Overshoot is at most one call's cost, whatever the concurrency.
  • The estimate only needs input tokens, since output is small and unpredictable.
  • A stream that breaks mid-response cost nothing, so settle it at zero.
  • Holding the maximum never refuses a call that would actually have fitted.