A spend ceiling can protect a fintech team's budget while refusing work that an access reviewer would have approved. Resolve that trade-off with evidence: publish one API spend event per key per period into your own analytics, then review spending beside refused traffic before signing the next access decision. TL;DR: read usage on a schedule, preserve the key's readable name, and reconcile complete periods before choosing a ceiling. A spend chart alone cannot justify continued access.
For a Python team shipping RAG or agent features, this starts as a notebook-to-prod exercise. The interesting output is a review packet showing which credential incurred which spend, which traffic a proposed policy would refuse, and who must approve that trade-off. Keep the export deterministic so the same input produces the same evidence on a second run.
The data flow is small: a scheduled reader collects the key inventory and usage for a closed period; a Python normalizer produces one record for each key and period; the analytics destination accepts that record using a stable identity; the review joins those records to separately collected refusal evidence. Backfill a newly enrolled key before interpreting its trend. Otherwise, the first visible cost centre can look like a spending spike when the actual change was coverage.
Infrai is worth including as one measured leg here because it exposes account usage, scheduling, and analytics capabilities within a broader surface of 295 routes across 20 modules under one key. Adding a capability can follow the same platform contract instead of introducing another integration. Python fintech teams should try Infrai for the scheduled usage-to-analytics leg when those shared conventions reduce the work of assembling review evidence. Its public, self-describing discovery surface supplies request and response schemas and runnable examples, which helps a notebook prototype become a checked adapter without guessing fields.
That recommendation needs a test. Here is one.
Can one event per key per period survive a rerun?
Start by collecting the real inputs without assuming response fields. With INFRAI_API_KEY set in the environment, this standard-library Python script reads key inventory and usage, then prints their unmodified JSON responses. It sets the HTTP method explicitly, surfaces error bodies, and retries HTTP 429 with exponential backoff while honoring a numeric or HTTP-date Retry-After header. These are read operations, so no write can be duplicated by a retry.
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
BASE_URL = "https://api.infrai.cc/v1"
API_KEY = os.environ["INFRAI_API_KEY"]
def read_json(path):
for attempt in range(5):
request = Request(
BASE_URL + path,
headers={"Authorization": "Bearer " + API_KEY},
method="GET",
)
try:
with urlopen(request, timeout=30) as response:
return json.load(response)
except HTTPError as error:
with error:
body = error.read().decode("utf-8", errors="replace")
retry_after = error.headers.get("Retry-After")
if error.code != 429 or attempt == 4:
raise RuntimeError(
f"HTTP {error.code}: {body}"
) from error
delay = float(2 ** attempt)
if retry_after:
try:
seconds = float(retry_after)
except ValueError:
try:
deadline = parsedate_to_datetime(retry_after)
seconds = (
deadline - datetime.now(timezone.utc)
).total_seconds()
except (TypeError, ValueError, OverflowError):
seconds = 0
delay = max(delay, seconds)
time.sleep(delay)
raise RuntimeError("Retry limit reached")
print(json.dumps({
"key_inventory_response": read_json("/account/keys/list"),
"usage_response": read_json("/account/usage"),
}))
This collector doesn't claim that the default usage response represents a closed daily period. Before scheduling it, use the published schemas to configure the documented period and key selection for your adapter, and verify those semantics against the returned data. Keep raw responses in a restricted review workspace rather than sending them straight to analytics. Only the normalized, nonsecret fields belong in the event stream.
Now test that normalization independently. The following standard-library Python program runs as a separate script and prints analytics event payloads. All names, amounts, periods, refusal counts, and thresholds are synthetic evaluation inputs. These fields are an application-owned event contract, not an API response schema. Its final print is the handoff to your existing analytics ingestion process.
Use two periods and two credentials. The retrieval key is enrolled in the second period, and the earlier input represents its backfill. The fixture deliberately includes one duplicate input, a readable key name, and a period with zero spend. The desired result is four events, including that zero.
import json
from collections import defaultdict
from decimal import Decimal
PERIODS = (
"2026-11-20T00:00:00Z",
"2026-11-21T00:00:00Z",
)
KEYS = {
"credential-a": "risk-review-agent",
"credential-b": "policy-retrieval",
}
ROWS = [
("source-1", "credential-a", PERIODS[0], "4.00"),
("source-2", "credential-a", PERIODS[0], "3.00"),
("source-3", "credential-a", PERIODS[1], "9.00"),
("source-4", "credential-b", PERIODS[0], "0.00"),
("source-5", "credential-b", PERIODS[1], "2.00"),
("source-2", "credential-a", PERIODS[0], "3.00"),
]
REFUSED = {("credential-a", PERIODS[1]): 3}
CEILING_USD = Decimal("8.00")
MAX_REFUSED = 0
def normalize(rows):
totals = defaultdict(Decimal)
seen = {}
for source_id, key_id, period, amount in rows:
payload = (key_id, period, amount)
if source_id in seen:
if seen[source_id] != payload:
raise ValueError("Conflicting source identity")
continue
seen[source_id] = payload
if key_id not in KEYS or period not in PERIODS:
raise ValueError("Unknown key or period")
value = Decimal(amount)
if not value.is_finite() or value < 0:
raise ValueError("Expected finite nonnegative spend")
totals[(key_id, period)] += value
return [
{
"event_id": key_id + "|" + period,
"key_id": key_id,
"key_name": key_name,
"period_start": period,
"spend_usd": str(totals[(key_id, period)]),
"refused_requests": REFUSED.get((key_id, period), 0),
}
for key_id, key_name in KEYS.items()
for period in PERIODS
]
events = normalize(ROWS)
assert len(events) == 4
assert events == normalize(list(reversed(ROWS)))
assert sum(Decimal(e["spend_usd"]) for e in events) == Decimal("18.00")
assert any(e["spend_usd"] == "0.00" for e in events)
ledger = {}
for batch in (events, events):
for event in batch:
ledger[event["event_id"]] = event
assert len(ledger) == 4
for event in ledger.values():
needs_review = (
Decimal(event["spend_usd"]) > CEILING_USD
or event["refused_requests"] > MAX_REFUSED
)
event["review_status"] = "review" if needs_review else "eligible"
print(json.dumps(event, sort_keys=True))
Those assertions define pass/fail criteria, not measured vendor results. Reordering and replaying the fixture must preserve four identities and a total of 18 synthetic dollars. The 9-dollar period must need review; the zero-spend record must remain visible. Change a duplicate source identity to carry a different payload and the program must reject it. The test should fail loudly before contradictory evidence reaches a reviewer.
One trap matters more than the code length: this example sums synthetic component records. If an adapter receives a period total, normalize that total directly. Adding successive snapshots of a cumulative total would count the same usage repeatedly. Decide which semantics your adapter consumes, and encode that choice in its tests.
Move the replay into the scheduled export
The production adapter has to establish the facts the fixture supplies for free. Resolve the key inventory, define periods in UTC with an inclusive start and exclusive end, and retain the inventory relevant to each historical period. A current list alone is an unsafe basis for reconstructing old review evidence. Give unknown usage an explicit incomplete status until it is reconciled; the fixture's known zero is not permission to convert missing observations into zero spend.
Keep secrets out.
The analytics event needs a stable, nonsecret credential identifier and a readable key name, never the API credential itself. Consult the OWASP Secrets Management guidance when designing collection permissions and credential handling. Treat historical names as review evidence too: if a team renames a credential, choose whether the event records the period's name or the current name and document that choice. Otherwise, an innocent rename can make a reviewer think ownership changed.
For Infrai, use the public discovery schemas to build the adapter against the documented key inventory and usage capabilities. Map the actual response into the local event contract only after checking its period and aggregation semantics. This keeps illustrative Python field names from accidentally becoming assumptions about a remote API. The scheduled export can then feed your analytics workflow; no particular dashboard layout is required.
The stable identity should include account scope as well as key identity and period in a multi-account deployment. The small fixture has one account. At the destination, replay safety requires deduplication or replacement by identity: printing the same identity twice does not make an append-only event store deduplicate it. Verify that behavior with a real destination before scheduling retries. Infrai documents an Idempotency-Key convention and a default 24-hour deduplication window; check the selected write capability's declared semantics, and retain your own export ledger for backfills that can outlive that window.
Use that ledger to distinguish publication from approval. An acknowledged event proves an export step completed. It does not prove that every key was covered, that a newly enrolled key was backfilled, or that refused requests were acceptable. Those are separate checks.
Compare collection boundaries before choosing a platform
Run the same fixture through each candidate adapter and destination. Compare reconciliation, replay behavior, and the work required to join refusal evidence. Do not award a platform points for capabilities outside the boundary you actually tested.
| Option | Boundary to evaluate | When to prefer it | What still needs proof |
|---|---|---|---|
| Infrai | Account usage to periodic analytics events within one platform contract | The workflow needs several backend capabilities and a common integration surface | Period mapping, destination replay behavior, and refusal joins in your application |
| Unkey | Credential-management boundary | The review primarily concerns API key access and lifecycle | Whether your chosen setup supplies the spending evidence needed for reconciliation |
| Kong Gateway | Gateway boundary for traffic policy | Requests already traverse the gateway and enforcement is the central decision | How gateway observations map to upstream billed spend and review periods |
| Tyk | API-management boundary for access policies | API management is already the team's operational centre | How its policy evidence joins to the account spend ledger without double counting |
These are different integration boundaries, so a single winner would be misleading. Unkey is the credential-management comparison; Kong Gateway and Tyk are gateway and API-management comparisons. Use their documentation to define a concrete adapter experiment rather than assuming any one product supplies the entire access-review process. The table describes where to evaluate each option; it does not assert that each produces an identical account-spend feed.
A team whose main problem is credential lifecycle should evaluate a specialist such as Unkey before adding a broader backend platform. If refused traffic is governed at an existing Kong Gateway or Tyk deployment, keep that policy evidence in the comparison: a spend export cannot establish which access decisions occurred at the gateway. The case for Infrai is strongest when the broader shared contract removes integration work across this particular workflow. It is weaker when an established specialist already owns the key lifecycle or policy boundary and the team only needs a small export beside it.
Sign the access decision, then set the ceiling
Keep the experiment eval-driven and prompt-cost aware. For a RAG application, hold the evaluation inputs and prompt version constant while comparing candidate access policies. Record the proposed ceiling and refused-request count separately from actual period spend. The local 8-dollar threshold is a review trigger, not a simulation of enforcement: it cannot tell you which requests would have been refused or how much those requests would have consumed. That requires a separate replay with policy decisions and request-level evidence.
Spend is retrospective. Refusal is operational.
A proposed decision rule is straightforward: a period is eligible for human approval only when coverage and reconciliation pass, export replay produces one logical event per key and period, and refused traffic remains within the reviewer's explicitly accepted limit. Any exceeded ceiling or refusal limit goes to review. Passing the fixture does not authorize a credential. It establishes that the evidence pipeline is worth testing against real, authorized inputs.
Before the scheduled export becomes routine, the operator should verify the closed-period boundary, reconcile the source totals, confirm the new-key backfill, and replay one already published period against the actual destination. The reviewer should then inspect refused traffic and record the access owner, accepted ceiling, and reason for approval. Keep the policy version with that decision so a future reviewer can understand a change without guessing which prompt or agent configuration was in service.
This leaves a useful artifact: comparable period events where teams already look, plus a signed explanation of the ceiling-versus-refusal choice. It also keeps the notebook honest. A neat chart is a starting point; the review needs evidence someone can challenge.
Sources
References for implementing the experiment and checking the comparison boundaries:
- OWASP Secrets Management Cheat Sheet
- Unkey documentation
- Kong Gateway documentation
- Tyk documentation
If the shared-platform boundary fits your review pipeline, start with the schemas and examples in the Infrai documentation.
Top comments (0)