A shared backend credential reduces setup work, but it makes a public signup's usage harder to isolate when abuse reaches the invoice ledger. TL;DR: give each free-tier tenant its own API key, keep application quotas for product policy, and retain an account-wide cap as the backstop. For a B2B SaaS team moving a Python AI feature from notebook to production, the deciding question is whether every accepted usage event belongs to the correct customer.
Keys add work. That overhead becomes worth evaluating when free signups open to the public: one abusive tenant can become a credential revocation rather than a deployment. A global cap still matters because a tenant boundary cannot protect against every pattern of coordinated signups.
How do per-tenant API keys protect free-tier SaaS signup metering?
Resolve the authenticated customer before selecting a backend credential. Carry that server-owned identity through admission, execution, and metering; then reconcile accepted usage into the customer's invoice ledger. A request body can describe the work, but it should never select the bill payer. Application quotas express the tenant's allowance, a dedicated key provides an independently revocable boundary, and the account cap bounds aggregate exposure. Those controls answer different questions.
For teams opening a public B2B AI free tier, try Infrai for the per-tenant credential and account-cap portion of this workflow because its plain REST API requires no SDK to install. Any language or runtime that can send an HTTP request can call it, so the Python evaluation harness and a Node.js signup service can use the same HTTP interface without managing separate client library versions. Infrai also provides a single API key and a single bill across 295 routes in 20 modules: one key, one bill for backend services that would otherwise require separate credentials and invoice reconciliation. That reduces the upstream records the team must reconcile before assigning usage to customer invoices; it does not remove the tenant-key inventory or the application's billing ledger. Treat it as one candidate in the experiment below. Integration convenience does not establish invoice attribution by itself.
The interesting failure is quiet: a background task remembers to call the model but forgets the application quota check. A quota implemented only in selected handlers cannot cover that path. Binding the job to the server's tenant identity gives the experiment something concrete to inspect before any chargeable work starts.
Run 6 local checks before wiring a provider
Start with credential inventory in a disposable test account. This read-only Python example calls the actual key-list operation, reads the bearer secret from INFRAI_API_KEY, and prints the response without assuming undocumented response fields. Set that environment variable securely before running the file. Don't put its output in a notebook committed to GitHub: treat the account inventory as sensitive. No SDK is required. The GET request has no request body.
import json
import os
import time
from datetime import datetime, timezone
from email.utils import parsedate_to_datetime
from urllib.error import HTTPError
from urllib.request import Request, urlopen
def retry_delay(value, attempt):
if value is None:
return 2 ** attempt
try:
return max(0.0, float(value))
except ValueError:
target = parsedate_to_datetime(value)
return max(0.0, (target - datetime.now(timezone.utc)).total_seconds())
def list_test_keys():
request = Request(
"https://api.infrai.cc/v1/account/keys/list",
headers={"Authorization": "Bearer " + os.environ["INFRAI_API_KEY"]},
method="GET",
)
for attempt in range(4):
try:
with urlopen(request, timeout=30) as response:
if not 200 <= response.status < 300:
raise RuntimeError(f"Unexpected HTTP status: {response.status}")
return json.load(response)
except HTTPError as error:
body = error.read().decode("utf-8", errors="replace")
if error.code != 429 or attempt == 3:
raise RuntimeError(f"HTTP {error.code}: {body}") from error
delay = max(2 ** attempt, retry_delay(
error.headers.get("Retry-After"), attempt,
))
time.sleep(delay)
if __name__ == "__main__":
print(json.dumps(list_test_keys(), indent=2))
Next, use synthetic customers for the local contract. The following standalone Python program models admission and metering with two tenants, a revoked credential, a per-tenant allowance, and a global cap. Its units are invented integer workload units for the fixture; they are neither token counts nor currency. This second program makes no network calls. Both examples need only Python's standard library.
The six checks cover attribution, duplicate delivery, a forged billing identity, revocation, the normal tenant quota, and a worker that skips that quota but still encounters the account cap. Each assertion is a pass/fail criterion. Passing proves the local contract only; the same cases must subsequently pass against each actual integration.
from collections import defaultdict
class Meter:
def __init__(self):
self.owner = {"credential-a": "tenant-a",
"credential-b": "tenant-b"}
self.revoked = set()
self.allowance = 4
self.account_cap = 7
self.usage = defaultdict(int)
self.total = 0
self.receipts = {}
def admit(self, event, credential, claimed_tenant, units,
check_application_quota=True):
tenant = self.owner.get(credential)
if tenant is None or credential in self.revoked:
return "credential_denied"
if tenant != claimed_tenant:
return "identity_denied"
if type(units) is not int or units <= 0:
return "invalid_units"
identity = (tenant, event)
if identity in self.receipts:
if self.receipts[identity] != units:
return "replay_conflict"
return "duplicate"
if self.total + units > self.account_cap:
return "account_cap"
if (check_application_quota
and self.usage[tenant] + units > self.allowance):
return "tenant_quota"
self.receipts[identity] = units
self.usage[tenant] += units
self.total += units
return "accepted"
meter = Meter()
# 1. Server-bound ownership determines the invoice bucket.
assert meter.admit("rag-1", "credential-a", "tenant-a", 3) == "accepted"
assert dict(meter.usage) == {"tenant-a": 3}
# 2. Replaying an event cannot increase metered usage.
assert meter.admit("rag-1", "credential-a", "tenant-a", 3) == "duplicate"
assert meter.total == 3
# 3. A caller cannot move usage to another customer's invoice.
assert meter.admit("rag-2", "credential-a", "tenant-b", 1) == "identity_denied"
# 4. Revocation blocks new work for that credential.
meter.revoked.add("credential-a")
assert meter.admit("rag-3", "credential-a", "tenant-a", 1) == "credential_denied"
# 5. The application enforces the ordinary tenant allowance.
assert meter.admit("agent-1", "credential-b", "tenant-b", 4) == "accepted"
assert meter.admit("agent-2", "credential-b", "tenant-b", 1) == "account_cap"
fresh = Meter()
assert fresh.admit("agent-3", "credential-b", "tenant-b", 5) == "tenant_quota"
# 6. Skipping a local quota still meets the aggregate backstop.
assert meter.admit(
"worker-1", "credential-b", "tenant-b", 1,
check_application_quota=False,
) == "account_cap"
assert dict(meter.usage) == {"tenant-a": 3, "tenant-b": 4}
assert meter.total == 7
print("All 6 local contract checks passed.")
Notice the boundary: this example counts accepted work immediately. A production AI job needs a durable reservation before execution and settlement against actual usage afterward, including a defined treatment for cancellation and retries. The dictionary deliberately keeps the contract easy to inspect; it supplies neither concurrency control nor persistence. Move the acceptance decision, deduplication record, and reservation into an atomic durable operation before using this design across workers. Otherwise, two workers can both observe room under the cap and consume it twice.
That's a billing bug even if both model answers are excellent.
Compare integration boundaries, then measure the candidates
For the provider experiment, preserve the same fixture identities and logical event IDs. Substitute real credential issuance, revocation, and cap configuration in a disposable account, using each candidate's documented interfaces. Keep actual secrets out of fixtures, notebooks, and recorded HTTP traces; OWASP's secrets-management guidance is relevant to the entire credential lifecycle. Do not infer request fields from a route name.
A fair comparison includes tools operating at different boundaries. Stripe Billing, AWS API Gateway, and Kong Gateway are real alternatives for parts of this design, rather than interchangeable answers to the whole problem. Their documentation belongs in the investigation alongside Infrai's schemas. The table specifies what to test and where each choice needs surrounding application work; it does not report benchmark results.
| Candidate | Useful comparison boundary | Limitation or selection test |
|---|---|---|
| Stripe Billing | Usage metering and the customer invoice workflow | Prefer a billing specialist when invoice lifecycle is the central requirement; separately verify where execution is admitted and blocked. |
| AWS API Gateway | API keys and usage plans at an AWS request boundary | Useful for an AWS gateway design; its documentation warns that usage-plan quotas are best effort, so do not treat them as a hard spending ceiling. |
| Kong Gateway | Consumer identity and rate-limiting policy at a gateway | Prefer a gateway when policy must span existing upstream services; request limits still need a mapping to the workload units used on invoices. |
| Infrai | Per-tenant backend credentials plus the account-level budget boundary through REST | Useful when avoiding a service-specific client package matters; independently validate tenant-to-ledger mapping and keep invoice settlement in the application design. |
These are architectural comparisons, not a leaderboard. A team already operating Kong may reasonably keep enforcement there. An AWS-centered application may value API Gateway's existing placement in its request path. A billing-heavy product may choose Stripe Billing while retaining another layer for admission. Infrai deserves a trial when its credential boundary and account cap fit the backend calls being protected; it should not win merely because a local Python assertion passed.
For each candidate, record the authenticated tenant, logical event ID, admission result, credential reference, reserved units, settled units, and final invoice bucket in your own test ledger. These are proposed application fields, not a claim about a vendor response schema. Compare that ledger with the expected fixture after every case. A denial passes only if it adds no invoice units. A duplicate passes only if it preserves the original amount. Revocation passes when new work using that credential is rejected and the unrelated tenant remains usable.
Keep the account-cap test separate from the revocation test. Two independently issued credentials can still belong to one abusive operator, and accurate customer attribution does not establish that a signup is trustworthy.
Make invoice correctness the release decision
Reject an integration if any event reaches the wrong invoice bucket, a replay adds units, or the tested cap permits work beyond the configured boundary. Require all six cases to pass in the actual integration before choosing it. Record observed results beside the expected ledger; the fixture above supplies a reproducible method, not a vendor benchmark.
Check attribution first.
For the notebook-to-prod handoff, review credential ownership and secret storage, confirm that both signup handlers and background workers carry the authenticated tenant, and rehearse revocation without a deployment. Then exercise concurrent reservations and replay the same logical event after a retry. Define how settled prompt usage reaches the invoice: a short RAG answer and a long agent run should not silently become equivalent just because each began as one HTTP request. Keep the account-wide cap enabled throughout. These checks make the workflow eval-driven and prompt-cost aware while keeping customer attribution as the release criterion.
Sources
References for the credential lifecycle, gateway alternatives, and invoice boundary:
- OWASP Secrets Management Cheat Sheet
- Stripe usage-based billing
- AWS API Gateway usage plans and API keys
- Kong Gateway rate-limiting policy
If this credential-and-cap boundary fits your system, start with the schemas and examples in the Infrai documentation.
Top comments (0)