Idempotent Usage Metering, Billing Ledgers, and Race-Free Quota Enforcement
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:
- 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). - An atomic conditional reservation executed inside a single SQL statement or row-locked transaction before incurring external cost.
| Step | Database Operation | Why It Is Safe |
|---|---|---|
| 1. Reserve | UPDATE quota SET used = used + $n WHERE tenant_id = $id AND used + $n <= limit | Single atomic check-and-increment; zero TOCTOU race |
| 2. Execute | Call LLM or messaging provider | External work happens outside DB lock |
| 3. Reconcile | Record actual usage in idempotent ledger; refund unused reservation delta | Never overcharges on failed or shorter completions |
-- 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.