Building an Atomic Spend Guard with Firestore Transactions
Inside the two-phase micro-cent reservation, OCC retry loop, and crash-recovery lease architecture powering Noethekx.
Verified Source Facts
Floating-point arithmetic (0.1 + 0.2) and non-transactional read-modify-write updates introduce subtle drift and race conditions in billing systems. When protecting AI API budgets, even small rounding bugs or concurrent optimistic races can let a burst slip past a hard spending limit.
Noethekx stores all spend counters in integer micro-cents (100_000_000 micro-cents per USD, 1_000_000 per cent) and executes every budget check inside Cloud Firestore optimistic concurrency transactions.
Why Single-Phase Post-Billing Fails
Updating spend totals only after an upstream LLM call returns creates an unbounded race window equal to the upstream model latency. If an upstream response takes several seconds and an agent spawns 25 parallel requests at once, all 25 requests observe spent_today_microcents === 0 and proceed before the first completion writes back cost.
Two-Phase Reservation and Reconciliation
reserveBudgetAtomically reads the organization document, organization spend policy (spend_policies/{orgId}), and proxy key document (proxy_keys/{keyId}) inside runTransactionWithRetry. After performing inline monotonic UTC day_key and month_key rollovers (resolveMonotonicPeriod) so backward NTP skew cannot reset daily spend, the transaction verifies:
- Neither the organization nor policy kill switch is engaged, and the key is not revoked.
- The model satisfies key allowlists and request cost stays under
max_request_cents. spent + reserved + estMicroCents <= capMicroCentson key, policy, and plan monthly volume limits.
All checks pass atomically before incrementing reserved_microcents and writing a crash-recovery lease into active_reservations/{resId} with a 5 minutes expiration window.
// Phase 1: atomic reservation inside runTransactionWithRetry
const res = await reserveBudgetAtomically({
orgId,
keyId,
model,
estMicroCents,
nowMs: Date.now(),
});
if (!res.ok) {
return buildProviderErrorResponse({ httpStatus: res.httpStatus, code: res.code });
}Bounded Exponential Jitter Retries and Fail-Closed Safety
High parallel concurrency triggers Firestore gRPC ABORTED (code 10) contention. runTransactionWithRetry retries transient ABORTED and DEADLINE_EXCEEDED errors up to maxAttempts 15 with exponential jitter starting at 20ms base delay, capped at 250ms max delay, and bounded by a 4000ms total retry budget.
If Firestore remains unreachable or retries exhaust, the gateway fails closed with HTTP 503 SPEND_GUARD_UNAVAILABLE rather than letting unguarded requests pass to paid upstream providers.
Crash-Recovery Leases Without Double Decrement
If a server instance terminates abruptly mid-request, /api/cron/maintenance scans expired active_reservations documents older than 5 minutes and decrements reserved_microcents transactionally. During normal reconciliation, reconcileBudgetAtomically reads active_reservations/{resId} first inside the same transaction; if the maintenance cron already reclaimed the lease, reconciliation avoids double-decrementing reserved_microcents.
Verified under our 25 parallel requests race runner at a $0.05 daily cap, total settled spend stays strictly below the configured cap with reserved_microcents returning to zero after every wave. Every proxy endpoint at https://nothekx.com/api/v1 runs through this exact two-phase reservation and reconciliation pipeline.
Test hard spend caps in the Zero-Key Sandbox
Route requests through https://nothekx.com/api/v1 or inspect pass-through header mode.