Backend & Cloud Engineer Guide: Usage-Based SaaS Billing & Token Metering
Modern AI applications, API platforms, and cloud infrastructure products rarely charge a flat per-seat fee alone. Instead, they rely on hybrid usage-based billing: metering LLM input/output tokens, GPU compute seconds, active WebSocket minutes, or processed documents. If your metering pipeline drops events during traffic spikes or double-counts retries, you either leak revenue or overcharge customers and destroy trust. As a Senior Backend Engineer and Cloud Engineer, I architect high-throughput, idempotent usage metering and billing rollup engines in PostgreSQL and Python/Go.
1. The 3 Core Invariants of Usage-Based Metering
- Strict Event Idempotency: Every metered event (whether an LLM completion call or a 60-second compute heartbeat) must carry a deterministic
idempotency_keyso network retries never inflate customer invoices. - Append-Only Raw Ledger + Hourly Pre-Aggregated Rollups: Never run
SUM(units)across 50 million raw event rows during a customer dashboard page load. Persist raw events for auditability and roll them up into hourly/daily organization buckets atomically. - Pre-Authorized Quota Enforcement: For prepaid credit or hard-capped tiers, check remaining balance with low-latency atomic counters before dispatching expensive downstream AI or cloud workloads.
2. Atomic Upsert Metering & Hourly Bucket Rollup in PostgreSQL
Using PostgreSQL CTEs (Common Table Expressions) and ON CONFLICT DO NOTHING, we can insert a raw usage event and increment the organization's hourly billing bucket in a single atomic round-trip—guaranteeing that duplicate retries increment the rollup counter exactly zero times:
from django.db import connection
from datetime import datetime
RECORD_USAGE_SQL = """
WITH inserted_event AS (
INSERT INTO billing_usage_events (
idempotency_key,
organization_id,
metric_code,
quantity,
occurred_at
)
VALUES (%s, %s, %s, %s, %s)
ON CONFLICT (organization_id, idempotency_key) DO NOTHING
RETURNING organization_id, metric_code, quantity, date_trunc('hour', occurred_at) AS bucket_hour
)
INSERT INTO billing_usage_hourly_rollups (
organization_id,
metric_code,
bucket_hour,
total_quantity,
event_count,
updated_at
)
SELECT
organization_id,
metric_code,
bucket_hour,
quantity,
1,
NOW()
FROM inserted_event
ON CONFLICT (organization_id, metric_code, bucket_hour)
DO UPDATE SET
total_quantity = billing_usage_hourly_rollups.total_quantity + EXCLUDED.total_quantity,
event_count = billing_usage_hourly_rollups.event_count + 1,
updated_at = NOW()
RETURNING total_quantity;
"""
def record_metered_usage(
idempotency_key: str,
organization_id: str,
metric_code: str,
quantity: int,
occurred_at: datetime,
) -> int | None:
with connection.cursor() as cursor:
cursor.execute(
RECORD_USAGE_SQL,
[idempotency_key, organization_id, metric_code, quantity, occurred_at],
)
row = cursor.fetchone()
return int(row[0]) if row else None
3. Heartbeat Lease Metering for Long-Running Sessions & GPU Sandboxes
When billing by active session duration (such as remote browser containers, WebRTC calls, or GPU pods), relying solely on a "session ended" webhook is dangerous: if a worker crashes violently, the stop event never arrives. Instead, workers emit a signed heartbeat every 30 seconds with a deterministic key f"{session_id}:hb:{epoch_minute}". If heartbeats stop, the billing window automatically caps at the last verified heartbeat timestamp.
4. Hire a Senior Backend & Cloud Engineer for SaaS Billing
Need a rock-solid usage metering ledger, prepaid credit wallet, or automated invoice sync for your SaaS or AI platform? Explore my Backend Engineer Pillar Guide, review my Idempotent Payment Webhook & Outbox Architecture, or book a 1-Day Billing Architecture Sprint.