Interview's MateAI Engineering
Interview's Mate

AI Engineering

LLMs, RAG, agents & evals

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
AI Engineering topics
Lesson 112/ 160
06. AI Security

API Key Rotation

Rotate provider keys on a schedule and after incidents without downtime.

BeginnerRotation · Dual Keys3 quiz questions
Practice Generative AI Q&A
In plain wordsDiagramTheoryStep by stepWhen to use itInterview cluesMistakes to avoidHands-onQuiz (3)Practice

In plain words

Swap your app's secret key for a new one regularly and after any leak, giving the new key to every service before turning the old one off, so nothing breaks.

Think of it like…

Changing the locks on an office building while people work: you hand out new keys first, check everyone has one, then re-key the old lock, rather than locking everyone out for an afternoon.

Where you’ve seen it

A company has 24 provider and tool keys across 12 services. With a 90-day schedule that is 365 ÷ 90 ≈ 4.06 rotations per key, about 97 rotations a year; done by hand at 20 minutes each, that's 97 × 20 = 1,947 minutes (32.4 hours) of error-prone work, so they automate. The secret manager keeps two versions, current and previous. A rotation job creates the new provider key, stores it as current, triggers a rolling restart so each service loads it (services accept previous as a fallback for 24 hours), then watches the provider's usage metrics: when requests authenticated with K1 fall to zero for 6 hours it revokes K1. In one rotation a forgotten cron job on an old VM was still using K1; the monitoring caught the stray traffic and the owner was identified before revocation, preventing an outage. After a leak incident, the same runbook revokes the exposed key within 1 hour, then audits usage between exposure and revocation.

Words you’ll hear

Dual-key rotation
Overlapping old and new keys so consumers can switch without downtime.
Secret versions
Stored current and previous values with labels managed by the secret manager.
Revocation
Disabling a key so it no longer authenticates.
Exposure window
The time between a credential leaking and being invalidated.

Visual diagram

Loading interactive diagram

Theory & deep dive

Designing rotation that doesn't break things

Start from design for rotation: each service gets its own key (so one rotation affects one consumer and logs show who used what), consumers read the secret from a secret manager at start-up or on refresh rather than baking it in, and the provider supports multiple active keys. Name keys with metadata (service, environment, owner, created date) and keep an inventory. The procedure: (1) create K2, (2) publish it as the current version, (3) roll consumers, which should be able to reload without a code deploy (periodic refresh or restart on secret change), (4) keep K1 valid for an overlap window (hours to a day, longer for batch jobs that run weekly), (5) verify via the provider's usage dashboard or audit logs that K1 traffic has stopped, (6) revoke K1 and (7) record the rotation.

Choose a schedule by risk and cost: 30 to 90 days for high-value keys, and rotate immediately on suspected exposure, employee departures, vendor incidents or when a secret appeared in a log or ticket. Prefer short-lived credentials (workload identity, OAuth tokens that expire in minutes) wherever the provider allows, since they make rotation unnecessary. For keys that must be static, automation matters: 24 keys on a 90-day cycle means 24 × 4.06 ≈ 97 rotations a year, about 32 hours of manual work at 20 minutes each. Rotation also reveals hidden copies (scripts, notebooks, partner integrations), which is a benefit: a failed rotation is better found in a planned window than during an incident.

Rotation workload

24 keys ÷ 90-day schedule: 24 × (365/90) ≈ 97 rotations a year. At 20 minutes each by hand: 97 × 20 = 1,947 minutes = 32.4 hours. Automated rotation reduces this to review and exception handling.

Key takeaway: Use per-service keys, a secret manager with versions and an overlap window, and automate on a schedule plus on incidents.

Verification, incidents and pitfalls

Verify before you revoke: check that all consumers have the new key (deployment status, secret read logs) and watch usage of the old key at the provider; any traffic means a consumer is still using it. Investigate unknown callers (an old VM, a notebook, a partner) rather than revoking blindly, unless the key is compromised, in which case revoke first and fix breakage after. Run rotations in a low-risk window, with a rollback plan (K1 can be re-enabled during the overlap, but not after revocation) and alerts on authentication errors (401/403 spikes) from your services.

