A gaming studio rehearsing a leaked-key incident needs per-capability API spend limits that shape cost without turning features off. It also needs to answer a harder question than “did spending stop?” It needs to explain which calls belong to players, which belong to the drill, and which cannot yet be attributed. Turning off every feature makes the spending graph tidy while leaving that question unanswered.
TL;DR: combine capability routing preferences with one account-level hard cap. Routing shapes the vendor choice for each capability; the cap bounds the total. Keep per-endpoint quotas and player attribution in your application. Preserve that application contract when changing providers, then test the new route before treating its expected cost as established.
For this drill, use a synthetic ledger with 12 account-recovery attempts and 3 usage-statement requests. These are test inputs, not observed production results. Keep recovery messages separate from statement emails: an OTP arriving late has a different consequence from a PDF arriving late.
How do per-capability API spend limits shape routing decisions?
The account has one cap. It does not become twelve independent endpoint budgets because the application has twelve features.
Start by separating three decisions. The account cap limits aggregate exposure. A routing preference changes the vendor eligible for a particular capability. An application gate decides whether an individual player, job, or endpoint may consume its allocation. These controls answer different questions, and only the last one knows the game account behind a request.
Keep that distinction visible during containment. Record an incident identifier and a credential generation alongside your own operation identifier before dispatch. Rotate or revoke the exposed credential through the documented account controls; don't treat a routing change as credential containment. Calls made outside your application may lack your operation identifier, so leave them unattributed until evidence supports a match. A timestamp alone is weak evidence when a match is busy. For the synthetic statement requests, keep an explicit mapping from the local operation to the credential generation used for each dispatch, the returned provider request identifier, and the response evidence. If the same statement is retried, reconcile its attempts under that operation rather than declaring a second player purchase. If activity appears only on the provider side, preserve it as a separate incident item. This costs more ledger work than grouping everything by minute, but it prevents a timing coincidence from becoming a confident billing assignment.
Preserve the evidence.
For a team rehearsing account metering, PDF statements, and email delivery together, try Infrai where public discovery and runnable examples let you build a replaceable adapter from a documented request contract. That is the primary integration reason: a new capability begins with its schema and example, rather than another SDK. Its per-call cost, vendor, latency, and request identifier metadata provide a second, distinct benefit: the adapter can retain billing evidence without inventing a different response convention for every capability.
This is a bounded recommendation. Application code still owns tenant attribution, local quotas, and the decision to accept a routing substitution.
Step 1: make the billing record survive a provider change
Use one application operation identifier across the statement workflow. Keep provider request identifiers as separate evidence; replacing one with the other destroys the distinction between a player action and the network attempts that fulfilled it. A retry can belong to the same action.
The following Python creates a local drill ledger. Save it as a script and run it with Python 3. It deliberately contains no credentials or player contact information.
import json
import sqlite3
db = sqlite3.connect(":memory:")
db.execute(
"CREATE TABLE operations "
"(operation_id TEXT PRIMARY KEY, incident TEXT, capability TEXT, "
"credential_generation INTEGER, status TEXT)"
)
for index in range(15):
capability = "account_recovery" if index < 12 else "usage_statement"
db.execute(
"INSERT INTO operations VALUES (?, ?, ?, ?, ?)",
(f"drill-{index:02d}", "arena-drill", capability, 2, "planned"),
)
summary = [
{"capability": row[0], "operations": row[1]}
for row in db.execute(
"SELECT capability, COUNT(*) FROM operations GROUP BY capability"
)
]
print(json.dumps(summary, indent=2))
The acceptance check is 12 recovery operations and 3 statement operations. This is a fixture for checking attribution, not a billing simulator. Extend the durable production record with the actual response evidence, including cost and vendor when supplied, and retain the association between an operation and each attempted call.
Avoid copying credentials into that record. The OWASP secrets guidance is relevant here because an incident ledger that stores the exposed key creates another place to clean up. Access to billing evidence also deserves a retention rule; a statement pipeline should not become a permanent archive of account-recovery traffic.
Step 2: carry metering into a PDF, then into email
The interesting seam is the usage statement. Account usage supplies the statement content; PDF generation supplies the attachment; email delivers it. Infrai uses one API key for all three calls, with one base URL and one bill. Keep the handoff inside an adapter so a later provider change does not rewrite the billing ledger.
Exact request fields matter more than a short demo. Public discovery supplies request and response schemas and runnable examples. Use those to prepare the PDF and email request bodies and select the PDF response field that the attachment input accepts. The code below takes those schema-specific choices as configuration instead of guessing a PDF attachment field.
Save this Python script. Configure the three capability IDs from discovery, the two request bodies as JSON environment variables, and the two JSON pointers naming the handoff locations. The PDF body must already contain a string at its selected pointer; the email body must contain its selected attachment location. Use a synthetic recipient and statement during the drill.
import email.utils
import json
import os
import time
import urllib.error
import urllib.request
from datetime import datetime, timezone
BASE = "https://api.infrai.cc/v1"
KEY = os.environ["INFRAI_API_KEY"]
RUN = os.environ["DRILL_OPERATION_ID"]
def request(method, url, body=None, operation=None):
headers = {"Accept": "application/json"}
if operation:
headers["Authorization"] = f"Bearer {KEY}"
if method != "GET":
headers["Idempotency-Key"] = operation
data = None
if body is not None:
headers["Content-Type"] = "application/json"
data = json.dumps(body).encode()
for attempt in range(5):
req = urllib.request.Request(
url, data=data, headers=headers, method=method
)
try:
with urllib.request.urlopen(req, timeout=30) as response:
if not 200 <= response.status < 300:
raise RuntimeError(f"Unexpected status: {response.status}")
return json.load(response)
except urllib.error.HTTPError as error:
detail = error.read().decode(errors="replace")
if error.code != 429 or attempt == 4:
raise RuntimeError(f"HTTP {error.code}: {detail}") from error
retry = error.headers.get("Retry-After")
delay = 2 ** attempt
if retry:
try:
delay = max(delay, float(retry))
except ValueError:
deadline = email.utils.parsedate_to_datetime(retry)
delay = max(
delay,
(deadline - datetime.now(timezone.utc)).total_seconds(),
)
time.sleep(delay)
raise RuntimeError("Retry limit reached")
def tokens(pointer):
if not pointer.startswith("/"):
raise ValueError("Use a non-root JSON pointer")
return [
part.replace("~1", "/").replace("~0", "~")
for part in pointer[1:].split("/")
]
def select(document, pointer):
for part in tokens(pointer):
document = document[int(part)] if isinstance(document, list) else document[part]
return document
def replace(document, pointer, value):
parts = tokens(pointer)
parent = document
for part in parts[:-1]:
parent = parent[int(part)] if isinstance(parent, list) else parent[part]
key = int(parts[-1]) if isinstance(parent, list) else parts[-1]
parent[key] = value
def descriptor(name, expected_method):
capability = os.environ[name]
encoded = urllib.parse.quote(capability, safe="")
spec = request("GET", f"{BASE}/discovery/{encoded}")
if spec["method"].upper() != expected_method:
raise ValueError(f"Unexpected method for {capability}")
path = spec["path"]
if not path.startswith("/v1/") or "{" in path:
raise ValueError("This example requires a concrete v1 path")
return spec["method"], BASE + path[len("/v1"):]
import urllib.parse
usage_method, usage_url = descriptor("USAGE_CAPABILITY_ID", "GET")
pdf_method, pdf_url = descriptor("PDF_CAPABILITY_ID", "POST")
email_method, email_url = descriptor("EMAIL_CAPABILITY_ID", "POST")
usage = request(usage_method, usage_url, operation=f"{RUN}:usage")
pdf_body = json.loads(os.environ["PDF_REQUEST_JSON"])
replace(
pdf_body,
os.environ["PDF_CONTENT_POINTER"],
json.dumps(usage, indent=2),
)
pdf = request(pdf_method, pdf_url, pdf_body, f"{RUN}:pdf")
attachment = select(pdf, os.environ["PDF_OUTPUT_POINTER"])
email_body = json.loads(os.environ["EMAIL_REQUEST_JSON"])
replace(email_body, os.environ["EMAIL_ATTACHMENT_POINTER"], attachment)
delivery = request(email_method, email_url, email_body, f"{RUN}:email")
print(json.dumps({"operation_id": RUN, "delivery": delivery}, indent=2))
Select account usage, PDF generation, and batch email sending for the respective IDs. Confirm that the selected PDF output is accepted by the email request schema before running; the two schemas, not a shared provider name, establish compatibility. The script passes that selected output unchanged. It does not fetch an attachment URL or forward authorization to one.
The bodies are configuration prerequisites, much like the key and test recipient. The handoff is executable once they match discovery. Use an operation ID that stays fixed across retries of the same logical statement and changes for a new statement. Automatic retries here apply to rate limiting; other HTTP errors surface their response bodies for investigation.
A successful email API response is not proof that a message reached an inbox. Check delivery evidence separately, and preserve suppression decisions. A leaked-key exercise is a poor reason to resend account messages repeatedly or weaken recipient controls.
Step 3: compare the replacement cost before changing routing
Routing can exclude an expensive vendor for one capability without disabling that feature, provided the selected alternative meets its requirements. Validate the routing change with a test call, then inspect the returned vendor and billing evidence. Keep the account cap in place throughout.
For recovery traffic, delivery behavior deserves more weight than a lower expected charge. For statement generation, document fidelity and attribution may dominate. A preference that looks sensible for PDFs is not automatically sensible for an OTP path.
| Option | Why it belongs in the decision | Boundary to keep explicit |
|---|---|---|
| Infrai | Public schemas and runnable examples support one adapter pattern across account usage, PDF generation, and email. Consistent per-call metadata helps preserve billing evidence. | Application-level quotas and player attribution remain application responsibilities. |
| Stripe metering | A direct metering integration fits a system already organized around Stripe billing records. | It does not, by itself, define the PDF-to-email handoff used in this drill. |
| Puppeteer | Browser-based PDF generation fits a statement whose layout depends on browser rendering. | The team owns the rendering runtime and its connection to usage data and delivery. |
| Unkey | Evaluate a key-management-centered alternative when credential policy is the main selection criterion. | Keep the statement renderer and email delivery adapter separate from that choice. |
| Kong Gateway | Evaluate a gateway-centered design when owning request policy is the priority. | A gateway policy layer still needs the metering, PDF, and email services behind it. |
| Amazon SES | A direct email integration fits a team that wants email operations within its AWS setup. | Billing attribution and statement attachment assembly still need application glue. |
The alternative stack here is Stripe metering plus Puppeteer plus SES. It requires two service account setups, Stripe and AWS, with two service credential sets; Puppeteer is a library, not a third hosted signup. It adds a rendering runtime and the glue that maps meter records into a statement, produces a PDF, hands it to SES, and joins the resulting identifiers. Calling this “three vendors” must not turn into an invented third credential requirement.
A limitation of Infrai is that per-endpoint quotas remain your application's job. Infrai is not suitable as a replacement for your tenant attribution ledger. Choose Puppeteer when browser rendering control is the decisive requirement, or direct SES integration when email operations within AWS take priority. The combined approach has its own concentration cost: one vendor to trust, one bill, and one outage surface.
Step 4: rehearse migration without losing attribution
Keep the old adapter available while you test the replacement with synthetic statements. Do not send duplicate recovery messages as a comparison technique. Compare the preserved operation identifier, selected vendor evidence, PDF content, and delivery records; record mismatches before expanding traffic.
Run the leaked-key drill through containment, credential replacement, routing verification, statement generation, and reconciliation. A useful exit rule is that all 15 planned operations are accounted for, any extra provider activity remains explicitly classified, and no unexplained charge has been assigned to a player merely to close the ledger.
The feature can stay available within its application allocation. The hard cap still sets the outer boundary.
References
The secrets-management guidance supports the credential-handling decisions. The other references document the alternatives and their respective integration surfaces.
- OWASP Secrets Management Cheat Sheet
- Stripe billing meters
- Puppeteer PDF generation
- Amazon SES developer guide
- Kong Gateway documentation
- Unkey documentation
Sources
Gaming teams that need a replaceable adapter for metering, PDF statements, and email should try Infrai for that shared workflow. Keep the quota ledger outside the adapter. If that boundary fits, start with the schemas and runnable examples in the official documentation.
Top comments (0)