Back to Journal
AI Engineering 10 min read

How to Meter AI Usage in a SaaS Product

A practical architecture for counting customer-visible units, enforcing fair limits under concurrency, recording explainable usage, and reconciling billing.

Key Takeaways

  • Meter a clear product outcome, such as a completed review, rather than exposing model tokens as the customer unit by default.
  • Keep customer-billable usage, plan entitlements, and provider cost in separate records; they answer different questions.
  • Write immutable usage events with a stable idempotency key and a database uniqueness constraint so retries do not create duplicate charges.
  • Reserve quota atomically before expensive work, then commit the actual billable event or release the reservation when the task fails.
  • Treat a billing provider's usage summary as an invoicing input, not necessarily a real-time quota counter; reconcile delayed and corrected events before invoices close.

To meter AI usage safely in a SaaS product, count a clearly defined customer outcome, record each billable event once in your own tenant-scoped ledger, and enforce limits before work begins. Keep that record separate from the provider-cost data used to manage margin. Raw token counts are useful for engineering and cost analysis, but should not become the customer's billable unit by default.

The distinction matters because an AI task can include several model calls, retries, retrieval steps, and tool calls but produce one useful product outcome. If you charge for every internal step, an implementation change can alter a customer's bill. If you only watch the model invoice, you may know your cost without knowing which customer-facing allowance was used. This guide gives product and engineering teams a framework for connecting those records without treating them as interchangeable.

What should count as one billable AI event?

Start with the customer promise, then write down the exact event that consumes it. A product might count a completed support-case draft, an accepted document review, or one successful workflow run. Those are illustrative choices, not universal recommendations: use a unit that buyers can understand and that corresponds to meaningful work in your product.

Define edge cases before code makes the policy for you. Decide whether a failed model call, an internal retry, a user-cancelled task, an invalid result, a human handoff, or a rerun after an edit consumes a unit. If a customer is charged for a result that is later reversed, record a linked adjustment rather than silently rewriting history. The rule can vary by feature; consistency and visibility matter more than pretending every task is identical.

A useful design test is this: can a customer administrator explain why one unit was counted by looking at the product activity? If the only explanation is an internal token total or a chain of hidden model calls, choose a more legible meter or make the usage detail explicit.

Keep customer usage, entitlements, and provider cost separate

RecordQuestion it answersExample fields
Billable usage eventWhat did this tenant use under the published plan?Tenant, feature, unit, quantity, event time, policy version
Entitlement and reservationMay this tenant start one more operation now?Tenant, period, included units, reserved units, consumed units
Provider cost recordWhat did it cost us to serve the operation?Request ID, provider, model, returned usage, direct cost

Link these records with a server-generated request ID, but do not use the provider cost as a substitute for customer usage. One visible task can require multiple provider calls; a cached or failed call can also produce cost without a billable outcome. Keeping separate ledgers makes it possible to explain a customer balance while also finding an expensive feature path.

Keep plan interpretation versioned too. Store the unit, allowance, price or credit rule, billing period, and effective date that applied to an event. When packaging changes, historical records should still explain the old invoice. The unit-economics and packaging decision is covered in our guide to pricing AI features in a SaaS product.

Use a durable, idempotent usage ledger

A minimal ledger needs an immutable event ID, tenant ID, stable event key, feature and unit names, positive quantity, event timestamp, and the pricing or policy version. Derive tenant identity from the authenticated server-side request context; never trust a tenant ID supplied only by the browser. For shared infrastructure, tenant isolation must apply to the usage records as well as the AI data they describe. AWS explains why ordinary authentication alone does not guarantee tenant isolation in its SaaS architecture guidance.

The following is an illustrative PostgreSQL shape, not a drop-in billing schema. It stores the billable fact, not prompts or generated content:

create table ai_usage_events (
  id uuid primary key,
  tenant_id uuid not null,
  event_key text not null,
  feature_key text not null,
  unit_key text not null,
  quantity numeric(18, 6) not null check (quantity > 0),
  occurred_at timestamptz not null,
  policy_version text not null,
  unique (tenant_id, event_key)
);

When writing an event, use the same event key on every retry and let the unique constraint decide whether it is new. PostgreSQL's INSERT ... ON CONFLICT can make the insert idempotent under concurrent retries:

insert into ai_usage_events (
  id, tenant_id, event_key, feature_key, unit_key,
  quantity, occurred_at, policy_version
)
values ($1, $2, $3, $4, $5, $6, $7, $8)
on conflict (tenant_id, event_key) do nothing
returning id;

If the insert returns no row, the logical event was already recorded. Do not issue a second usage charge. Use an outbox row in the same database transaction to deliver newly recorded events to your billing provider after commit. That avoids the split-brain case where the database write succeeds but a network call fails, or a retry reaches the provider before the product has durably recorded the event.

Enforce limits without racing concurrent requests

A quota check that reads the balance and increments it later is unsafe under concurrency. If several requests arrive together, each can read the same remaining allowance and all proceed. Instead, atomically reserve the expected units against a tenant-and-period record before starting an expensive AI operation. The reservation should succeed only if consumed plus reserved plus requested units remain within the configured limit.

For a product with one quota row per tenant and billing period, a conditional update can make that reservation in one database statement. This simplified example assumes the row already exists and the request units use the same meter as the allowance:

update ai_entitlements
set reserved_units = reserved_units + $requested_units
where tenant_id = $tenant_id
  and period_start = $period_start
  and consumed_units + reserved_units + $requested_units <= included_units
