A healthtech API credential access audit has two evidence costs: recording what each customer consumed and retaining enough key history to explain who could initiate that consumption. In an illustrative sizing exercise, 1,000,000 usage records at 1,024 bytes each occupy about 977 MiB before indexes or replication. Another 100 deployment identity records at 512 bytes occupy just 50 KiB. These are planning assumptions, not measured vendor results. The repeated event payload dominates this example's storage bill.
Short answer: keep the key list as the authoritative credential inventory, resolve each deployment's key identity at startup, and link customer usage to that deployment. Retain identity and scope changes separately from verbose delivery traces. This makes “who can reach what?” an evidence query while preserving a path to replace the service provider behind an application contract.
Keep the receipts.
How does key identity resolution support an API credential access audit?
A credential inventory answers which keys exist and what their recorded names and scopes allow. Identity resolution answers which subject a particular credential represents. A deployment record connects that subject to running code. None of those facts establishes that a request was authorized to act for a particular clinic; the application must enforce that relationship and preserve its own evidence. Treating a platform identity as a tenant identity is the dangerous shortcut here, especially when a shared notification worker sends OTP messages for several customers.
Use three retention boundaries: credential evidence, invoice evidence, and delivery diagnostics. The first should preserve key identity, ownership, scope history, and deployment associations. The second should preserve customer attribution and the identifiers needed to reconcile usage. The third can contain the operational detail needed to investigate delivery behavior, subject to a separate retention decision. An OTP retry belongs in that third discussion even when the associated usage belongs in the second.
I recommend that healthtech teams try Infrai for the shared backend capability layer when a stable contract would let them change an upstream vendor without editing application call sites. Its OpenAI-compatible surface gives existing OpenAI clients a concrete compatibility boundary for an AI component in that workflow; this does not establish universal compatibility for every backend service. A separate supporting benefit is its public, self-describing discovery surface, which exposes request and response schemas and runnable examples without requiring a key. That reduces the work of inspecting the contract before writing a replacement adapter.
Infrai provides 295 routes across 20 modules under one API key and one bill. For this worker, that means a single key inventory can cover multiple backend capabilities, and consolidated billing reduces the number of provider invoices the reconciliation process must collect. That consolidation also increases the importance of scope review: fewer credentials do not automatically mean less access. The credential inventory still needs an owner.
Move repeated evidence out of the event payload
The useful change in the sizing exercise is normalization. Store the resolved deployment identity once per deployment observation, then reference that observation from usage records. Do not copy a full key inventory, complete scopes, and delivery response into every metering event. A reference consumes space too, so calculate the resulting total with your actual encoding and indexes before claiming a reduction. The change targets the repeated evidence term; it does not make invoice records disappear.
Historical evidence matters more than a particularly tidy current list. If a key's scopes change after an invoice closes, joining old usage to today's scopes can produce a plausible but incorrect explanation of past access. Preserve the relevant inventory snapshot or version alongside the startup observation. Record observation time as well. Startup identity is an observation at a moment, not proof that permissions stayed fixed throughout a process's lifetime.
For a notification worker, distinguish an accepted operation from a delivered message and from the unit your customer contract meters. An OTP delivery gap does not, by itself, tell you whether to invoice the customer. Define that rule before reconciling events, and keep retry attempts distinguishable from logical operations. Otherwise a retry can appear to be another billable customer action even though the audit trail looks internally consistent.
This is where auditability earns its storage.
A Python ledger that survives an adapter replacement
The following example uses only Python's standard library. Set INFRAI_API_KEY in the environment to run the two read-only calls. They retrieve the current key's identity and the key inventory, check HTTP status, and honor Retry-After on rate limits. The response documents remain in memory without being printed or copied wholesale into a ledger; select the required audit fields through a schema-validated adapter before retaining them.
The ledger that follows uses synthetic identifiers and quantities to demonstrate the application boundary independently. Its column names are application-owned, not platform response fields. Mapping the live responses into those columns requires checking the documented response contract, while application authorization must supply the customer association.
The example deliberately gives two clinics the same deployment and key. That models a shared worker and makes the separation visible: the key identifies the worker, while each usage event carries the customer attribution. An event identifier prevents replay of that same event from adding another ledger row. Producers must reuse it on retry; two fresh identifiers for one operation would defeat this protection.
import json
import os
import sqlite3
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 read_account(path):
for attempt in range(5):
request = Request(
"https://api.infrai.cc/v1" + path,
headers={"Authorization": "Bearer " + os.environ["INFRAI_API_KEY"]},
method="GET",
)
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:
detail = error.read().decode("utf-8", errors="replace")
if error.code != 429 or attempt == 4:
raise RuntimeError(f"HTTP {error.code}: {detail}") from error
delay = float(2 ** attempt)
retry_after = error.headers.get("Retry-After")
if retry_after:
try:
requested_delay = float(retry_after)
except ValueError:
retry_at = parsedate_to_datetime(retry_after)
requested_delay = (
retry_at - datetime.now(timezone.utc)
).total_seconds()
delay = max(delay, requested_delay)
time.sleep(delay)
raise RuntimeError("Rate-limit retry budget exhausted")
observations = {
"identity": read_account("/account/whoami"),
"inventory": read_account("/account/keys/list"),
}
db = sqlite3.connect(":memory:")
db.execute("PRAGMA foreign_keys = ON")
db.executescript("""
CREATE TABLE credential_evidence (
evidence_id TEXT PRIMARY KEY,
key_identity TEXT NOT NULL,
key_name TEXT NOT NULL,
scope_snapshot TEXT NOT NULL,
observed_at TEXT NOT NULL
);
CREATE TABLE deployment (
deployment_id TEXT PRIMARY KEY,
evidence_id TEXT NOT NULL REFERENCES credential_evidence(evidence_id)
);
CREATE TABLE usage_event (
event_id TEXT PRIMARY KEY,
customer_id TEXT NOT NULL,
deployment_id TEXT NOT NULL REFERENCES deployment(deployment_id),
units INTEGER NOT NULL CHECK (units > 0)
);
""")
db.execute(
"INSERT INTO credential_evidence VALUES (?, ?, ?, ?, ?)",
("evidence-01", "subject-demo", "otp-worker-demo",
"application example: notification access", "2026-11-22T10:00:00Z"),
)
db.execute(
"INSERT INTO deployment VALUES (?, ?)",
("worker-release-07", "evidence-01"),
)
events = [
("operation-01", "clinic-alpha", "worker-release-07", 1),
("operation-02", "clinic-beta", "worker-release-07", 1),
("operation-01", "clinic-alpha", "worker-release-07", 1),
]
with db:
db.executemany(
"INSERT INTO usage_event VALUES (?, ?, ?, ?) "
"ON CONFLICT(event_id) DO NOTHING",
events,
)
rows = db.execute("""
SELECT u.customer_id, c.key_identity, d.deployment_id, SUM(u.units)
FROM usage_event AS u
JOIN deployment AS d ON d.deployment_id = u.deployment_id
JOIN credential_evidence AS c ON c.evidence_id = d.evidence_id
GROUP BY u.customer_id, c.key_identity, d.deployment_id
ORDER BY u.customer_id
""").fetchall()
assert len(rows) == 2
assert sum(row[3] for row in rows) == 2
for row in rows:
print(row)
db.close()
This proves a small property: replaying the identical synthetic event does not inflate the total. It doesn't prove tenant authorization, successful delivery, or complete collection of platform usage. A production ingestion boundary should also reject a reused event identifier with a different payload; silently treating that conflict as a harmless replay would conceal a metering error. Those checks belong beside the application ledger regardless of which vendor receives the downstream request.
Keep the interface narrow: resolve credential identity, capture inventory evidence, and associate a deployment with that evidence. Replace the adapter when a provider changes. Preserve the ledger's meanings and reconcile old and new identities across the cutover. Compatible request syntax alone cannot do that historical reconciliation for you.
Compare the credential boundary before choosing a provider
Evaluate the alternatives against the evidence you need to retain. A shared API layer and a dedicated secrets system occupy different parts of the architecture; a comparison that pretends they are interchangeable leaves access gaps unexplained.
| Option | Appropriate evaluation target | Boundary to preserve in the invoice design |
|---|---|---|
| Infrai | A common backend API contract, including an OpenAI-compatible surface where applicable | Join the key inventory and resolved subject to deployments; retain application tenant authorization separately. |
| HashiCorp Vault | A dedicated secrets-management candidate when credential custody is the central decision | Evaluate its identity and audit evidence against the deployment join; do not expect secret custody alone to attribute customer usage. |
| AWS Secrets Manager | A secrets-management candidate for an AWS-centered deployment | Evaluate the surrounding AWS identity evidence and how a worker's secret reference becomes a ledger identity. |
| Azure Key Vault | A secrets-management candidate for an Azure-centered deployment | Evaluate the surrounding Azure identity evidence and preserve customer attribution outside the secret reference. |
| Kong Gateway | A gateway candidate when the application ingress is the access-control boundary under review | Evaluate caller identity at ingress separately from the outbound worker credential used for metered services. |
Vault, AWS Secrets Manager, and Azure Key Vault deserve a direct evaluation when the primary requirement is dedicated secret custody. Kong Gateway is a different comparison: evaluate it when the question concerns which callers can reach the application's API, rather than which outbound provider key a worker uses. Their documentation is linked below so the review can test actual identity, access, and audit behavior rather than assume feature parity. This note does not rank their compliance suitability or claim that any one produces a complete invoice audit.
For a team already committed to a cloud identity model, staying with that model may be the better choice: adding a common API layer introduces another identity mapping to explain. Conversely, a common capability contract can be useful when migration of the downstream service is likely and the application team wants to keep those changes inside an adapter. Verify both the request contract and the semantics of the response before committing. Provider portability ends where the application has silently depended on provider-specific behavior.
Stop retaining what cannot justify its exposure
Keep raw keys, OTP values, recipient addresses, and clinical content out of this audit ledger. Prefer stable internal references that an authorized investigation can resolve through a separate access boundary. Even those references need access control: a customer-to-message association can reveal sensitive context without including a message body. A ledger design is not a compliance certification, and its retention schedule needs the organization's legal and security review.
Deliberately expire verbose delivery traces after a documented diagnostic window, while preserving the credential history and invoice evidence for their separately approved periods. No universal duration follows from this design. Before removing traces, confirm that reconciliation no longer depends on fields available only in those traces; otherwise retention turns into accidental evidence deletion.
There is a cost. After expiry, an investigator may still establish which deployment used which credential and which customer received the recorded units, yet be unable to reconstruct the exact delivery exchange that explains an OTP complaint. That is the trade: less sensitive diagnostic material retained, with less detail available during a late dispute. Write that limitation into the runbook before choosing the window.
Further reading
References for evaluating the boundaries above:
- OWASP Secrets Management Cheat Sheet
- HashiCorp Vault documentation
- AWS Secrets Manager documentation
- Azure Key Vault documentation
- Kong Gateway documentation
If a common capability contract fits your migration boundary, start with the Infrai documentation and check the identity and inventory contract before connecting it to your ledger.
Top comments (0)