Ankit Sinha

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:

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.