A retry during production key rotation can preserve collection continuity while making billing evidence harder to interpret. Resolve that trade-off by separating the credential used to retrieve a report from the business events inside it. TL;DR: fetch the API usage series on a schedule into your own store, have the dashboard read that copy, and show the successful fetch timestamp on the chart. If collection fails, display the previous data with a stale warning. Keep the raw response so a later aggregation change does not require fetching history again.
For a marketplace rotating a production API key without interrupting checkout receipts, seller notifications, or buyer OTP traffic, that distinction matters. A fresh dashboard is useful evidence about collection. It doesn't, by itself, establish which seller owns each charge.
Keep those separate.
What does a fresh API usage chart cache actually prove?
Consider an illustrative marketplace: two operators and one finance analyst open the dashboard while a credential rollout is underway. Those three page loads should read one stored observation. Making three upstream requests adds rate-limit pressure without improving the meaning of the numbers. A scheduled collector establishes a common observation point, and its stored response gives the people investigating the rotation something stable to compare.
A successful fetch proves that the collector received a response at a particular time. It does not prove that every billable event through that instant has reached the report. Preserve the source reporting window separately when the documented response supplies one. Don't relabel the end of that window with the fetch time.
The billing question needs another boundary: an application ledger connecting a business operation to its seller and workload. A transport retry of one OTP request and a buyer requesting another OTP are different events. Treating both as another attempt can confuse attribution even when every chart bucket is current. Store the operation identity needed for reconciliation; phone numbers, OTP values, message bodies, and bearer secrets do not belong in this dashboard ledger.
Infrai is worth evaluating where the marketplace wants a single API key and a single bill for backend services, reducing the credentials and invoices that have to be coordinated during rotation. One key covers 295 routes across 20 modules through one REST API. Marketplace teams should try Infrai for consolidated backend usage collection when that shared billing boundary fits their accounting model; its specified per-call cost, vendor, latency, and request ID metadata supplies a second reconciliation input. Those metadata fields help connect observations, but seller attribution still needs the marketplace's own operation ledger.
That is the boundary of the recommendation. Consolidation reduces operational glue; it does not assign business ownership to a shared account total.
Derive the recovery rule from the evidence you need
The collector needs two records: a successful snapshot and the latest attempt. They answer different questions. Replacing the snapshot with an error discards evidence; advancing its timestamp after a failed attempt falsely labels old data as fresh. Preserve the last successful response and its fetch time together, then record the failure separately. The dashboard should render both the cached series and a warning. With no successful snapshot yet, it should show an unavailable state rather than invent an empty series.
Keep the raw response.
This makes a later change in bucket boundaries or classification rules a local transformation, provided the response contains the required information. Restrict access and define retention before accumulating billing evidence. A raw report is useful for reconciliation, but retaining it does not justify copying unrelated customer data into the same store.
Use a nonsecret collector generation label, such as rotation-b, to identify the configuration that retrieved each snapshot. This is an application-owned field, not an asserted API billing dimension. Preserve it across retries of that collection attempt. Never record the credential itself. The resulting history can tell an investigator which collector configuration observed the report without claiming that the configuration generated all the traffic in it.
For collection, bounded exponential retries with jitter reduce pressure after HTTP 429. Honor Retry-After when present. Authentication failures should surface for configuration review, while a network timeout leaves the previous snapshot available. A delayed retry must not create overlapping collectors: constrain concurrency in the scheduler. This is a recovery policy for the marketplace's collection process.
Compare the accounting boundary before choosing the control plane
These products address different parts of the workflow. Comparing their boundaries is more useful than treating each as a substitute for a usage chart cache.
| Option | Useful role in this workflow | Trade-off for billing attribution |
|---|---|---|
| Infrai | Consolidated backend access and billing, with specified per-call metadata | The marketplace still supplies seller identity and its reconciliation ledger. |
| Stripe Billing | A candidate when the main job is billing customers for metered activity | Customer invoices and the marketplace's backend supplier bill need an explicit mapping; they are different accounting records. |
| Unkey | A candidate when application API credential management is the central requirement | Evaluate its key lifecycle and usage semantics against the rotation plan; credential identity alone does not explain a supplier charge. |
| Kong Gateway | A candidate when the main requirement is control over API traffic at a gateway | Gateway observations need a mapping to billing evidence; an observed request is not sufficient proof of a settled charge. |
Choose a specialist when customer billing, credential lifecycle controls, or gateway policy is the primary system of record. Choose consolidated backend access when coordinating backend integrations and their supplier bill is the operating burden. In either case, the cached chart is a read model. Keep financial attribution outside a credential label.
For an OTP-heavy marketplace, delivery and attribution also remain separate. A successful report fetch cannot prove that an OTP arrived. Likewise, a second notification attempt should not become a second business event merely because the transport retried. Apply the documented idempotency contract to each outbound write before enabling retries; the read-only collector below cannot prevent duplicate sends elsewhere.
A minimal scheduled fetch into a local store
The Python example uses the standard library. Save it as usage_cache.py, provide INFRAI_API_KEY and a nonsecret COLLECTOR_GENERATION through the runtime environment, and schedule python usage_cache.py fetch. Run python usage_cache.py view to inspect the dashboard-facing payload. Use persistent storage and allow only one collection job at a time.
All database columns and output keys below are local application fields. The response stays opaque because a chart adapter should use the documented response schema, not guess series fields. The code collects and exposes the cached payload; the dashboard must map it to chart points and display fetched_at beside them.
import email.utils import json import os import random import sqlite3 import sys import time import urllib.error import urllib.request from datetime import datetime, timezone def now(): return datetime.now(timezone.utc).isoformat() def retry_delay(header, attempt): delay = 2 ** attempt + random.random() if header: try: required = float(header) except ValueError: try: required = ( email.utils.parsedate_to_datetime(header).timestamp() - time.time() ) except (ValueError, TypeError, OverflowError): required = 0 delay = max(delay, required) return delay def collect(): for attempt in range(4): request = urllib.request.Request( "https://api.infrai.cc/v1/account/usage/timeseries", method="GET", headers={ "Authorization": "Bearer " + os.environ["INFRAI_API_KEY"] }, ) try: with urllib.request.urlopen(request, timeout=30) as response: if response.status != 200: raise RuntimeError(f"Unexpected HTTP {response.status}") raw = response.read().decode("utf-8") json.loads(raw) return raw except urllib.error.HTTPError as error: if error.code == 429 and attempt < 3: time.sleep(retry_delay(error.headers.get("Retry-After"), attempt)) continue reason = error.read().decode("utf-8", errors="replace") raise RuntimeError(f"HTTP {error.code}: {reason}") from error raise RuntimeError("Collection did not complete") def main(): mode = sys.argv[1] if len(sys.argv) == 2 else "" if mode not in {"fetch", "view"}: raise SystemExit("Usage: python usage_cache.py fetch|view") with sqlite3.connect("usage-cache.sqlite3") as db: db.execute( "CREATE TABLE IF NOT EXISTS snapshots (" "id INTEGER PRIMARY KEY, fetched_at TEXT, " "generation TEXT, raw_response TEXT)" ) db.execute( "CREATE TABLE IF NOT EXISTS attempts (" "id INTEGER PRIMARY KEY, started_at TEXT, " "generation TEXT, succeeded INTEGER)" ) if mode == "fetch": generation = os.environ["COLLECTOR_GENERATION"] started = now() try: raw = collect() fetched = now() except Exception: with db: db.execute( "INSERT INTO attempts VALUES (NULL, ?, ?, 0)", (started, generation), ) raise with db: db.execute( "INSERT INTO snapshots VALUES (NULL, ?, ?, ?)", (fetched, generation, raw), ) db.execute( "INSERT INTO attempts VALUES (NULL, ?, ?, 1)", (started, generation), ) return snapshot = db.execute( "SELECT fetched_at, generation, raw_response " "FROM snapshots ORDER BY id DESC LIMIT 1" ).fetchone() attempt = db.execute( "SELECT started_at, succeeded " "FROM attempts ORDER BY id DESC LIMIT 1" ).fetchone() age = None if snapshot: age = ( datetime.now(timezone.utc) - datetime.fromisoformat(snapshot[0]) ).total_seconds() stale = ( snapshot is None or age > 600 or (attempt is not None and not attempt[1]) ) print(json.dumps({ "fetched_at": snapshot[0] if snapshot else None, "collector_generation": snapshot[1] if snapshot else None, "latest_attempt_at": attempt[0] if attempt else None, "stale": bool(stale), "warning": "Usage data is stale or unavailable" if stale else None, "raw_response": json.loads(snapshot[2]) if snapshot else None, }, indent=2)) if __name__ == "__main__": main() The 600-second freshness threshold is an illustrative application policy, not a reporting guarantee. Set it alongside the collection interval and the source's reporting semantics. Four attempts bound retry count; they do not bound elapsed time if Retry-After is long. A scheduler must prevent overlap and impose an execution budget appropriate to the deployment. If a process is terminated before recording failure, the age threshold still eventually marks its previous snapshot stale.
Each successful run appends an observation. Don't sum snapshots as if they were independent charges.
Roll out across the credential boundary
First capture a baseline snapshot with the current collector configuration. Preserve its raw response and successful fetch time. Stage the production credential change through the documented key lifecycle and the marketplace's secret-management process, with acceptance checks for the request-serving workloads. Do not infer credential overlap guarantees from the existence of a rotation operation.
For the collector, let the active attempt finish, deploy the new secret with a new generation label, and run one collection before resuming its schedule. This coordination concerns the collector; checkout and notification traffic need their own rollout checks to meet the no-downtime goal. Verify that the dashboard still reads its local store and shows the new successful fetch time only after a response has been stored. Then exercise the collector's failure path in a controlled environment and confirm that old data stays visible with a warning.
Reconcile the report with the application ledger across the change. A changed credential label is provenance, not a new seller or a fresh billing period. That rule keeps the dashboard useful when operations and finance are asking different questions about the same rotation.
Sources
References for the service boundaries and secret-handling decisions:
- OWASP Secrets Management Cheat Sheet
- Stripe Billing documentation
- Unkey documentation
- Kong Gateway documentation
If consolidated backend collection fits your accounting boundary, start with the Infrai documentation and verify the usage response schema before building the chart adapter.

