Finance wants October’s message bill split by tenant. Your request counter says acme made 80% of the sends, but the provider bills per recipient, and globex’s five bulk sends carried 69% of the units. The counter’s total is also 86 units short of the provider’s export, because the counter cannot see which failed attempts the provider billed.
What you get
You will end up with a per-tenant spend table built from billable units and a bounded tenant label on your counters. A reconciliation states the gap to the billing export and its cause. This is for you if you resell or absorb a provider’s per-unit charges.
Short answer
To attribute API cost to a tenant, meter the units the provider bills on every call, and label
each call with a tenant from a fixed list. Price the units from a table keyed by operation, and
sum per tenant. On an sdkgen client, the cost feature’s path option reads the units from the
response body, and the actor control names the tenant. Then compare the month’s total with the
provider’s billing export and explain the gap.
You will need
Node 22 or later, Python 3.12 or later, and a provider that reports billable units on each
response or in an export. Verified 2026-11-21 against Node 22.23.5, @voxgig/sdkgen 4.44.3,
prom-client 15.1.3, Swagger Codegen 3.0.85, and Python 3.13.18. The document, api.json,
describes a message API that bills one unit per recipient. There is no provider invoice here:
billing/2026-10.json is an export that record.sh wrote from the stand-in’s own ledger, and the
stand-in, server.mjs, serves it. The stand-in fails on a fixed plan, with some 503 responses after billing and
some before, so the month replays the same way every time.
Approaches compared
| Approach | When it fits | What it costs you | When to pick something else |
|---|---|---|---|
| Kong gateway analytics | Outbound calls already pass through Kong, with one Consumer per tenant | Counts requests, the rejected ones included, rather than the units a provider bills | The provider bills per unit or per record |
| Prometheus counters with a tenant label | You run Prometheus and want spend per tenant in near real time | A label set you must bound, and counts that reset on restart and drift from the bill | The figure must match an invoice to the cent |
| The provider’s usage and billing API | The provider exports billed units, and knows your tenants as subaccounts | Arrives after the period, and per account, so one shared account gives no tenant split | You need the split before the month closes |
| sdkgen cost feature | The client is generated by sdkgen, and responses report units | One count per call, so a billed attempt that failed is missing, and the budget is a cutoff | Your client is not generated by sdkgen |
| Speakeasy SDK hooks | The SDK is a Speakeasy one, on a plan that includes hooks | A Business or Enterprise plan, and the tenant passed to the hook by your own code | Hooks are outside your plan |
| Swagger Codegen Python client with a metering wrapper | You generate with Swagger Codegen and can route every call through one wrapper | No response hook or status retry in the client, so metering, retry, and the bearer header are yours | Calls bypass the wrapper anywhere in the codebase |
Voxgig maintains sdkgen, one of the six rows here; the table ranks none of them.
A client-side count is ready as each call returns, but it drifts from the invoice. The export is the bill, but it arrives after the period and per account. Twilio’s usage records, for one, describe subaccounts per end user as the way to bill each one. The useful arrangement uses both: attribute on the client, then hold the client’s total to the export every month.
Meter billable units with the cost feature
generate.sh scaffolds the TypeScript target with the
cost feature and
retry, generates, and builds. The compiled SDK is committed under generated/ts. The feature’s
model file holds its defaults: inactive, with no rates, no path, and no budget.
config: {
options: {
active: false
currency: 'USD'
unit: 0
rates: {}
# response header carrying a reported usage figure (per attempt)
header: ''
# response body path carrying a reported usage figure (per operation),
# e.g. 'usage.total_tokens'
path: ''
perUnit: 0
budget: 0
# once the budget is spent: 'warn' records it, 'deny' refuses the call
onBudget: 'warn'
}
}
makeClient turns it on with path pointing at the response’s usage.units and perUnit: 1, so
the feature records units rather than money. Each call names its tenant in the control argument,
{ actor: tenant }, and sink receives one record per call.
// The tenants the label may name. The platform's own calls are "platform", and anyone else,
// a trial account or a typo, is "other", so the label has five values however many accounts exist.
export const TENANTS = Object.freeze(['acme', 'globex', 'initech'])
export const tenantLabel = (tenant) => (TENANTS.includes(tenant) || tenant === 'platform' ? tenant : 'other')
// The provider's price list, in micro-USD per billable unit, keyed '<entity>.<op>'.
// Whole numbers, so the sums are exact.
export const PRICES = Object.freeze({ 'message.create': 2500, 'message.load': 0, 'usage.load': 0 })
export function price(operation, units) {
if (!Object.hasOwn(PRICES, operation)) throw new Error(`no price for ${operation}`)
return units * PRICES[operation]
}
The price table refuses an operation it does not list, so a new endpoint cannot be attributed as
free. The label is bounded because every label value is a separate time series in
Prometheus.1 replay passes the label, not the raw tenant, as the actor. The feature keeps
client._cost.actors as a plain object keyed by actor, and in a test an actor of __proto__
wrote its totals onto Object.prototype.
Reconcile the month against the export
reconcile.mjs replays month.json through one client, sums the records per tenant, fetches the
export through the same SDK, and states the gap.
node reconcile.mjs
attributed from client records, 2026-10, priced at 2500 micro-USD per unit
tenant calls units USD failed attempts
acme 124 93 0.2325 4 (4 units)
globex 5 400 1.0000 1 (80 units)
initech 16 80 0.2000 2 (10 units)
other 2 4 0.0100 0 (0 units)
platform 1 0 0.0000 0 (0 units)
total 577 1.4425 7 (94 units)
billing export 2026-10: 663 units, 120 billed requests, 1.6575 USD
gap: 86 units, 0.2150 USD, 12.97% of the export
the gap is within the units of failed attempts: true
The client saw seven attempts fail and retried each one. The provider billed four of them, the
503 responses it sent after accepting the message. The client passes its features as a map, which
initializes cost before retry, so retry wraps cost and every attempt reaches it. With
path set, the body figure replaces the per-attempt price, so a call’s units come once, from the
attempt that succeeded. A test lists retry first instead: the units stay the same, and
attempts drops to one, which empties the failed-attempts column. So the gap is 86 units, and one 80-recipient send to
globex makes most of it. The client cannot tell a billed failure from one that was not billed. The check it
can make is a bound: the gap must lie between zero and the 94 units its failed attempts carried.
Write that bound into the monthly check, and the gap into the report. Charge the gap to tenants in proportion to their failed-attempt units, or carry it as platform cost, but say which.
Stop a tenant at a budget
The cost feature’s budget is per client, so give each tenant its own client to give it its own
limit. budget.mjs sets 100 units with onBudget: 'deny' and sends three 80-recipient messages.
node budget.mjs
send 1: spent before 0, sent, spent after 80
send 2: spent before 80, sent, spent after 160
send 3: spent before 160, refused with cost_budget
budget 100 units: spent 160, exceeded true
requests the stand-in received: 2
The second send went out at 80 units spent and took the total to 160. The budget is checked against the spend so far, so it is a cutoff rather than a cap, and the call that crosses it is let through. The refused call never reached the stand-in.
Meter the same month with Swagger Codegen and Speakeasy
Swagger Codegen’s Python client has no response hook and no status retry; its one hook,
refresh_api_key_hook, runs when an API key is read. Its auth_settings() comes out empty for
this document’s bearer scheme, because the Python template has branches for API key, basic, and
OAuth schemes only. So swagger_meter.py sets the Authorization header with
set_default_header and routes every call through TenantMeter. It reads usage.units from each
returned model, retries a 503 up to twice as the sdkgen client does, and replays the same month.
python3 swagger_meter.py
attributed through the Swagger Codegen client, 2026-10
acme 124 calls 93 units 0.2325 USD, failed attempts 4
globex 5 calls 400 units 1.0000 USD, failed attempts 1
initech 16 calls 80 units 0.2000 USD, failed attempts 2
other 2 calls 4 units 0.0100 USD, failed attempts 0
total 577 units
The wrapper attributes the same 577 units. It also counts units from the attempt that succeeded, so its gap to the export is the same 86 units.
The Speakeasy CLI starts with an account
login, so it was not run
here. Its SDK
hooks are for Business and
Enterprise users only. An after_success hook receives the hook context, with its
operation_id, and the response, and after_error receives the failures, so it can count units
and failed attempts. None of the context fields the page lists is a tenant, so set one in a context
variable around each call and read it in the hook. Register the hook in src/{sdk_name}/_hooks/registration.py, which the page says the
generator does not overwrite.
Check it worked
cost.test.mjs replays the month twice, once through each client, and checks the totals against
the export and against each other.
node --test cost.test.mjs
1..14
# tests 14
# suites 0
# pass 14
# fail 0
# cancelled 0
# skipped 0
# todo 0
# duration_ms 1964.716313
Three tests carry the claims. One asserts that the gap equals the units the stand-in billed for
failed attempts and lies within the client’s bound. One asserts that the committed export is what
the stand-in bills on a fresh replay, so the export cannot drift from the month. The third
compares the Swagger Codegen replay with the sdkgen one, tenant by tenant. Two more hold the label
to its five values against tenant names such as __proto__ and one carrying a newline, and show
the wrap order changing the attempts but not the units.
When it goes wrong
The bulk tenant reads as cheap. A counter of requests, or a rate per request, prices an 80-recipient send like a single one. Count the units the response reports.
node metrics.mjs
mailroute_billable_units_total{tenant="acme",operation="message.create"} 93
mailroute_billable_units_total{tenant="acme",operation="message.load"} 0
mailroute_billable_units_total{tenant="globex",operation="message.create"} 400
mailroute_billable_units_total{tenant="initech",operation="message.create"} 80
mailroute_billable_units_total{tenant="other",operation="message.create"} 4
mailroute_billable_units_total{tenant="platform",operation="usage.load"} 0
share of sends by calls: acme 80%, initech 14%, globex 4%, other 2%
share of sends by units: globex 69%, acme 16%, initech 14%, other 1%
tenant label values: acme, globex, initech, other, platform
The attributed total runs short of the export. Retried failures that the provider billed are
counted once on the client. Report the gap with its bound, as reconcile.mjs does, rather than
scaling the tenants’ figures up to match.
The counters reset to zero after a deploy. A Prometheus counter lives in the process, so a month
total read from it misses whatever a restart lost.2 Keep the month’s ledger from the sink
records in a store, and use the counters for the near-real-time view only.
When not to do this
Do not attribute from client counters when the provider can do it for you. A subaccount per tenant puts the split on the invoice itself, which makes the reconciliation unnecessary.
Do not use the sdkgen cost feature as the bill. It counts each call’s units once, from the response that arrived, and its budget is a cutoff that lets one call past the limit. It suits a client sdkgen already generates, for the near-real-time split.
If you already generate with Swagger Codegen, keep it: one small wrapper class meters every call
routed through it, with no second generator to adopt. On a Speakeasy SDK whose plan includes
hooks, an after_success hook sees every call without a wrapper.
Related how-tos
Last verified
Verified 2026-11-21 against Node 22.23.5, Python 3.13.18, @voxgig/create-sdkgen 0.31.9,
@voxgig/sdkgen 4.44.3, @voxgig/apidef 8.32.4, prom-client 15.1.3, and Swagger Codegen 3.0.85 on
Java 21. Every output block is what the command preceding it printed. The two generators ran once,
in generate.sh, and their output is committed under generated/. Speakeasy was not run; its
hooks and plan are described from its documentation, and Kong’s analytics from Kong’s.
Footnotes
-
Prometheus’s naming page says every unique combination of label values is a new time series. It tells you not to store high-cardinality dimensions such as user IDs or email addresses in labels. The list ends on other unbounded sets of values, which is the set a tenant id belongs to wherever tenants sign themselves up. ↩︎ Back to text
-
Kong sells metering, and its own Prometheus collector page warns that Prometheus metrics and queries are not designed for billing. It names two causes, metrics lost when an app restarts before a scrape and duplicates that are never removed, and recommends monetizing them only for long-running workloads. ↩︎ Back to text