For incidents, have a tested emergency path: revoke within a target time (for example 1 hour), rotate dependent secrets, review the audit log for use of the key between exposure and revocation (which IPs, models, volumes), check for data accessed through the key, notify as required and fix the leak source. Common pitfalls: sharing one key across many services (a rotation becomes a coordinated outage), keys hard-coded in images or client apps (rotation requires rebuilds or app updates), no overlap (downtime), revoking before verifying, and rotating but leaving the old key in git history or chat where it remains useful if not revoked. Track rotation compliance (keys older than policy), mean time to revoke and the number of unexpected old-key calls as program metrics.

Catching a stray consumer

After rolling K2, provider metrics still show 40 requests a day on K1 from an unfamiliar IP range. The team traces it to a forgotten reporting cron job, updates it to read the secret manager and revokes K1 two days later with no outage.

Key takeaway: Verify old-key traffic is zero before revoking, rehearse the emergency path and track compliance metrics.

How it works, step by step

Step 1 of 4
Security + platform

1. Inventory and separate keys

List all keys with owner, service, environment and age; split shared keys into per-service keys.

24 keys · 12 services
Key numbers at this step
Metadata
owner, created date

When to use it & trade-offs

What it is

API key rotation replaces a credential with a new one on a schedule and immediately after any suspected exposure, without downtime. The standard technique is dual-key (overlapping) rotation: create the new key (K2) while the old key (K1) still works, roll consumers to K2 (with a fallback to K1 during the transition), verify traffic and error rates, observe that K1 is no longer used, and only then revoke K1. Mature setups automate this with a secret manager that stores versions (current and previous), notifies or restarts consumers, and records every step in an audit log. Rotation limits how long a stolen key is useful and makes emergency revocation routine.

Why it matters: Credentials leak through logs, laptops, ex-employees, third-party tools and compromised build systems, often without anyone noticing. A key that never changes is a permanent liability; a key that rotates every 90 days has a bounded exposure window, and a team that has rehearsed rotation can respond to an incident in minutes rather than days. Rotation is also hard to do manually (many consumers, hidden copies), which is why the design must make it safe and automatic.

When to reach for it

  • Scheduled hygiene for provider and tool keys
  • Incident response after a suspected leak
  • Offboarding and vendor-compromise events

When to avoid or be careful

  • One key shared by every service
  • Revoking before verifying old-key traffic
  • Rotating without removing the old key from repositories and chats

Credential strategies

Scheduled dual-key rotation
Best for: Static API keys from providers

Strengths: Bounded exposure; zero downtime with overlap.

Watch out: Needs automation and per-service keys.

Short-lived tokens (workload identity, OAuth)
Best for: Cloud and modern APIs

Strengths: Expire quickly; little rotation work.

Watch out: Provider support varies.

Never rotate
Best for: Nothing

Strengths: No effort.

Watch out: Permanent exposure; unknown consumers; slow incident response.

Interview signals & numbers to know

When this topic comes up

  • “Rotate the key without downtime”
  • Dual keys and overlap
  • Secret versions
  • Mean time to revoke
  • Unexpected old-key calls

Benchmarks & rules of thumb

365 ÷ 90 ≈ 4.06 -
rotations per year per key on a 90-day schedule
24 × 4.06 ≈ 97 -
yearly rotations for 24 keys
≤ 1 hour -
target time to revoke an exposed key

Common mistakes & follow-ups

Common interview mistakes

  • Rotating all services at once with no overlap window.
  • Forgetting scheduled jobs and partner integrations that use the old key.
  • Treating rotation as a yearly manual chore.

Likely interviewer follow-ups

  • How do you rotate an API key with zero downtime?
  • What would you do within the first hour of a key leak?
  • How do you find hidden consumers of a key?
Interview tip: Describe overlap plus old-key usage monitoring before revocation. It's the step that prevents rotation outages.
Loading hands-on exercise

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply API Key Rotation with generative AI interview Q&A and hands-on practice.

Open Generative AI Q&A →Tech Learn Q&A
Previous topic
Secrets Management
Next topic
Authorization for Agents