returning reserved_units;

Give the tenant-and-period key a unique constraint so this statement targets exactly one row. Treat no returned row as a denied reservation, and make the reservation itself idempotent by request ID. In PostgreSQL's default Read-Committed isolation, a concurrent update waits for the row being changed and then checks whether its WHERE condition still matches. That is the concurrency behavior this single-row pattern relies on; read the current PostgreSQL transaction-isolation documentation, and handle transaction retry errors if you use a stricter isolation level.

After the operation, commit the actual billable quantity and release any unused reservation. On a provider error or user cancellation, release the reservation according to the published policy. Reservations need an expiry and cleanup path so a crashed worker cannot hold capacity forever. For a long-running workflow, make the reservation visible as pending rather than counting it as a completed task.

Decide what a reached limit means in the product: warn and continue, ask an administrator to approve more usage, offer a clear top-up, or pause a non-critical AI action. A hard stop may be appropriate for a cost-sensitive feature, but preserve the customer's primary workflow where possible. The plan needs to explain the consequence before a user reaches the cap.

Reconcile billing events before the invoice is final

Your own ledger should be the operational source for live balances. A billing service can aggregate events and calculate invoices, but its processing may not be immediate. Stripe's current documentation says its basic usage-based billing meter events are processed asynchronously and supports idempotency identifiers to avoid duplicate reporting; it also warns that accepted late events may miss a finalized invoice, depending on the invoice and its grace-period configuration. Review the current rules for the provider and invoice types you use:Stripe meter-event recording and its invoice finalization grace-period guidance.

Run a reconciliation job before invoice close. Compare your own events with provider-accepted events and billed quantities by tenant, meter, and service period. Alert on missing or rejected deliveries, late arrivals, and corrections that have not reached the invoice system. Label customer-facing usage as estimated until the invoice is finalized if that distinction matters to your plan.

What should you test before charging customers?

  • Retry test: send the same successful task twice and confirm it creates one billable event.
  • Concurrency test: send simultaneous requests at the last available unit and confirm the limit cannot be overspent unless your plan allows it.
  • Failure test: simulate provider timeouts, retries, invalid output, cancellation, and worker crashes; check how each affects reservations and billing.
  • Tenant-boundary test: attempt to read and aggregate another tenant's events through every API and background job.
  • Reconciliation test: deliver late and duplicated events in a billing sandbox and verify totals before invoices close.

Start in shadow mode: write and reconcile usage without changing what customers pay. Compare the meter with actual workflows, fix the cases where the number surprises a user, then pilot the allowance and billing experience with a small group. Add evaluations for quality as well as metering; a correctly billed AI feature can still fail its job. Our guides to evaluating AI systems and measuring AI ROI cover those related decisions.

Plan the meter before adding the paywall

Before charging for an AI feature, write a one-page meter definition: the customer outcome, the event that counts, edge-case rules, unit and allowance, reservation behavior, adjustment policy, and reconciliation owner. Then exercise it against real product workflows in shadow mode. This makes pricing, product UX, and engineering agree on what the customer is paying for.

If you are adding AI to an existing B2B product and need help designing the integration, metering, or release plan, tell us about the product and workflow in the project inquiry form. Include the unit you are considering, current usage assumptions, and the launch decision you need to make.

Frequently Asked Questions

What is the difference between AI usage metering and AI cost tracking?

Usage metering records the customer-facing unit that the product promises to count, such as a completed document review or a monthly workspace allowance. Cost tracking records what the provider and infrastructure cost to serve that work, such as model tokens, tool calls, storage, and retries. Keep both, linked by a request identifier, but do not assume they should be the same unit or amount.

Should a SaaS product charge customers by AI tokens?

Only when token counts are a unit customers can understand, forecast, and connect to value. For many products, tokens are an internal cost driver while a completed task, document, seat, or credit is easier to budget. Whatever unit you choose, define it before launch and show how the allowance and overage work.

How do I prevent an AI usage event from being counted twice?

Give each billable product event a stable key that survives retries, store that key under a database unique constraint, and insert with an idempotent conflict rule. Keep the source event in your own ledger before sending it to a billing provider, and reuse a provider-supported idempotency identifier when delivering it. A retry should return the prior result, not create a second unit.

How can I enforce an AI usage limit when several requests arrive at once?

Reserve the expected units in one atomic operation against the tenant's allowance before starting the provider call. If the reservation would exceed the limit, do not start work that the plan says is unavailable. On success, move the reservation to consumed usage; on failure or timeout, release it through a safe cleanup path. A plain read-then-increment can let concurrent requests all pass against the same remaining balance.

Can my billing provider's usage summary enforce an in-app quota?

Do not assume that it can. Billing meters can process events asynchronously, and a summary or invoice preview may lag the latest product action. Enforce immediate product limits from your own tenant-scoped usage and reservation records; use the billing provider for invoice calculation and reconciliation according to its current delivery and finalization rules.

Free Tools

Game Changer Labs

Tell us what you're building — book a free scoping call.

Pick a time that works and walk us through your project — 30 minutes, straight to the point. You leave with a concrete plan, timeline, and cost. No sales pitch — if we're not the right fit, we'll say so.

Keep Reading

Get new playbooks by email

Occasional, no-fluff field notes on building production AI — new guides and tools, straight to your inbox. Unsubscribe anytime.

Published: November 16, 2026Game Changer Labs