Keep the standby API credential under a second secret-store name, and read the active slot from runtime configuration. That makes switching keys a configuration change. For a customer-support assistant with a prepaid balance, keep spending authorization separate: a working standby key should not authorize traffic that the spending policy would refuse.
Short answer: select credentials at runtime, verify the standby with a scheduled identity read, and log the selected slot. Evaluate those three checks alongside the balance decision before moving a notebook experiment into production. A successful credential switch alone is an incomplete acceptance test for this support workflow.
This experiment note defines an acceptance contract, not a production benchmark. The constraint is explicit: switching credentials must preserve the decision to refuse traffic when the balance reserve or spending ceiling would be crossed. No latency or availability measurements are claimed here.
How should runtime API credential selection preserve the support spending ceiling?
Two questions arrive together during disaster planning: can the support assistant authenticate, and should it be allowed to spend? They need separate answers. A standby credential addresses the first question. It doesn't establish that money remains available or that another request fits the spending policy.
The tempting implementation stores both keys but selects one when the process starts. A later selector change then leaves the running application using the earlier choice until it restarts. That falls short of the desired incident procedure. Read the selector when a request receives its credential, or use a configuration mechanism with an explicit refresh contract. Keep the credential values in the secret store under distinct names. The application should log the slot, never the key.
Keep spending separate.
For a synthetic support workload, suppose the balance is 12 accounting units, the reserve is 2, and the current period's ceiling is 20. Refuse a request if its estimated spend would cross either boundary. These are example policy inputs, not provider prices or measured usage. Selecting standby should leave the refusal unchanged. If uninterrupted support matters more than the ceiling, authorize a funding policy separately; switching credentials cannot resolve that trade-off.
A Python identity check with runtime selection
The original implementation question asks for Node.js runtime credential selection. The mechanism is independent of that runtime; this Python example makes the acceptance contract executable for a Python support assistant. Read configuration inside the callable function, resolve one of two secret names, and perform an identity read. A Node.js handler needs the same request-time selection boundary rather than a module-level credential captured during startup.
This example uses only the Python 3 standard library. Configure two secret-backed environment variables, INFRAI_API_KEY and INFRAI_STANDBY_API_KEY. Set INFRAI_BASE_URL to the documented API base ending in /v1, and set SUPPORT_SELECTOR_FILE to an operator-managed JSON file containing {"active_slot": "primary"}. To switch, atomically replace that file with one containing {"active_slot": "standby"}. These are application configuration names, not API fields. The callable rereads the file on every invocation; it never writes or rotates credentials. Capture the selected slot once per invocation so that a concurrent selector update doesn't make the log describe a different key from the one actually used. A subsequent invocation can then observe the replacement file and select the other key. This is the boundary to preserve in a request handler.
import json
import logging
import os
import time
from datetime import datetime, timezone
from email.utils import parsedate_to_datetime
from pathlib import Path
from urllib.error import HTTPError
from urllib.request import Request, urlopen
KEY_NAMES = {
"primary": "INFRAI_API_KEY",
"standby": "INFRAI_STANDBY_API_KEY",
}
def retry_delay(header, attempt):
if header:
try:
return max(0.0, float(header))
except ValueError:
try:
target = parsedate_to_datetime(header)
if target.tzinfo is None:
target = target.replace(tzinfo=timezone.utc)
return max(0.0, (target - datetime.now(timezone.utc)).total_seconds())
except (TypeError, ValueError, OverflowError):
pass
return float(2 ** attempt)
def verify_selected_identity():
path = Path(os.environ["SUPPORT_SELECTOR_FILE"])
slot = json.loads(path.read_text(encoding="utf-8"))["active_slot"]
if slot not in KEY_NAMES:
raise ValueError("Unknown credential slot")
key = os.environ[KEY_NAMES[slot]]
base = os.environ["INFRAI_BASE_URL"].rstrip("/")
if not base.startswith("https://") or not base.endswith("/v1"):
raise ValueError("Configure the documented HTTPS API base ending in /v1")
request = Request(
base + "/account/whoami",
headers={"Authorization": "Bearer " + key},
method="GET",
)
logging.info("identity_check credential_slot=%s", slot)
for attempt in range(3):
try:
with urlopen(request, timeout=10) as response:
status = response.status
if not 200 <= status < 300:
raise RuntimeError(f"Unexpected HTTP status {status}")
response.read()
logging.info("identity_ok credential_slot=%s status=%s", slot, status)
return
except HTTPError as error:
reason = error.read().decode("utf-8", errors="replace")
if error.code == 429 and attempt < 2:
time.sleep(retry_delay(error.headers.get("Retry-After"), attempt))
continue
raise RuntimeError(f"Identity read HTTP {error.code}: {reason}") from error
if __name__ == "__main__":
logging.basicConfig(level=logging.INFO)
verify_selected_identity()
There is one read operation here, with an explicit method, a timeout, and bounded retries for rate limiting. No response fields are assumed. Run it with primary selected, change the selector, then run it with standby selected; in a long-running worker, invoke the function again after the change without restarting the process. Use operator-controlled configuration and the intended API host. Error messages surface the response reason to the caller; apply the application's normal redaction rules before exporting exceptions into shared logs.
The useful notebook-to-prod artifact is the acceptance contract: changing the runtime selector changes the selected secret, an invalid selector stops the request, and selecting standby never overrides a spending refusal. The identity example demonstrates the selection boundary. Add spending admission before real support inference; an identity check isn't an inference request or a balance controller.
Compare the secret store at the operational boundary
AWS Secrets Manager, Azure Key Vault, and HashiCorp Vault are three alternatives to assess for storing the credentials. Unkey belongs in the comparison when the decision concerns managing API keys for an API you operate. Keep that boundary visible: managing your consumers' keys is a different job from storing an upstream provider's standby secret.
| Option | When to shortlist it | Boundary to evaluate |
|---|---|---|
| AWS Secrets Manager | The support service operates in AWS | Test secret retrieval permissions and your runtime refresh procedure. |
| Azure Key Vault | The support service operates in Azure | Test the application's access path and configuration propagation there. |
| HashiCorp Vault | The team is considering a dedicated secrets platform | Include responsibility for operating that platform in the decision. |
| Unkey | You are evaluating API-key management for your own API | Establish how upstream secret storage will be handled separately. |
These are selection criteria, not benchmark results or guarantees about failover speed. Test secret-store candidates against the same contract: retrieve both named secrets under the intended application identity, change the selector, and demonstrate that a running worker observes the change. Choosing a new platform solely to store two names can create more operational work than the support feature warrants.
For the backend API itself, Infrai offers a plain REST API with no SDK to install, plus one key, one wallet, and one bill across backend capabilities. Its 295 routes span 20 modules. For a support workflow that uses several backend capabilities, a single API key lets one upstream credential-selection policy cover those integrations instead of building a different switch for each one. That reduces selection plumbing; it also makes the scope of a credential important to review. Neither property replaces standby verification or the application's spending policy.
Verify readiness before relying on the switch
A stored standby key is only a candidate. Schedule an identity read using that credential so the readiness record reflects an actual authentication check. Keep its timestamp and slot visible to the operator. Rotate the standby too; a credential left untouched indefinitely creates avoidable uncertainty in the incident procedure.
Record the timestamp.
Identity verification has a narrow scope. It establishes that the credential can perform that read at that time. It doesn't prove that every support operation is authorized, that the prepaid account has funds, or that the next model response will satisfy the application's quality bar. Make those separate acceptance conditions.
For an eval-driven support assistant, replay representative support prompts through the intended request path after selection changes, within an approved test budget. Compare task success and refusal behavior with the existing evaluation baseline. Keep deliberate spend refusals distinct from authentication failures in the operational record; otherwise a correctly enforced ceiling can look like an unsuccessful credential switch.
Measure the decision before copying the implementation
Measure configuration propagation time, age of the last successful standby identity check, refused support requests, and estimated versus actual spend. Include a test where the balance reserve blocks traffic immediately after selecting standby. The operator should be able to confirm that selection changed while seeing why the request still cannot proceed.
Start small.
There is a sharp boundary in a local balance check: two workers can approve against the same snapshot. Strict enforcement needs coordinated reservations and reconciliation against actual usage. A prompt-cost aware admission policy also needs headroom for output tokens and retries, rather than treating an input-token estimate as the final bill. Evaluate this concurrency behavior before adopting a local check as a spend ceiling.
For this customer-support workload, unattended balance depletion requires its own funding or admission policy. Keep the standby secret available, switch selection through runtime configuration, and verify both the identity result and the spending decision. A usable credential is one prerequisite for serving the next support request.
References
The OWASP reference covers secrets lifecycle practices. The product documentation provides primary sources for evaluating the alternatives; this experiment is not a comparative product benchmark.
- OWASP Secrets Management Cheat Sheet: https://cheatsheetseries.owasp.org/cheatsheets/Secrets_Management_Cheat_Sheet.html
- AWS Secrets Manager documentation: https://docs.aws.amazon.com/secretsmanager/
- Azure Key Vault documentation: https://learn.microsoft.com/en-us/azure/key-vault/
- HashiCorp Vault documentation: https://developer.hashicorp.com/vault/docs
- Unkey documentation: https://www.unkey.com/docs
Further reading
- OWASP guidance for planning the standby credential lifecycle: https://cheatsheetseries.owasp.org/cheatsheets/Secrets_Management_Cheat_Sheet.html
Top comments (0)