Atomic quota reservations in PostgreSQL for a high-concurrency LLM gateway

Billing for a normal REST API is easy: one request equals one fixed unit, or you count requests after the fact.
Billing for an LLM inference gateway is annoyingly asymmetric. When a streaming request arrives at POST /v1/chat/completions, you do not know the final cost yet. You might estimate the input tokens, yet the output could be 40 tokens or 8,000 tokens, and the upstream provider might fail halfway through or the client might abort the SSE stream after 2 seconds.
Meanwhile, a single tenant can easily fire 50 concurrent requests at once against an account that only has $0.50 left.
Why naive check-then-deduct fails under load
The textbook bug looks like this:
-
SELECT balance FROM accounts WHERE id = $1-> sees$0.50. -
Forward request to upstream LLM (takes 6 seconds).
-
UPDATE accounts SET balance = balance - $cost WHERE id = $1.
If 30 concurrent requests hit step 1 within the same 100ms, all 30 see $0.50, all 30 pass the gate, and six seconds later your tenant's balance is -$8.40. Even wrapping step 1 and step 3 in a single DB transaction is a disaster because you would be holding a PostgreSQL row lock open for 6+ seconds while waiting on an upstream HTTP stream, instantly exhausting your connection pool.
Two-phase reserve and idempotent settlement
When we built our in-house LLM inference gateway, we split billing into two short, atomic database transactions with zero DB locks held during upstream streaming:
-
Reserve upfront (before dialing upstream): estimate a conservative upper bound (
reserved_micros) from prompt size +max_tokens, atomically checkbalance - reserved >= amount, incrementreserved_micros, and insert aPENDINGledger reservation row keyed byrequest_id. -
Settle asynchronously (after stream completes, errors, or aborts): compute actual cost from reported/counted prompt + completion tokens, release
reserved_micros, deductactual_micros, and mark the ledger entrySETTLEDinside an idempotent transaction.
-- Phase 1: Atomic reservation (runs in <2ms, no lock held across LLM call)
WITH updated AS (
UPDATE tenant_quotas
SET reserved_micros = reserved_micros + $2,
updated_at = NOW()
WHERE tenant_id = $1
AND (balance_micros - reserved_micros) >= $2
RETURNING tenant_id
)
INSERT INTO quota_reservations (request_id, tenant_id, reserved_micros, status)
SELECT $3, tenant_id, $2, 'pending'
FROM updated
RETURNING request_id;
If the INSERT returns zero rows, the tenant does not have enough available headroom right now and we immediately return HTTP 402/429 before touching any upstream provider.
Settlement is guarded by checking WHERE request_id = $1 AND status = 'pending' so even if a background settlement worker retries the same job twice after a crash, it can never double-charge or double-refund:
-- Phase 2: Idempotent settlement
WITH claimed AS (
UPDATE quota_reservations
SET status = 'settled',
actual_micros = $2,
settled_at = NOW()
WHERE request_id = $1
AND status = 'pending'
RETURNING tenant_id, reserved_micros
)
UPDATE tenant_quotas q
SET reserved_micros = q.reserved_micros - c.reserved_micros,
balance_micros = q.balance_micros - $2,
updated_at = NOW()
FROM claimed c
WHERE q.tenant_id = c.tenant_id;
Handling crashed gateways and stuck reservations
One case you must plan for: what if a gateway pod gets OOM-killed mid-stream after Phase 1 succeeded, so Phase 2 never gets enqueued? Without a sweeper, reserved_micros stays leaked forever and eventually locks the tenant out of their own remaining balance.
A periodic sweeper looks for pending reservations older than our max request timeout (say 15 minutes), reconciles against any recorded upstream usage logs if available, and settles or releases the stale reservation idempotently.
Using integer micro-dollars (bigint) instead of floats, keeping locks strictly outside network I/O, and making settlement idempotent by construction gave us strict billing consistency even under heavy concurrent bursts.
Share this article
Reactions