Skip to content

Idempotent Usage Metering, Billing Ledgers, and Race-Free Quota Enforcement

2 min read

Enforcing plan limits with a naive SELECT count followed by if (count < limit) { send(); UPDATE count = count + 1 } fails under concurrency. Two simultaneous requests read count = 99, both pass < 100, and both proceed. For AI token budgets or outbound message quotas, race conditions and duplicate webhook retries silently drain margins.

Append-Only Ledger + Atomic Reservation Pattern

Model usage with two cooperating structures:

  1. An append-only usage ledger keyed by an idempotent event_id (every debit, credit, or refund adjustment is an immutable row, making audits and billing disputes trivial to reconcile).
  2. An atomic conditional reservation executed inside a single SQL statement or row-locked transaction before incurring external cost.
StepDatabase OperationWhy It Is Safe
1. ReserveUPDATE quota SET used = used + $n WHERE tenant_id = $id AND used + $n <= limitSingle atomic check-and-increment; zero TOCTOU race
2. ExecuteCall LLM or messaging providerExternal work happens outside DB lock
3. ReconcileRecord actual usage in idempotent ledger; refund unused reservation deltaNever overcharges on failed or shorter completions
sql
-- Race-free quota admission in one atomic statement
UPDATE tenant_usage_periods
SET used_units = used_units + $2,
    updated_at = now()
WHERE tenant_id = $1
  AND period_key = $3
  AND used_units + $2 <= limit_units
RETURNING used_units, limit_units;

Integer Arithmetic Always

Store monetary amounts in smallest integer units (cents or micro-USD) rather than floating-point doubles (0.1 + 0.2 !== 0.3). Keep pricing rate tables versioned by effective_from timestamp so historical invoices always reconcile cleanly even after plan prices change.

Next: turn raw conversations, ad clicks, and recorded orders into trustworthy business analytics in Analytics Engineering for Conversational Commerce.

Was this helpful?