Usage-Based Billing for AI SaaS: Tokens, Credits, Quotas, Metering, and Cost Control
AI SaaS billing looks simple until the first real agent reaches production.
A user clicks one button. Behind that button, your application might make several model calls, read cached context, execute tools, retry a failed provider, fall back to another model, perform web search, generate an image, and keep an agent loop running for several minutes.
Which part should the customer pay for?
That is not only a pricing decision. It is a backend architecture problem.
A reliable AI SaaS needs to distinguish four different truths:
- Provider usage: what the model or tool provider says you consumed.
- Internal cost: what that usage cost your company.
- Customer billing: what your product contract says the customer should pay.
- Entitlement: what the customer is still allowed to consume.
Mix those together and billing becomes fragile. Keep them separate and you can change models, providers, pricing plans, credits, or billing vendors without rewriting the product.
This guide explains how to build that separation in a production system.
TL;DR
A strong AI SaaS billing path usually looks like this:
Customer request
↓
Entitlement + quota check
↓
Optional credit/cost reservation
↓
AI runtime / agent execution
↓
Provider-native usage capture
↓
Normalized usage ledger
↓
Versioned provider cost calculation
↓
Product billing rules
↓
Credit settlement / billable meter event
↓
Billing provider
↓
Reconciliation
The most important rules are:
- Do not use request count as a proxy for AI cost.
- Do not make provider tokens your only customer-facing billing unit unless that is genuinely your product.
- Preserve provider-native usage dimensions before normalizing them.
- Keep internal cost accounting separate from customer billing.
- Store usage as durable, append-oriented events rather than relying on logs.
- Use globally unique event IDs and idempotency.
- Version provider price rules and customer billing rules independently.
- Reserve budget before expensive agent work when hard limits matter.
- Settle against actual usage afterward.
- Record retries and fallbacks even when the customer is billed only once.
- Treat corrections as compensating entries instead of rewriting history.
- Reconcile your internal ledger against providers and your billing system.
The goal is not to build a giant billing platform. It is to create a few clear accounting boundaries that remain correct when AI workloads become unpredictable.
Why AI SaaS Billing Is Different
Traditional SaaS often starts with predictable units:
- $20 per seat
- 10,000 emails per month
- 100 GB of storage
- 1,000 API requests
- a fixed monthly subscription
AI workloads are different because one user-visible action can expand into many internal operations.
Consider an AI support agent asked to investigate an order issue, review payment status, search a knowledge base, and prepare a resolution.
The runtime might perform:
1 user request
→ 1 routing/model call
→ 2 retrieval operations
→ 1 order lookup
→ 1 payment tool call
→ 2 additional model turns
→ 1 web search
→ 1 final generation
If one model call fails and a second provider is used as fallback, your infrastructure may pay for both attempts even though the customer experiences one task.
This is why one request does not equal one unit of cost.
Stripe's 2026 guidance for AI usage-based billing explicitly highlights agent loops, tool-calling fanout, token variability, uneven workloads, and nondeterministic cost as reasons AI metering needs stronger controls than traditional API billing.
The major AI providers also expose different usage dimensions. OpenAI usage data can distinguish input, cached input, output, and reasoning-related usage. Anthropic can distinguish normal input, cache creation, cache reads, output, and some server-side tool usage. Gemini can expose input, output, thought, cached, and tool-use token dimensions.
A production billing system should therefore assume from day one that usage is multi-dimensional and provider-specific.
The Most Important Design Decision: Cost Is Not Billing
Suppose an agent run uses:
- 18,000 normal input tokens
- 60,000 cached input tokens
- 4,000 output tokens
- two search calls
- three external tool calls
- one failed model retry
Those facts belong to cost accounting.
But your product might charge the customer:
- 3 credits for the task
- $0.08 for the task
- one included agent run
- 500 AI units
- or nothing extra because usage is included in the subscription
Those facts belong to customer billing.
Do not force these two models to be identical.
A clean architecture looks like:
Provider usage
↓
Internal cost ledger
↓
Product pricing policy
↓
Customer billable usage
The internal cost ledger answers:
> What did this workload cost us?
The billing ledger answers:
> What did we promise to charge this customer?
Those answers can be different while both remain correct.
Why Billing Customers Directly in Tokens Can Become a Trap
Token billing is attractive because model providers already expose tokens.
For API-first products, raw token pricing can be completely reasonable. But for many end-user SaaS products it creates several problems.
Different providers count and price usage differently
A multi-provider application may use OpenAI, Anthropic, Gemini, or another provider. Token categories, caching semantics, reasoning usage, tool charges, and service tiers are not identical.
If the customer contract is tied directly to one provider's current token economics, switching provider becomes a billing migration.
Product value is rarely measured in tokens
A customer cares that the agent completed a useful task. They usually do not care whether the model needed 3,000 or 12,000 tokens.
Better models can change the economics
A stronger model may cost more per token but finish a task with fewer retries or turns. A cheaper model may need more total calls.
The useful metric is often cost per successful task, not simply cost per token.
Provider prices change
Pricing is an external dependency. Customer entitlements should not silently change every time an upstream provider changes its rate card.
For many SaaS products, it is cleaner to translate provider usage into a product-level unit such as credits, actions, minutes, documents, images, successful tasks, or a hybrid model.
Choosing the Right Billable Unit
There is no universal best unit. The unit should be understandable to customers and correlated enough with your variable cost to keep the business sustainable.
| Billing unit | Good fit | Main weakness |
|---|---|---|
| Raw tokens | Developer APIs, model gateways | Hard for normal customers to understand |
| Model requests | Simple inference APIs | Requests can vary massively in cost |
| Credits | Multi-model AI SaaS | Requires a clear conversion policy |
| Agent runs | Workflow products | One run can vary significantly in depth |
| Successful tasks | Outcome-oriented products | Success must be defined precisely |
| Images / minutes / documents | Modality-specific products | Cost inside the unit can still vary |
| Flat subscription | Predictable low-variance use | Heavy users can destroy margin |
| Subscription + included usage + overage | General SaaS | More billing logic |
| Prepaid credits | High-variance AI | Expiry and refunds need clear rules |
For a broad AI SaaS, a hybrid model is often practical:
monthly subscription
+ included credits
+ hard/soft limits
+ optional overage or top-up
This gives customers predictable pricing while preventing one runaway agent from creating unlimited variable cost.
A Production Reference Architecture
The important boundaries are:
Runtime owns execution
The runtime knows which model calls, retries, fallbacks, and tools actually happened.
Usage layer owns evidence
It converts runtime activity into durable accounting records.
Cost calculator owns provider economics
It applies a versioned provider rate card to actual usage.
Product billing policy owns customer pricing
It decides what the customer should be charged according to plan and product rules.
Billing provider owns invoices and payment collection
Stripe or another billing platform should not be your only source of truth for raw AI execution.
Step 1: Enforce Entitlements Before Spending Money
A common mistake is:
run expensive model
→ calculate usage
→ discover customer exceeded quota
At that point the cost already happened.
Admission control should happen before expensive work begins.
The request path can check:
- account status
- subscription status
- plan entitlements
- tenant limits
- project limits
- hard spend limit
- credit balance
- concurrent AI jobs
- model permission
- feature permission
- optional per-user limits
Conceptually:
request
↓
authenticate
↓
resolve tenant + plan
↓
check entitlement
↓
check concurrency
↓
check credit / spend budget
↓
reserve estimated usage if required
↓
execute AI work
This is different from normal rate limiting.
A rate limiter protects throughput.
A quota protects entitlement.
A budget protects money.
Do not collapse all three into one counter.
Step 2: Reserve Before Long or Expensive Agent Runs
For inexpensive single-turn requests, a preflight quota check may be enough.
Long-running agents are different.
An agent can keep calling models and tools while cost accumulates. A useful pattern is reservation + settlement.
Before the run:
available credits: 1,000
maximum reservation: 80
reserve 80
available for other work: 920
After the run actually consumes 53 credits:
settle 53
release 27
If the run needs more capacity than the reservation, the runtime can request another reservation before continuing.
This prevents two concurrent jobs from both seeing the same 100-credit balance and each spending 100 credits.
The reservation is a guardrail. It is not automatically the final charge.
Step 3: Capture Provider-Native Usage First
Do not normalize provider responses too early.
Each provider exposes details that may matter for future pricing or reconciliation.
For one provider you may need:
provider
model
input_tokens
cached_input_tokens
output_tokens
reasoning_tokens
provider_request_id
Another provider may need separate cache-creation and cache-read dimensions. Gemini may expose thought tokens and tool-use tokens separately.
The rule is:
> Normalize for querying, but preserve enough provider-native evidence to reproduce cost and investigate discrepancies.
If everything is squashed into one total-token number, you may lose information needed to match the provider's own bill.
Step 4: Use an Append-Oriented Usage Ledger
Billing evidence should not live only in logs.
Logs can be sampled, expire, change format, or disappear during an incident.
Create durable usage records.
A practical event can contain:
event_id
tenant_id
project_id
actor_id
request_id
run_id
provider
model
provider_request_id
usage_type
input_tokens
cached_input_tokens
output_tokens
reasoning_or_thought_tokens
tool_units
status
occurred_at
ingested_at
provider_usage_metadata
Cost-related data can include:
provider_price_version
provider_cost_micros
currency
cost_calculated_at
Customer billing data can include:
billing_metric
billable_quantity
billing_rule_version
billing_status
external_meter_event_id
You do not have to put all of this in one table. The important part is preserving the relationships.
Prefer integer money units
Do not accumulate monetary cost using binary floating point.
Use integer micros, integer cents where precision is sufficient, or a fixed-precision decimal type.
Tiny rounding differences become painful when millions of events are reconciled.
Step 5: Make Usage Events Idempotent
Distributed systems retry.
Your API can time out after successfully writing an event. A queue consumer can restart. A billing provider can return slowly. A worker can deliver the same message twice.
Without idempotency:
one AI run
→ retry
→ two usage records
→ two charges
Every logical usage event needs a stable unique identity.
A good pattern is a globally unique event ID generated at the source, with uniqueness enforced by the ledger.
Stripe's Meter Events use the same general concept: meter events can contain a unique identifier, and Stripe recommends idempotency to prevent duplicate usage reporting.
Your internal guarantee should be authoritative. Do not depend on the billing vendor as your only deduplication layer.
Step 6: Version Provider Pricing
Never calculate historical cost using whatever the provider charges today.
If a model price changes in October and you reconcile September usage in November, an unversioned price table can silently recalculate September incorrectly.
Use a price book with effective dates.
provider: example
model: model-x
service_tier: standard
effective_from: 2026-09-01T00:00:00Z
effective_to: null
input_rate_per_million: ...
cached_input_rate_per_million: ...
output_rate_per_million: ...
tool_search_rate: ...
When usage happens:
- find the rate valid at the event time;
- calculate provider cost;
- store the pricing version or immutable rate reference;
- keep the original usage quantities.
Modern AI pricing can have separate rates for:
- uncached input
- cached input
- cache writes
- output
- reasoning or thinking
- long context
- batch processing
- fast or priority service
- web search
- audio
- images
- video
- cached-context storage
Represent only the dimensions your product actually uses. Do not build a universal pricing language before you need one.
Step 7: Version Customer Billing Rules Separately
The provider price book describes your cost.
The customer price book describes your contract.
Keep them separate.
Example:
Plan: Pro AI
Effective from: 2026-09-01
Included credits: 5,000 / month
Standard AI action: 1 credit
Premium agent workflow: variable credits
Image generation: 10 credits
Overage: enabled
If the credit policy changes later, old billable usage must remain linked to the old rule.
Store the billing-rule version on every billable record.
Otherwise a future recalculation can silently change history.
Step 8: Credits Need a Ledger, Not Just a Balance Column
A single column such as:
account.credit_balance = 743
is easy to start with and hard to explain later.
If a customer asks why 120 credits disappeared yesterday, you need evidence.
Use a credit ledger:
+5000 monthly plan allocation
-42 agent run settlement
-10 image generation
+10 refund for failed generation
-75 agent run settlement
+500 purchased top-up
Each entry should reference the cause:
- subscription grant
- purchase
- usage settlement
- expiration
- refund
- adjustment
- promotion
- admin correction
You can still maintain a materialized current balance for fast reads. The ledger is the audit trail.
Corrections should compensate, not erase
If a charge was wrong, append a reversing entry.
Do not delete the historical usage and pretend it never happened.
Step 9: Decide Exactly What Happens on Failure
AI requests fail in many ways.
Provider rejects before meaningful execution
There may be no billable provider usage.
Provider generates output and the client disconnects
Your infrastructure may still have incurred cost.
Stream fails after partial generation
Some usage may already exist.
First provider fails and fallback succeeds
You may incur cost from both attempts.
Tool succeeds but the agent times out later
The external action happened even if the final answer did not.
Customer cancels a long-running agent
Usage before cancellation may still cost money.
Your cost ledger should record actual infrastructure cost whenever evidence exists.
Your customer billing policy can independently decide whether the customer is charged.
For example:
internal cost:
attempt 1 = $0.012
attempt 2 = $0.041
total = $0.053
customer billing:
successful task = 4 credits
This preserves margin visibility without exposing implementation failures as duplicate customer charges.
Step 10: Treat Retries and Fallbacks as First-Class Accounting Events
Retries are where weak metering starts lying.
Suppose:
provider A call → ambiguous timeout
provider B fallback → success
Your runtime may have two costs.
If you record only the final successful response, internal cost is understated.
Link every provider attempt to the parent product operation:
customer_task_id
├── provider_attempt_1
└── provider_attempt_2
Then you can answer:
> What did task 123 cost us?
and separately:
> What did we bill the customer for task 123?
This becomes especially important for agents that can make dozens of provider calls in one run.
Step 11: Tool Costs Belong in the Same Cost Model
Modern agents can spend money outside the language model.
Examples include:
- paid web search
- image generation
- speech
- OCR
- maps
- email or SMS
- third-party APIs
- browser infrastructure
- sandbox compute
A useful task-level cost view could be:
model inference $0.031
web search $0.020
image generation $0.040
external API $0.005
--------------------------------
variable task cost $0.096
You do not need to allocate every CPU cycle. Track the variable costs that materially affect product economics.
Step 12: Send Billable Usage to the Billing Provider
Your internal usage ledger should be authoritative for execution evidence.
The billing provider should receive the billable result, not necessarily every raw provider token event.
raw provider events
↓
internal cost + product policy
↓
customer billable metric
↓
billing meter event
Stripe's current usage-based billing APIs support meter events and models including pay-as-you-go, flat fee plus overage, and credit-oriented pricing.
A meter event carries concepts such as event name, customer mapping, usage value, timestamp, and unique identifier.
Stripe also notes that meter events are processed asynchronously, so external aggregates may not update immediately.
That is another reason not to use the billing vendor's aggregate as your realtime entitlement counter.
Realtime Entitlements and Invoice Billing Are Different Systems
A billing platform is optimized for invoices and payment collection.
Your application needs to answer in milliseconds:
> Can this tenant start another agent run right now?
That decision should use internal entitlement state:
- remaining included usage
- credit balance
- hard limits
- soft limits
- concurrency
- model access
- feature access
Then billable usage can be synchronized asynchronously to the external billing system.
The two systems must reconcile, but they do not need the same latency or data model.
Soft Limits, Hard Limits, and Agent Kill Switches
Good AI cost control is proactive.
Soft limits
Warn at thresholds such as 70%, 90%, and 100%.
A warning can trigger:
- dashboard notification
- admin alert
- top-up prompt
- model downgrade suggestion
Hard limits
Reject new cost-generating work when:
- monthly credit is exhausted
- project budget is exhausted
- trial limit is reached
- account is suspended
- organization-level cap is reached
Run-level kill switches
A single agent run can itself be expensive.
Set boundaries such as:
- maximum iterations
- maximum model calls
- maximum tool calls
- maximum duration
- maximum token usage
- maximum estimated cost
- maximum credit consumption
Enforce these inside the agent loop.
Checking the monthly balance only at the start is not enough.
Multi-Tenant SaaS: Attribute Every Unit Correctly
Billing bugs can become security bugs when tenant attribution is wrong.
Every usage event should carry trusted server-side ownership context.
At minimum:
tenant_id
account/customer_id
project/application_id where relevant
run/request correlation
Depending on the product, also consider:
- branch or workspace
- API key
- end user
- environment
- cost center
- team
- feature
Never trust a client-submitted tenant identifier without verifying it against authenticated server context.
A usage event attached to the wrong tenant can produce:
- incorrect invoices
- wrong quota enforcement
- data leakage in dashboards
- support disputes
- corrupted margin reporting
Usage attribution deserves the same seriousness as authorization.
Do Not Put Billing Logic in Every Feature
A common failure pattern looks like:
chat endpoint calculates credits
image endpoint calculates credits differently
agent endpoint has another implementation
background worker has another implementation
Eventually one path uses old pricing, another forgets a discount, and another double-charges a retry.
Features should emit well-defined usage facts.
A centralized billing-policy layer should convert facts into billable units.
feature emits:
event_type = image.generated
model_class = premium
quantity = 1
billing policy:
Pro plan → 8 credits
Business plan → 6 credits
Internal account → 0 credits
Centralization does not mean a billing microservice is required.
A well-bounded module inside a modular monolith is perfectly valid. Extract it only when ownership, scaling, or deployment needs justify it.
A Practical Event Contract
A usage event should remain valid even after pricing changes.
{
"event_id": "evt_01...",
"tenant_id": "tenant_123",
"operation_id": "run_456",
"event_type": "ai.provider.completed",
"occurred_at": "2026-09-18T04:30:00Z",
"provider": "provider_name",
"model": "model_name",
"provider_request_id": "req_...",
"usage": {
"input_tokens": 18420,
"cached_input_tokens": 60210,
"output_tokens": 4381,
"reasoning_tokens": 0
},
"dimensions": {
"feature": "support_agent",
"project_id": "project_77"
}
}
Notice what is not inside the raw event:
charge_customer_4_credits = true
That is pricing policy, not usage evidence.
The same raw event should still be meaningful after a plan or provider-price change.
What About Streaming?
Streaming creates a timing problem because final usage may not be available when output begins.
Use a state machine rather than guessing:
reserved
→ running
→ usage_pending
→ usage_finalized
→ billed
If the stream disconnects before final usage is known:
- keep the operation in a recoverable state;
- use provider usage reporting or request metadata where available;
- reconcile later;
- do not silently assume zero.
The exact recovery path depends on the provider, but the ledger should be able to represent "usage not finalized yet."
Reconciliation Is Not Optional
Even a careful pipeline eventually sees:
- duplicate delivery
- missing events
- delayed provider reporting
- network failures
- pricing-table mistakes
- external billing lag
- manual adjustments
Run reconciliation jobs.
Runtime vs internal ledger
Did every provider attempt that should produce usage create an accounting record?
Internal cost ledger vs provider reporting
OpenAI exposes organization usage data. Anthropic exposes organization-level usage reports with model and cache dimensions. Gemini and other providers expose their own usage evidence.
You do not need perfect realtime equality. You need explainable differences.
Internal billable ledger vs billing provider
For each billing period compare:
internal billable quantity
vs
external metered quantity
vs
invoiced quantity
Large mismatches should alert your team before customers discover them.
Metrics Worth Monitoring
Start with metrics that reveal correctness and margin risk.
Usage pipeline
- usage events created
- duplicate events rejected
- usage awaiting finalization
- ingestion lag
- failed billing exports
- external meter lag
Attribution
- events missing tenant
- events missing run correlation
- events missing provider request ID where expected
- events with unknown model or price rule
Cost
- provider cost by tenant
- cost by feature
- cost by model and provider
- retry cost
- fallback cost
- paid-tool cost
- cost per successful task
Billing
- credits granted
- credits consumed
- credits refunded
- overage quantity
- internal vs external meter drift
- invoice reconciliation difference
Risk
- unusual usage velocity
- repeated agent-loop exhaustion
- hard-limit rejections
- unusually expensive runs
- invalid or negative balances
The goal is to catch revenue leakage and runaway cost early.
Gross Margin Is an Engineering Metric in AI SaaS
For traditional SaaS, compute cost is often small relative to subscription revenue.
For AI SaaS, inference and paid-tool cost can be material.
A product team should be able to calculate:
customer revenue
- model/provider cost
- paid tool cost
- directly attributable variable infrastructure
= contribution margin
Then inspect it by:
- plan
- tenant
- feature
- model
- workflow
- cohort
This enables better engineering decisions.
A premium model may be more expensive per token but cheaper per completed task if it reduces retries.
Prompt caching may dramatically lower repeated-context cost.
A popular feature may have terrible unit economics.
The cheapest model on a price sheet is not necessarily the cheapest product outcome.
Credits Should Be Understandable
Credits are useful because they decouple customer pricing from provider mechanics.
But opaque credits create distrust.
Explain:
- how many credits are included
- what common actions usually cost
- whether unused credits roll over
- whether credits expire
- what happens when credits run out
- whether top-ups exist
- whether premium models consume more
- whether failed tasks consume credits
- whether overage can happen automatically
Do not retroactively change the value of already purchased credits.
If pricing changes, version the policy and communicate the effective date.
A Sensible Architecture for an Early-Stage SaaS
Do not overengineer this.
You probably do not need:
- Kafka purely for billing
- a dedicated billing microservice
- a universal pricing DSL
- a distributed event-sourcing platform
- a custom financial database
- a stream-processing cluster
A production-capable early architecture can be:
API / Agent Runtime
↓
Transactional database
- usage_events
- provider_prices
- billing_rules
- credit_ledger
- reservations
↓
Background worker
↓
Billing provider meter API
↓
Scheduled reconciliation
A relational database such as PostgreSQL can handle a large amount of this workload correctly.
Add queues, partitions, analytics stores, or separate services when real volume or team boundaries justify them.
Correctness comes from invariants, not from the number of infrastructure components.
Core Invariants to Protect
Write these down and test them.
Invariant 1
A logical usage event is applied at most once.
Invariant 2
Every billable event belongs to exactly one authoritative tenant/account.
Invariant 3
Historical provider cost is reproducible from original usage and the price version used.
Invariant 4
Historical customer charges are reproducible from the billing-rule version used.
Invariant 5
A retry may increase internal cost but must not automatically duplicate the customer charge.
Invariant 6
A credit correction creates an auditable compensating entry.
Invariant 7
A customer cannot start work that violates a hard entitlement or reservation rule.
Invariant 8
Concurrent reservations cannot spend the same available balance twice.
Invariant 9
External billing export can be retried safely.
Invariant 10
Internal billable totals can be reconciled against external invoiced totals.
If these invariants hold, the implementation can evolve without turning billing into a mystery.
Testing the Billing Pipeline
Billing code deserves stronger tests than normal CRUD.
Unit tests
Test:
- provider usage normalization
- rate-card selection by date
- cached-token pricing
- credit conversion
- plan-specific billing rules
- rounding
- zero usage
- very large usage
- invalid provider data
Idempotency tests
Deliver the same usage event twice.
The second delivery must not create another settlement.
Concurrency tests
Start two reservations against a nearly exhausted balance.
They must not both succeed if combined consumption exceeds the available amount.
Retry and fallback tests
Simulate:
attempt 1 fails after provider usage
attempt 2 succeeds
Verify that both provider costs are recorded while the customer charge follows product policy exactly once.
Streaming interruption tests
Interrupt a stream after partial output and verify the operation remains reconcilable.
Billing-provider outage tests
The product must preserve usage when the external billing API is unavailable.
Historical pricing tests
Change the current rate card and verify that old usage still reproduces its original cost.
These tests protect revenue, customer trust, and gross margin at the same time.
Common Mistakes
"One API request equals one credit"
It breaks when context, output, model choice, or agent depth varies.
Calculating cost only from the final response
Retries, fallbacks, and paid tools disappear from cost reporting.
Storing only total tokens
Provider-specific dimensions such as cached input or thinking usage can be lost.
Using logs as the billing ledger
Logs are observability evidence, not durable accounting.
Trusting only the billing provider's aggregate
External billing can be asynchronous and is not your realtime entitlement engine.
Hardcoding model prices throughout the codebase
Provider pricing changes. Use a versioned rate table.
Mutating old billing records
Use compensating events or ledger entries.
Checking budget only after the agent finishes
The cost has already happened.
Sharing one counter across rate limits, quotas, and spend
Those controls solve different problems.
Overengineering from day one
A transactional database, clear invariants, and reliable workers are often enough.
Example: Multi-Provider Agent SaaS
Imagine three plans:
Starter
1,000 credits included
standard models
no overage
Pro
10,000 credits included
standard + premium models
optional top-up
Business
pooled organization credits
custom monthly budget
negotiated overage
A Pro customer starts an agent run.
Admission
tenant = t_42
available credits = 1,420
max run reservation = 100
reservation accepted
Execution
provider call 1
normal input
cached input
output
tool call
paid web search
provider call 2
premium model
provider call 3
fallback after transient failure
Internal accounting
Each cost-producing operation becomes durable evidence linked to the same agent run.
The cost calculator applies the correct provider price version.
provider cost total = $0.0874
Product billing
The Pro billing rule evaluates the completed workload:
billable credits = 7
Settlement
reserved = 100
actual charge = 7
released = 93
new available balance = 1,413
Export
A billable meter event is sent to the billing platform with a stable unique identifier.
Reconciliation
Later, automated jobs compare:
runtime attempts
↔ internal usage ledger
↔ provider reporting
↔ credit ledger
↔ external meter
↔ invoice
The provider cost can change later without changing what a customer credit means until you intentionally update the customer pricing policy.
When to Use Usage-Based Billing vs Flat Pricing
Usage billing is not automatically better.
Flat pricing can work when
- workloads are predictable
- AI cost is a small percentage of revenue
- heavy users are naturally capped
- pricing simplicity materially helps sales
- gross margins remain healthy
Usage-based or credit pricing becomes more useful when
- workloads vary dramatically
- inference is a meaningful cost
- agent loops create unpredictable consumption
- premium models have different economics
- customers need budget control
- API customers expect metering
- enterprise customers need cost allocation
Hybrid pricing often fits the middle
A subscription can pay for the SaaS platform while credits or overage protect the business from unusually expensive AI usage.
That avoids turning every feature into a tiny transaction while still respecting variable cost.
Production Checklist
Before launching paid AI usage, verify:
- Every usage event has an authoritative tenant.
- Duplicate events can be retried safely.
- Every provider attempt is linked to its parent task/run.
- Important provider pricing dimensions are preserved.
- Provider rates are versioned.
- Customer billing rules are versioned independently.
- Historical provider cost can be reproduced.
- Historical customer charge can be reproduced.
- Credits have an auditable ledger.
- Concurrent jobs cannot overspend the same balance.
- Agent runs have cost/iteration/tool-call limits.
- Streaming failures remain reconcilable.
- Retry and fallback behavior has an explicit billing rule.
- External billing outages do not lose usage.
- Corrections do not rewrite history.
- Provider reporting is reconciled against internal usage.
- External metered usage is reconciled against invoices.
- Cost per successful task is measurable.
- Expensive tenants/features can be identified quickly.
If several answers are "no," the next billing task is not a prettier pricing page. Fix the accounting foundation first.
Final Takeaway
The difficult part of AI SaaS billing is not sending a number to Stripe.
It is defining a trustworthy chain from execution → usage → cost → entitlement → customer charge → invoice.
The strongest design keeps three truths separate:
Provider truth:
What resources did the workload consume?
Business truth:
What did those resources cost us?
Customer truth:
What did the product contract say the customer should pay?
Once those boundaries are clear, tokens, credits, quotas, model routing, retries, agent loops, and multi-provider support become manageable engineering problems.
Without them, every provider change becomes a pricing change, every retry becomes a billing risk, and every invoice dispute becomes log archaeology.
For AI SaaS, usage accounting is not a finance feature added at the end.
It is part of the runtime architecture.
Sources and Further Reading
- Stripe — AI companies and usage-based billing: https://stripe.com/resources/more/ai-companies-and-usage-based-billing
- Stripe Docs — Record usage for billing: https://docs.stripe.com/billing/subscriptions/usage-based/recording-usage-api
- Stripe API — Meter events: https://docs.stripe.com/api/billing/meter-event
- Stripe Docs — Usage-based billing use cases: https://docs.stripe.com/billing/subscriptions/usage-based-v1/use-cases
- OpenAI API Reference — Usage: https://platform.openai.com/docs/api-reference/usage
- OpenAI API Reference — Responses: https://platform.openai.com/docs/api-reference/responses
- Anthropic Docs — Pricing and usage dimensions: https://docs.anthropic.com/en/docs/about-claude/pricing
- Gemini API — Token counting and usage metadata: https://ai.google.dev/gemini-api/docs/tokens
- Gemini API — Billing: https://ai.google.dev/gemini-api/docs/billing

Discussion (0)