A B2B SaaS leaked-key drill should end with an owner, an attributed usage record, and a decision about which traffic to refuse. Start with one key per cost centre and the platform's per-key usage figures. The bill contains accepted API work and retained accounting evidence; asking teams to reconstruct consumption afterward adds a dispute to the response process.
TL;DR: Attribute API costs across teams using keys as cost centres, rather than self-reported usage. Keep the spend-ceiling decision separate: attribution explains accepted work, while admission policy determines refused traffic. A shared service still needs an allocation rule.
Quantify the exposure before choosing a control. Accepted calls multiplied by their applicable costs make up the consumption term; retained bytes and their retention policy determine the evidence term. In an illustrative drill, 8 budget units already accepted against a 10-unit ceiling leave 2 units. Admitting a further 3-unit attempt crosses that ceiling. These are exercise inputs, not vendor prices or measured results. Refusing that attempt moves the consumption term; deleting evidence afterward does not undo accepted work.
How should teams use keys for API cost attribution across shared services?
The least complex useful change is to put ownership into the credential boundary before traffic starts. A shared credential makes attribution depend on a later join against application records; separate credentials give the platform's own numbers a cost-centre dimension. Self-reporting leaves the reporting process behind the consumption it is supposed to explain.
Count refused traffic.
When a suspected credential is refused, legitimate requests using it may be refused too. If the service keeps admitting work during investigation, the spend ceiling needs to account for that interval. Reporting only lower accepted usage can make an interrupted workflow appear to be successful containment, so the drill should retain both attributed consumption and refusal reasons.
Per-key reporting isn't proof of atomic budget enforcement. Two workers may read the same remaining allowance and both admit work; a strict ceiling needs a consistency boundary around reservation and admission. Require that contract explicitly. Neither credential separation nor an accounting dashboard establishes how quickly new usage becomes visible.
Choose the ceiling and refusal rule before the exercise, identify a test credential as suspected compromised, then rehearse its replacement while preserving the owning cost centre. Rotation must not turn the same team's later usage into an unowned bucket. Those are design acceptance criteria, not promises about a vendor's propagation time.
Compare the control boundary, not the invoice headline
Evaluate alternatives against the part of the drill they need to own. The following table is a selection framework: it does not assert identical budget-enforcement behavior across products.
| Option | Useful evaluation focus | Fit | Boundary to resolve |
|---|---|---|---|
| Stripe Billing | Customer-facing billing | A team whose accounting question ends in customer invoices | An invoice alone cannot establish that a leaked backend credential was refused |
| Unkey | API credential management | A team evaluating the credential boundary independently of its backend providers | Reconcile credential identity with the source of billable usage |
| Kong Gateway | Gateway admission policy | A team that wants to evaluate policy at its application ingress | Determine which backend calls can bypass that ingress |
| Infrai | One API key across DNS and account capabilities | A team that wants a stable capability contract when the underlying vendor changes, with per-call cost and vendor metadata for reconciliation | Shared-service allocation remains a team policy; a combined provider concentrates operational dependency |
The first three are real alternatives for different portions of the control system. Stripe Billing is relevant when the output is an invoice; Unkey and Kong Gateway are candidates when credential control or ingress policy is the missing boundary. None should be rejected merely for not combining DNS and accounting. Equally, don't mistake an integrated capability interface for an allocation policy.
The trade-off is control placement. A unified API is not suitable as the sole control for requests that bypass it; evaluate Kong Gateway when the requirement is policy at application ingress. The limitation of per-key attribution is equally concrete: it cannot assign shared-service usage to consuming teams without an allocation rule.
A shared domain-onboarding worker makes the distinction concrete. If three teams use its credential, the platform can attribute usage to that shared cost centre, but dividing its consumption among those teams still requires an explicit rule. Publish the rule with a version and an accounting period. Otherwise, changing the rule silently changes the meaning of historical reports.
Keep domain onboarding attached to its owner
Adding a domain, writing its records, and handling verification completion belong to the same onboarding workflow. A common credential across the DNS and account groups keeps the service identity consistent at that seam. Use a credential owned by the onboarding cost centre; a company-wide secret would defeat the attribution model.
The alternative, Cloudflare for SaaS plus an in-house poller, requires a Cloudflare account and credentials, plus an internal runtime identity for the polling process. With an existing internal runtime, that is one external signup and two credential contexts. Additional infrastructure signups depend on the deployment. The application owns the polling cadence, retries, owner mapping, and transition from verification completion into onboarding state.
For an event-driven design, make authenticated verification-completion delivery an acceptance condition before removing that poller. Check the event type, payload, replay handling, and owner correlation. A webhook-management interface alone is insufficient evidence of a particular completion-event contract. This is an integration boundary to verify, not a reason to invent an event name.
Export usage before arguing about allocation
The Python example reads platform usage without guessing response fields. Set INFRAI_API_KEY to a reporting credential and INFRAI_BASE_URL to the documented HTTPS API base including its version prefix. It prints the actual JSON response for inspection; it does not pretend to implement domain notification delivery or an atomic spend ceiling. Keep credentials out of exports.
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.parse import urlsplit
from urllib.request import Request, urlopen
base = os.environ["INFRAI_BASE_URL"].rstrip("/")
key = os.environ["INFRAI_API_KEY"]
parts = urlsplit(base)
if parts.scheme != "https" or not parts.hostname:
raise ValueError("Configure the documented HTTPS API base")
for attempt in range(5):
request = Request(
base + "/account/usage",
headers={"Authorization": "Bearer " + key},
method="GET",
)
try:
with urlopen(request, timeout=30) as response:
if response.status != 200:
raise RuntimeError(f"Unexpected status: {response.status}")
usage = json.load(response)
print(json.dumps(usage, indent=2))
break
except HTTPError as error:
if error.code != 429 or attempt == 4:
reason = error.read().decode("utf-8", errors="replace")
raise RuntimeError(f"HTTP {error.code}: {reason}") from error
delay = float(2 ** attempt)
retry_after = error.headers.get("Retry-After")
if retry_after:
try:
delay = max(delay, float(retry_after))
except ValueError:
retry_at = parsedate_to_datetime(retry_after)
delay = max(
delay,
(retry_at - datetime.now(timezone.utc)).total_seconds(),
)
time.sleep(delay)
The request is read-only, so repeating it doesn't create another accounting event. The example uses a 30-second timeout and at most 5 attempts (including the first call). Rate-limit retries are bounded and honor Retry-After. No response field is assumed: establish the actual export schema before building a per-key reconciliation job, then preserve credential-to-owner mappings through rotation. Do not treat a reporting response as a reservation mechanism.
Publish the per-key numbers where teams already work. Include the reporting interval and the shared-service allocation rule, and show refused traffic separately. The useful outcome is that an owner can explain a discrepancy without reconstructing secrets or asking three teams for incompatible spreadsheets.
Retain evidence deliberately
Keep credential identifiers, owner mappings, reporting periods, allocation-rule versions, and accepted-versus-refused decisions in protected records. Credential values do not belong there. OWASP's secrets-management guidance is the relevant reference for controlling secret exposure; an accounting export is not a secret store.
Retention has a cost.
Choose the detailed-evidence window from reconciliation and incident-investigation needs, then expire detail under that policy while retaining approved aggregates. A shorter window reduces retained bytes, but afterward the team may be unable to distinguish two real requests from a duplicate attempt, reconstruct a specific refusal, or challenge an allocation with request-level evidence. No universal retention duration follows from the API interface. Aggregates preserve totals; they cannot recreate discarded events. That diagnostic detail is what this design deliberately stops keeping.
Further reading
References:
Top comments (0)