API Key Rotation Best Practices: Automate Secret Lifecycle Management
An API key that never rotates is an API key waiting to be compromised. The median time to detect a credential breach is 204 days according to IBM's 2025 Cost of a Data Breach Report. If your API keys are not rotating on a schedule shorter than that, any compromised key has months of undetected access. This guide covers why rotation matters, how to implement automated rotation without downtime, which tools to use, and how to build an incident response process for exposed keys.
Why API Key Rotation Matters
API keys are the most commonly exposed credential type. A 2025 GitGuardian report found that 12.8 million new secrets were exposed in public GitHub repositories in 2024 alone. Among those, API keys represented 43% of all exposed secrets, followed by database credentials at 18% and private keys at 12%.
Regular key rotation limits the damage window of any compromise:
- Reduces exposure time: If a key is compromised but rotated every 30 days, the attacker has at most 30 days of access. Without rotation, access persists indefinitely.
- Invalidates stolen credentials: Keys that were accidentally committed to source code, logged in plaintext, or intercepted in transit become useless after rotation.
- Satisfies compliance requirements: SOC 2, PCI DSS, HIPAA, and ISO 27001 all require or recommend regular credential rotation.
- Forces good architecture: Systems designed for key rotation are inherently more resilient because they cannot depend on hardcoded credentials.
Rotation Strategies
1. Dual-Key Rotation (Zero-Downtime)
The most common strategy for production systems. It works by maintaining two active keys simultaneously during the rotation period:
- Generate: Create a new API key (Key B) while the current key (Key A) remains active
- Deploy: Update all consumers to use Key B. Key A continues to work during this transition
- Verify: Confirm that all traffic has migrated to Key B by monitoring API key usage metrics
- Revoke: Once no traffic uses Key A, revoke it
- Wait: Key B becomes the primary key. The cycle repeats on the next rotation schedule
This strategy requires your API provider to support multiple active keys simultaneously. Most major providers (AWS, Google Cloud, Stripe, Twilio) support this natively.
2. Rolling Rotation
For distributed systems where updating all consumers simultaneously is not feasible:
- Generate a new key and add it to your secret management system
- Configure the API to accept both old and new keys (grace period)
- Gradually roll out the new key to consumers through your normal deployment pipeline
- Monitor usage of the old key until it drops to zero
- Revoke the old key after the grace period expires
Grace periods should be long enough for all consumers to update but short enough to limit exposure. Typical grace periods range from 24 hours to 7 days depending on deployment frequency.
3. Dynamic Secrets
The most secure approach eliminates long-lived keys entirely. Instead of rotating static keys, the system generates short-lived credentials on demand:
- HashiCorp Vault dynamic secrets: Generates database credentials with a configurable TTL (e.g., 1 hour). When the TTL expires, Vault automatically revokes the credentials.
- AWS STS temporary credentials: IAM roles assume temporary credentials that expire after 1-12 hours. No static access keys needed.
- OAuth 2.0 client credentials: Short-lived access tokens (typically 1 hour) obtained through client authentication. The token itself rotates with every refresh.
Dynamic secrets eliminate the rotation problem entirely because there is nothing to rotate. Every credential is ephemeral by design.
Generate Strong API Keys
Use SecureBin's password generator to create cryptographically strong API keys with configurable length and character sets.
Generate API KeysAutomating API Key Rotation
AWS Secrets Manager Rotation
AWS Secrets Manager provides built-in rotation for AWS services and custom rotation for third-party APIs:
# Enable automatic rotation every 30 days
aws secretsmanager rotate-secret \
--secret-id prod/api/stripe-key \
--rotation-lambda-arn arn:aws:lambda:us-east-1:123456789:function:rotate-stripe \
--rotation-rules AutomaticallyAfterDays=30
The rotation Lambda function implements the four-step rotation process: createSecret, setSecret, testSecret, and finishSecret. AWS provides templates for common services, and you can write custom rotation functions for any API.
HashiCorp Vault Rotation
Vault's dynamic secrets engines generate credentials on demand with automatic revocation:
# Configure the database secrets engine
vault write database/config/mydb \
plugin_name=mysql-database-plugin \
connection_url="{{username}}:{{password}}@tcp(db.example.com:3306)/" \
allowed_roles="app-role" \
username="vault-admin" \
password="vault-password"
# Create a role with 1-hour TTL
vault write database/roles/app-role \
db_name=mydb \
creation_statements="CREATE USER '{{name}}'@'%' IDENTIFIED BY '{{password}}'; GRANT SELECT ON mydb.* TO '{{name}}'@'%';" \
default_ttl="1h" \
max_ttl="24h"
Applications request credentials from Vault at startup and periodically renew their lease. When the lease expires, Vault revokes the credentials automatically.
Kubernetes External Secrets Operator
For Kubernetes workloads, the External Secrets Operator syncs secrets from external providers and handles rotation automatically:
apiVersion: external-secrets.io/v1beta1
kind: ExternalSecret
metadata:
name: api-credentials
spec:
refreshInterval: 1h # Check for rotation every hour
secretStoreRef:
name: aws-secrets
kind: SecretStore
target:
name: api-credentials
data:
- secretKey: api-key
remoteRef:
key: prod/api/stripe-key
property: apiKey
The refreshInterval controls how frequently the operator checks for updated secrets. After rotation in AWS Secrets Manager, the Kubernetes secret is automatically updated without pod restarts (though your application must support hot-reloading).
Rotation Schedules by Key Type
Different types of API keys warrant different rotation frequencies based on their risk profile:
- Production API keys (payment processors, cloud providers): Rotate every 30-90 days. These keys have the highest blast radius and are the most common audit target.
- Database credentials: Rotate every 30 days, or use dynamic secrets with 1-24 hour TTLs. Database access is typically the most damaging if compromised.
- Third-party SaaS API keys (analytics, email, monitoring): Rotate every 90 days. Lower risk but still important for defense in depth.
- Internal service-to-service tokens: Use mutual TLS with certificate rotation every 90 days, or JWT tokens with 1-hour expiry.
- CI/CD pipeline tokens: Rotate every 30 days. These tokens often have broad access and are stored in multiple systems.
- Development and staging keys: Rotate every 90 days. Lower risk, but compromised dev keys can sometimes be used to pivot to production.
Monitoring and Alerting
Rotation without monitoring is incomplete. Set up the following alerts:
Key Age Monitoring
Track the age of every API key and alert when keys approach their rotation deadline:
- Warning at 80% of rotation period: "Stripe API key is 72 days old (90-day rotation policy)"
- Critical at 100% of rotation period: "Stripe API key has exceeded its 90-day rotation policy"
- Emergency at 150% of rotation period: Page on-call: "Stripe API key is 135 days old, immediately rotate"
Rotation Failure Monitoring
Automated rotation can fail silently. Monitor for:
- Rotation Lambda invocation errors
- Failed authentication attempts after rotation (new key not propagated correctly)
- Secret manager errors during the rotation process
- Vault lease expiration failures
Key Usage Anomalies
Monitor API key usage patterns to detect compromised keys:
- Geographic anomalies: Key used from an IP in a country where your organization does not operate
- Volume anomalies: Key usage spikes well above normal patterns
- Time anomalies: Key used during hours when no legitimate systems should be calling the API
- Endpoint anomalies: Key accessing API endpoints it has never accessed before
- Old key usage: Traffic on a revoked key indicates a consumer was not updated or an attacker is testing stolen credentials
Incident Response for Exposed API Keys
When an API key is discovered in a public location (GitHub, logs, error messages, client-side code), execute this response plan:
Immediate Actions (Within 15 Minutes)
- Rotate immediately: Generate a new key and revoke the exposed key. Do not wait for a change window.
- Assess scope: Determine what the exposed key can access. What APIs? What data? What permissions?
- Check for unauthorized usage: Review API logs for activity from unexpected IP addresses or unusual patterns since the key was exposed.
Short-Term Actions (Within 24 Hours)
- Remove the exposure: Delete the key from the public location (rewrite Git history if committed to a public repo, remove from logs, etc.)
- Notify affected parties: If the key provided access to customer data or third-party systems, notify the appropriate stakeholders.
- Update all consumers: Deploy the new key to all systems that depend on the rotated credential.
- Check for lateral movement: If the exposed key provided access to a system that stores other credentials, those credentials may also be compromised and need rotation.
Long-Term Actions (Within 1 Week)
- Root cause analysis: Determine how the key was exposed and implement controls to prevent recurrence.
- Implement scanning: If the key was exposed through source code, implement pre-commit hooks and CI/CD scanning to prevent future exposures.
- Review access permissions: Reduce the permissions of the new key to the minimum required (the exposed key may have had excessive permissions).
- Update runbooks: Document the incident and update your key rotation runbooks with lessons learned.
Securely Share API Keys During Rotation
When coordinating key rotation across teams, use SecureBin to share new credentials through encrypted, self-destructing links instead of Slack or email.
Share Keys SecurelyCommon Rotation Mistakes
Rotating the Key but Not the Secret
Some APIs use key-secret pairs (like AWS access key ID and secret access key). Rotating just the key ID without rotating the secret provides zero security benefit. Always rotate the entire credential set.
Not Testing After Rotation
Automated rotation should include a verification step that confirms the new credential works before revoking the old one. Without this, a rotation failure can cause a production outage. AWS Secrets Manager's rotation template includes a testSecret step specifically for this purpose.
Hardcoding Keys in Application Config
If your application reads API keys from a configuration file that requires a deployment to update, rotation requires a deployment. This makes rotation slow, risky, and dependent on your deployment pipeline. Instead, applications should read credentials from the secret manager at runtime, allowing rotation without redeployment.
Not Revoking Old Keys
Creating a new key without revoking the old one doubles your attack surface. Every rotation must include a revocation step after verifying that no traffic uses the old key. Monitor old key usage for a grace period, then revoke with zero exceptions.
Ignoring Service Account Keys
Service accounts often have the most permissive API keys and the least rotation discipline. A service account key created during initial setup that has never been rotated is a prime target. Include service account credentials in your rotation policy with the same rigor as user-facing keys.
Tools for API Key Rotation
- AWS Secrets Manager: Built-in rotation with Lambda. Native integration with RDS, Redshift, DocumentDB. $0.40/secret/month.
- HashiCorp Vault: Dynamic secrets for databases, cloud providers, PKI. Open source or HCP Vault ($0.03/hr). Best for multi-cloud.
- Google Cloud Secret Manager: Rotation notifications and integration with Cloud Functions. $0.06/active secret version/month.
- Azure Key Vault: Certificate and key rotation with Event Grid notifications. Standard tier from $0.03/10K operations.
- Doppler: Secret management with automatic rotation and deployment sync. Free for individuals, $4/user/month for teams.
- GitGuardian: Detects exposed secrets in repositories and triggers automated rotation workflows. $30/developer/month.
- SecureBin Hash Generator: Generate secure hashes for API key verification and integrity checking.
Building a Rotation Runbook
Document a runbook for each API key that includes:
- Key identifier: Which key, which service, which environment
- Rotation method: Automated (which tool) or manual (which steps)
- Dependent systems: Every application, service, and pipeline that uses this key
- Verification steps: How to confirm the new key works in all dependent systems
- Rollback procedure: What to do if the new key does not work (reactivate the old key, investigate, retry)
- Owner: Who is responsible for this key's lifecycle
- Rotation schedule: How frequently this key should rotate
- Last rotation date: When this key was last rotated
The Bottom Line
API key rotation is not optional security hygiene. It is the difference between a compromised key giving an attacker permanent access and a compromised key giving them a narrow window of access that closes automatically. Automate rotation wherever possible, use dynamic secrets to eliminate static keys where feasible, and maintain incident response procedures for when keys are inevitably exposed. The organizations that treat key rotation as a continuous operational process rather than a periodic compliance task are the ones that survive credential compromises without material impact.
Related Articles
Continue reading: SOC 2 Secret Management Requirements, Zero Trust Credential Sharing, How to Secure API Keys in Code, Detect Secrets in GitHub Repositories, Kubernetes Secrets Management.