Selected work / 01
LLM Gateway
OpenAI-compatible proxy with per-key micro-USD budget reservations, atomic settlement, and Groq-to-Gemini fallback.
TypeScript · Node.js · Express · PostgreSQL · Drizzle · Groq · Gemini
The problem #
Counters break when concurrent LLM requests share a virtual key: callers race past budget caps, time out mid-flight, or switch providers after already reserving spend. LLM Gateway treats every budget as a two-phase PostgreSQL ledger.
Architecture #
Client │ Bearer virtual key ▼ Express gateway ─────── PostgreSQL │ ├─ virtual keys + budgets │ 1. reserve (µUSD) ├─ usage ledger │ SELECT ... FOR ├─ reservations with TTL │ UPDATE └─ settle / release │ ├── Groq primary (8s timeout, 1 retry) │ └── Gemini fallback (10s timeout)
Fallback routes the same reservation—switching providers never double-reserves budget.
Key decisions #
Reserve first, settle on provider usage
A row lock verifies the worst-case estimate before any upstream call, then replaces the hold with actual provider-reported usage afterward.
No DB transaction across network calls
Locks span only the check-and-write step; LLM calls run outside the transaction so slow providers never stall concurrent requests on the same key.
Integer micro-USD
Balances and charges live in PostgreSQL bigint micro-USD, avoiding floating-point rounding drift under concurrent subtractions.
Circuit-broken fallback & TTL recovery
Transient Groq failures retry once before failing over to Gemini (open circuit skips timeout wait). Client aborts release immediately; a TTL sweeper reclaims crashed holds.
Numbers #
reservation
accounting
timeouts
tests
A request can fail, retry, fall back, or drop mid-stream without drifting the ledger.