Field note / 02
Two-phase micro-USD reservations in SQL
Decrementing an API budget after a provider responds always fails the same way: two concurrent requests both clear the balance check, both stream tokens, and both push the ledger negative.
Nov 2026 · 3 min read · from LLM Gateway
Lock the check, never the socket #
A naive fix wraps the entire upstream LLM call in a database transaction. Under slow responses or stalled streams, that pins PostgreSQL row locks for ten seconds per caller and serializes every request sharing a key.
The clean split treats budgets like a two-phase ledger in integer bigint micro-USD:
- Phase 1 — reserve: inside a sub-millisecond transaction, lock the key row with
SELECT ... FOR UPDATE, verify remaining budget covers the worst-case token ceiling, insert areservedhold with a TTL, and release the DB connection. - Upstream I/O + fallback: call the primary provider (Groq) or fail over to Gemini under the exact same reservation ID—switching providers never double-charges.
- Phase 2 — settle or release: once usage headers arrive, finalize actual micro-USD cost and return the unused remainder atomically. Client aborts trigger immediate release; crashed workers expire via TTL sweep.
SELECT ... FOR UPDATE (micro-ms) ─▶ release DB lock
└─▶ call Groq / Gemini (seconds, no DB lock held)
├─ success ─▶ settle actual cost + return diff
└─ abort / timeout ─▶ release hold (or TTL sweep)
Integers outlive rounding #
Storing fractional dollars as floats introduces subtle cent-boundary drift after thousands of tiny settlements. Storing micro-USD (1 USD = 1,000,000 units) as PostgreSQL bigint makes every reservation, partial refund, and daily reconciliation sum exact.
Concurrency bugs rarely show up in single-caller benchmarks; they live in the second parallel request that sneaks past an unlocked read.