How an app fetches and rotates an LLM API key from a vault
Step 1 of 5
App starts
The service starts with no API key in its code or environment. It has only an identity, such as an IAM role, for each environment.
Step 2 of 5
Ask the vault
The app authenticates to the vault and requests the secret by name. The vault checks the identity's permissions and records the access.
Step 3 of 5
Cache briefly
The key is held in memory so the vault is not called on every request. A short cache keeps latency low while still picking up a new key soon after rotation.
Step 4 of 5
Call provider
The key is attached to the model call and never written to logs. Separate keys per environment limit the damage if one leaks.
Step 5 of 5
Rotate
The vault issues a new key on a schedule. Apps pick it up on their next fetch, with no redeploy, and the audit trail shows who used which key.
The key lives in the vault, not in the code, the environment or the logs.
Problem
LLM API keys in .env files or code lead to leaks, unrotated keys, and no audit of who used which key.
Pattern
Store secrets in a vault (HashiCorp Vault, AWS Secrets Manager). Fetch at startup or per-request with short-lived tokens. Rotate frequently. Never log secrets.
Implementation
secrets.py
~128 tokens
from functools import lru_cache
import boto3
@lru_cache(maxsize=1)
def get_openai_key() -> str:
client = boto3.client("secretsmanager")
resp = client.get_secret_value(SecretId="prod/openai/key")
return resp["SecretString"]
def call_llm(messages):
# Key fetched from vault, never from env
key = get_openai_key()
return openai.chat.completions.create(api_key=key, ...)
# Rotate keys without redeploying apps — vault returns new value
# Audit access via CloudTrail