How to Rotate Claude API Keys Automatically
Rotating API keys automatically means replacing live credentials on a fixed schedule or trigger — without a human manually generating a key, copying it, and redeploying — so a leaked or stale key stops working before it becomes a real incident. For Claude API keys specifically, this usually means combining a secrets manager, a small rotation script, and a deployment process that reads the key at runtime instead of hardcoding it.
This article walks through a practical setup: how to generate rotation triggers, where to store keys so rotation doesn't require a redeploy, how to handle in-flight requests during the swap, and what to automate versus what to keep manual.
Why manual key rotation fails
Most teams rotate keys reactively — after a key shows up in a public repo, after an employee leaves, or after a billing alert. The problem is that manual rotation has a human bottleneck: someone has to notice, generate a new key, update every service that uses it, and revoke the old one. In practice this takes hours or days, during which the compromised key is still valid.
Automated rotation removes the "someone has to remember" step. The key changes on a schedule (say, every 30 or 90 days) or on an event (a suspected leak, an offboarded teammate), and every service picks up the new value without a manual code change.
Step 1: Separate key storage from application code
The first requirement for automated rotation is that your application never hardcodes the key. It should read it from an environment variable or a secrets manager at startup or per-request, not from a config file committed to git.
// bad: key baked into source
const client = new Anthropic({ apiKey: "sk-ant-...hardcoded..." });
// good: read at runtime
const client = new Anthropic({ apiKey: process.env.CLAUDE_API_KEY });
If you're using a secrets manager (AWS Secrets Manager, HashiCorp Vault, GCP Secret Manager), store the key there and have your app fetch it on boot or via a short-lived cache (5–15 minutes) so rotation propagates without a full redeploy.
Step 2: Script the rotation itself
A rotation job needs three steps: create the new key, update the secret store, and revoke the old key after a grace period. Pseudocode for a cron-triggered rotation:
#!/bin/bash
# rotate-key.sh — run on a schedule (e.g. monthly via cron or CI)
NEW_KEY=$(create_new_api_key) # call your provider's key-management API
update_secret_store "CLAUDE_API_KEY" "$NEW_KEY"
sleep 300 # grace period for in-flight requests
revoke_old_key "$OLD_KEY_ID"
The grace period matters: if you revoke the old key the instant the new one is created, any request already in flight using the old key will fail mid-stream. A 5–10 minute overlap where both keys are valid avoids that.
Step 3: Handle multiple environments and seats
If you have staging, production, and per-developer keys, rotate them independently. Tie each key to a name or label that maps to its environment, so a rotation script can target "production-api" without touching "staging" or a teammate's personal key. This also makes audit trails easier: when a key shows unusual usage, you know immediately which environment or person it belongs to, instead of grepping logs for a bare key string.
This is one of the practical reasons to issue per-application or per-service keys rather than sharing a single key across your whole stack — rotation and revocation become scoped operations instead of all-or-nothing events.
Step 4: Automate the trigger, not just the mechanics
Scheduled rotation (every 30–90 days) handles routine hygiene. But you also want event-based rotation for:
- A key appearing in a public commit, log file, or error report
- A teammate leaving the project
- Unusual usage patterns (spend spikes, unexpected IP ranges)
Wire these triggers into the same rotation script so a leak detector (like a GitHub secret-scanning webhook) can call rotate-key.sh immediately instead of waiting for the next scheduled run.
Where SubToAPI fits
If you're using SubToAPI to expose your Claude access as an HTTPS API, rotation is simpler because the application-facing key (sub_live_...) is already separate from your underlying Claude access. You generate and revoke sub_live_ keys per application from the dashboard, so rotating a key means issuing a new one and updating the environment variable for that specific app — it doesn't touch your other applications or team seats. Combine that with the secrets-manager pattern above and you get the same automated rotation workflow without having to manage provider-level key creation yourself. See /docs/quickstart for how key issuance works, and /pricing for plan details if you're rotating keys across a team.
A minimal automated rotation checklist
- Keys are read from environment variables or a secrets manager, never hardcoded
- A script (cron, CI job, or cloud function) creates a new key and updates the secret store
- Old keys stay valid for a short grace period before revocation
- Each environment or application has its own key, not a shared one
- Leak-detection triggers call the rotation script on demand, not just on schedule
- Rotation events are logged so you can audit when and why a key changed
// Example: fetching the current key at request time (cached)
let cachedKey = null;
let lastFetch = 0;
async function getApiKey() {
if (Date.now() - lastFetch > 10 * 60 * 1000) {
cachedKey = await secretsClient.getSecretValue("CLAUDE_API_KEY");
lastFetch = Date.now();
}
return cachedKey;
}
This pattern — short-lived in-memory cache backed by a secrets manager — lets rotation take effect within minutes without redeploying your application.
FAQ
Does Claude's API support built-in key rotation? Anthropic's console lets you create and revoke keys manually, but there's no native scheduled-rotation feature. You build rotation yourself using the pattern above: a secrets manager, a rotation script, and application code that reads keys at runtime instead of hardcoding them.
How often should I rotate API keys? A common baseline is every 30–90 days for routine hygiene, plus immediate rotation on any suspected leak or offboarding event. Lower-traffic internal tools can rotate less frequently; production keys handling customer traffic should rotate on the shorter end.
Can I rotate keys without downtime? Yes, if you keep the old key valid for a short grace period (5–15 minutes) after issuing the new one, and have your application re-fetch the key from a cache or secrets manager rather than requiring a restart. This avoids failed requests during the swap.