How to Rotate API Keys Without Downtime: A Developer's Guide

2026-07-14·
DevOpsBest PracticesTutorial

Why Key Rotation Matters

API keys are credentials — and like passwords, they should be rotated regularly. Leaked keys are the #1 cause of unauthorized API usage and surprise bills. Regular rotation limits the blast radius if a key is ever compromised.

The Zero-Downtime Rotation Strategy

Most providers let you have multiple active keys simultaneously. Use this to your advantage:

Step 1: Generate a New Key

Create a new key while the old one is still active:

Step 2: Test the New Key

Validate the new key before deploying:

  • Use Api Key Chain for an instant health check
  • Run your test suite against the new key
  • Verify it has the correct permissions and rate limits
# Quick validation with curl
curl -s -o /dev/null -w "%{http_code}" \
  -H "Authorization: Bearer NEW_KEY" \
  https://api.openai.com/v1/models
# Should return 200

Step 3: Deploy with Both Keys (Overlap Period)

This is the critical step — deploy your app with both keys configured:

# .env — during rotation
OPENAI_API_KEY=old-key-here
OPENAI_API_KEY_NEW=new-key-here

Your app should try the new key first, falling back to the old one:

const API_KEYS = [
  process.env.OPENAI_API_KEY_NEW,
  process.env.OPENAI_API_KEY,
].filter(Boolean);

async function callWithFallback(endpoint, options) {
  for (const key of API_KEYS) {
    try {
      const response = await fetch(endpoint, {
        ...options,
        headers: { ...options.headers, Authorization: `Bearer ${key}` }
      });
      if (response.ok) return response;
      if (response.status === 401) continue; // Try next key
      return response;
    } catch {
      continue;
    }
  }
  throw new Error('All API keys failed');
}

Step 4: Monitor and Verify

After deploying:

  1. Monitor error rates for 24-48 hours
  2. Check that traffic is flowing through the new key
  3. Confirm no 401 errors in logs
  4. Test the old key one final time to ensure you haven't missed any services

Step 5: Revoke the Old Key

Once traffic is stable on the new key:

  1. Go to the provider dashboard
  2. Revoke/delete the old key
  3. Remove it from environment variables
  4. Deploy the cleaned-up config

Automation with Api Key Chain

With Api Key Chain Premium, you can:

  • Save all your keys encrypted in one place
  • Schedule health checks to validate keys automatically
  • Get alerts when a key is nearing expiration
  • Bulk test multiple keys before and after rotation

Rotation Schedule by Risk Level

Service TierRotation FrequencyReason
Production payment (Stripe)Every 30 daysFinancial risk
Production AI (OpenAI, etc.)Every 90 daysCost and data risk
Development/TestingEvery 180 daysLower impact if leaked
Read-only keysEvery 365 daysMinimal blast radius

Common Rotation Mistakes

  • ❌ Revoking the old key before deploying the new one → downtime
  • ❌ Not testing the new key before deploy → surprise failures
  • ❌ Forgetting to update CI/CD environment variables → CI breaks
  • ❌ Rotating during peak traffic hours → schedule for low-traffic windows
🔄 Pro tip: Set a recurring calendar event for key rotation. Use Api Key Chain's health checks the day before rotation day to ensure all current keys are still valid.

Related Posts