Three ledgers that must agree
When your customers pay you by usage and your providers bill you on your own keys, there are three records of the same activity. The first is your billing meter: units delivered to each customer and the price charged. The second is the request log: what each request consumed and what it probably cost. The third is the provider's invoice: what you actually owe. Usage-based billing for an AI feature is mostly the work of keeping those three consistent and bounded.
The order of work matters, because each step constrains the next:
- Choose the billable unit.
- Price it from provider cost, and check margin across customer shapes.
- Decide between unit balances and metered invoices.
- Record one usage event per delivered unit.
- Enforce a cap before the provider call.
- Reconcile all three ledgers every period.
The FinOps Framework lists unit economics and invoicing and chargeback as separate capabilities, and states as a principle that FinOps data should be accessible, timely and accurate.1 That is a fair summary of what a billing pipeline has to be. For the event-design details behind step 4, see the companion post on metering AI usage; this guide adds pricing, caps and reconciliation around it.
Step 1: choose the billable unit
Providers meter in their own units, and those units differ by modality. INFRO's docs list the metering unit per endpoint: tokens for text, images for image generation, seconds of output for video, characters for speech and hours of audio for transcription.2 None of these is something a customer can forecast. A customer can forecast "500 documents a month" or "20 minutes of transcription".
Tokens are also unstable underneath you. Anthropic notes that Claude 4.7 and later models use a newer tokenizer that produces approximately 30% more tokens for the same text, with the exact increase depending on content.3 If you bill tokens, a model upgrade changes every customer's invoice. If you bill documents, it changes only your margin, which is where that risk belongs.
| Unit | Example | Fits when | Risk you carry |
|---|---|---|---|
| Raw tokens | 1M tokens | Customers are developers buying model access | Customer bills move with model and tokenizer |
| Work unit | Document, answer, image, minute | The unit has a stable meaning to the customer | Cost per unit can drift |
| Outcome | Ticket resolved, task completed | Value is measurable and "done" is defined | Disputes over what counted |
Pick the work unit unless your customers are buying raw model access. Keep the provider cost of each unit as an internal field on the same event, so the gap between price and cost is queryable per customer.
Define the unit by what the customer receives, not by what you call. A "document summarized" is one unit whether it took one provider call or four. Agent-style features that fan out into many calls are the reason to bill the outcome and not the call count.
Step 2: price from the 90th percentile, then test the margin
Start from the provider cost of one unit at your 90th percentile, not the median. Expensive inputs (long documents, long conversations) are the ones that erode margin, and a median-priced unit loses money on them. Add the cost of retries and failures you absorb. The result is the floor under your price.
You need real distributions to do this. INFRO's unit-economics endpoint returns estimated cost per run with median and p90, per request, and grouped by feature, end user or cost center, with the unpriced share beside every figure so a partial number never reads as a whole one.4 Any request-level log that records cost per request and a run or trace id will give you the same shape.
Rates move, and some rates have steps. Anthropic lists Haiku 5.5 with a higher input and output rate for prompts over 100,000 tokens than for shorter ones,3 so a long-context customer can cost several times as much per token as a short-prompt one on the same model. Price on the input shapes you will actually serve.
Two checks before you publish a price. First, compare the floor to what the unit is worth to the customer; if the floor is close to the value, change the design (a smaller model, shorter context) before changing the price. Second, re-run the table whenever a provider changes a rate or you change the default model.
Step 3: unit balances or metered invoices
There are two ways to turn units into money, and many products combine them.
Unit balance. The customer holds a balance of units, bought in a pack or included in a plan, and each delivered unit decrements it. Your application owns the balance, so refusal at zero is easy and the customer's spend is capped by construction. The costs are accounting and support: unused units need an expiry policy that your finance team and terms agree on, and customers will ask what happens to a balance when they cancel.
Metered invoice. You record usage during the period and invoice in arrears, at a per-unit price, perhaps with an included amount. Nothing needs to be bought in advance, and large customers usually prefer it. The exposure is yours: usage accrues before payment, so a customer who overruns or never pays leaves you holding the provider cost.
| Unit balance | Metered invoice | |
|---|---|---|
| Customer sees | A balance that runs down | An invoice after the period |
| Overrun | Stops at zero by design | Needs a cap you enforce |
| Your cash risk | Low: the customer pays first | Higher: you pay the provider first |
| Edge cases | Expiry, refunds, rollover | Disputes, late usage, proration |
| Best for | Self-serve, small accounts | Contracts, large variable usage |
A common shape is an included allowance per plan with metered overage above it, plus a hard stop on self-serve accounts. Whichever you choose, the cap in step 5 is the same control; a balance simply makes it explicit.
Step 4: record one event per delivered unit
The meter is the record of truth, so build it as an append-only log. Each event carries a unique, stable id (your request id), the customer id, the unit and quantity, a timestamp, the feature, and, for margin analysis only, the model and the estimated provider cost. Write it after the unit is delivered, never before the call, so failed requests do not bill. Corrections are new events with a negative quantity, never edits.
Decide in writing how each of these bills before the first invoice:
- Failed requests. Usually nothing, but count them separately so totals reconcile.
- Retries. The customer got one result, so bill one unit and absorb the duplicate provider cost; the 5% allowance in the example is that cost.
- Cut-off streams. Decide whether a partial answer is a unit.
- Cached answers. A response served from an exact-match cache never reaches the provider, so the provider does not bill it.5 You choose whether the customer still pays for the unit.
- Internal and trial traffic. Give it a separate customer id or project so it never produces a billable event.
If you route through a gateway, make sure the customer id travels on every request. INFRO reads it from metadata.user_id (or the X-INFRO-User-Id header), as your own opaque string of up to 128 characters, and recommends an opaque id rather than an email address because it is stored with every request.6
from openai import OpenAI
client = OpenAI(base_url="https://api.infro.io/v1", api_key=INFRO_GATEWAY_KEY)
resp = client.chat.completions.create(
model="anthropic/claude-sonnet-5.5",
messages=[{"role": "user", "content": document_text}],
extra_body={"metadata": {"user_id": "cust_42"}}, # your opaque customer id
)
# Record the unit only after a successful response.
record_unit(event_id=resp.id, customer="cust_42", unit="document", quantity=1)Per-customer usage can also be pulled after the fact. INFRO's usage export returns one row per end customer, period, project and model with requests, failed and cached counts, tokens and estimated provider cost, from the console as CSV or from the API as JSON; the response is flagged as an estimate, and the export is included from the Team plan.7 Use it to cross-check your own events, not to replace them: the docs are explicit that INFRO measures and you bill.
Step 5: enforce the cap before the provider call
An invoice reports spend after it happened. For a product that gives every signup access to a model, the exposure in the gap is real: one script on a free account can run up provider cost before any monthly job notices. The cap has to sit on the request path.
There are two layers, and they do different jobs.
- Entitlement check in your app. For unit balances, reserve before you call and settle after. Reserve the maximum units the request could consume, refuse if the balance cannot cover it, and release the difference on completion. This is where a customer sees "you have 12 documents left".
- Dollar cap at the gateway. A backstop in provider-cost terms that holds even if your entitlement logic has a bug, or a retry loop calls the model many times for one unit.
INFRO's end-customer caps implement the second layer. A rule sets a default amount in US dollars per period (daily, weekly or monthly, all in UTC) for every end customer, with one rule per organization and optionally one per project; an override changes the amount for a single customer, including 0 to refuse every priced request or null for no cap. A request that would exceed the cap is refused before it reaches your provider, and the behavior can be block or alert.6 A request with no customer id can be served or refused, so decide which, and keep batch jobs and evaluations in a project that does not refuse them.6
A refused request returns a 402 with the time the cap resets, which your app can turn into an upgrade prompt. Because overrides can be set from your backend through the management API, a plan change or an overage purchase can raise one customer's cap immediately; the docs say an override applies from the next request.6
def call_with_balance(customer, est_units, do_call):
if not ledger.reserve(customer, est_units): # atomic decrement
raise OutOfUnits(customer)
try:
result = do_call() # 402 here means the dollar cap fired
ledger.settle(customer, reserved=est_units, actual=result.units)
return result
except Exception:
ledger.release(customer, est_units) # failed calls bill nothing
raiseSize the dollar cap from your plan, not your hopes. Multiply the units the plan includes by the worst-case provider cost per unit from your margin table, then add an allowance for burst. That keeps a runaway loop from spending more than the plan can pay for. Concurrent requests can land together, so leave headroom rather than setting the cap at exactly the plan's cost; the per-customer limits post covers rate and token limits alongside spend caps.
Step 6: reconcile to the provider invoice
Your customers' invoices are based on units, so they will always be internally consistent. The risk is on the cost side: your estimate of what the provider will bill drifts from what it does bill, and your margin table is then wrong without anyone noticing.
Reconcile in two hops each period.
- Meter to request log. Units billed per customer should match delivered requests in the gateway log, after excluding the cases you decided not to bill. Differences are retries, failures, cache hits and internal traffic; list them by category instead of netting them.
- Request log to provider. The gateway estimates each request when it serves it, from your own rate for that model and provider if you entered one, else the vendor's list rate, and once a day compares that with the cost the provider reports for the same UTC day, storing both figures with the variance and, when a gap persists, its likely cause.5 The comparison reads OpenAI's cost API and Anthropic's cost report using a separate admin credential, excludes the current day, and leaves cache-served requests out of its side because the provider reports nothing for them.5
A steady gap in one direction is a finding. A provider that bills a fixed fraction of your list-rate estimate usually points to a contract or committed-use rate you have not entered; entering your negotiated rate, per model and optionally per provider, makes later estimates use it ahead of the list rate.5
Never bill customers from the reconciled figure. It is a cost input to your margin report, and the docs note it is an estimate, not an invoice.4
What the gateway can supply
INFRO is a control plane over provider accounts you already hold: your providers invoice you directly, and INFRO charges a subscription with 0% taken from model spend.2 For this build it supplies pieces you would otherwise write: attribution of every request to your customer id, estimated provider cost per request and per customer, end-customer caps that refuse before the provider call, a per-customer usage export, and daily reconciliation against OpenAI's and Anthropic's cost APIs. It does not invoice your customers or hold their payment details; that stays in your billing system.
Launch checklist
- The billable unit is defined by what the customer receives, with heavier units weighted.
- Price is set from p90 provider cost plus absorbed retries, and a margin table covers light, plan-sized, heavy and worst-case customers.
- The policy for failed, retried, cut-off, cached and internal requests is written down.
- Usage events are append-only, written after delivery, with a stable id as the dedup key.
- Every request carries an opaque customer id, and requests without one are either refused or routed to a non-billable project.
- A per-customer dollar cap is active at the gateway, with a backend path to raise it on upgrade.
- Meter-to-log and log-to-provider reconciliation run every period, with negotiated rates entered.
- The margin table is re-run when a provider rate, tokenizer or default model changes.
