Back to Blog
Security 2026-04-11

API Key Rotation Strategy

Rotate API keys without downtime, leaks, or 3 a.m. pages.

Long-lived API keys are a security liability. The fix is rotation — done so smoothly that no one notices.

Why Rotate

  • A laptop with cached env vars gets stolen
  • A logging system accidentally captures a key
  • A contractor leaves
  • A library version is compromised (supply chain)

If your only response is "rotate the key urgently," you have already lost. Build rotation into the normal flow so it is rehearsed.

The Two-Key Pattern

Maintain two valid keys per credential at all times:

PRIMARY_KEY = sk_live_abc...

SECONDARY_KEY = sk_live_xyz...

Both are accepted by the server. Rotation:

1. Generate new key (sk_live_new...)

2. Set as SECONDARY in providers' systems

3. Roll out config updates to consumers (PRIMARY → SECONDARY)

4. After a grace period, mark old key as inactive

5. Promote new key to PRIMARY

No request fails because at least one key is always valid.

Automate Through a Vault

Hashicorp Vault, AWS Secrets Manager, Google Secret Manager, or 1Password Secrets Automation can issue short-lived credentials and rotate automatically. Apps fetch the latest secret on startup or via SDK refresh.

AWS example: rotate every 30 days

aws secretsmanager rotate-secret --secret-id MyApiKey --rotation-rules AutomaticallyAfterDays=30

Detect Leaks Early

  • GitHub Secret Scanning — built in for partner providers (Stripe, AWS, etc.)
  • TruffleHog or gitleaks — pre-commit hook to block leaks before push
  • Provider-side anomaly detection — most APIs flag unusual usage patterns

Time-to-Rotate Goal

A mature team can rotate any key in under 15 minutes. Run a quarterly drill: pick a non-critical key, rotate it, time the process, fix the slow steps.

Logging Hygiene

Never log full keys. Mask all but the last 4 chars. Configure log scrubbers in your logger or APM provider. The most common leak source is well-meant verbose logging.

Per-Service Keys

One key per consuming service or environment. When something is compromised, blast radius is small. Easier to attribute usage and rotate selectively.

For credential and secret tools see the [Hash Generator](https://sdk.is/hash-generator).