In February a payments partner sent an email saying their API keys would rotate on the first of March, and the old key would stop working at 00:00 UTC. The integration was four years old. It lived in a Kubernetes config map, a Lambda environment variable, a cron box nobody had touched since 2023, and a screenshot in a support runbook that a team lead used to test refunds. A grep found three of those places. The fourth announced itself when a customer asked why their refund had not arrived.
That is the ordinary shape of a rotation failure. The secret itself is rarely the difficult part. What breaks is that a credential was copied into places the team stopped counting, and rotation is the moment the count starts to matter.
Why rotation is a distributed systems problem
A password in one file is easy to change. A credential used by forty containers, two batch jobs, a mobile build and an outsourced support desk takes on the properties of a deployment. Some consumers read the value at boot, some cache it for an hour, some hold a live session open for days, and one of them was written by a contractor who is no longer reachable.
Rotation also has to happen while the system keeps taking orders. That rules out the simple version, where you change the value and restart everything, because restarting everything at 2am is how a routine security task becomes an incident review.
So the pattern is always some variation of overlap. Two credentials are valid at once, every consumer migrates from the old one to the new one on its own schedule, and the old one is retired only when you can prove nothing is still using it. The interesting engineering is in that last clause.
The four kinds of secret, and why each rotates differently
Treating all credentials the same is the mistake that produces brittle runbooks. They fall into four groups, and each group has its own mechanics.
Symmetric API keys you issue
You control both sides, so you can accept several keys at once and tag each request with the key that authenticated it. A table of key hashes with an expires_at column is enough. The work is making sure the service that accepts the key tells you which one was used, because without that you cannot tell whether the old key is dead or merely idle.
Asymmetric signing keys
Verifiers fetch a public key set. Rotation means publishing the new public key before any token is signed with it, so every verifier has a chance to refresh. That is why a JWT with no key identifier is a liability: the verifier has to guess which key to try, and guessing across a rotation window produces a spike of authentication failures that looks like an attack.
Database credentials
The database is where rotation hurts most, because changing a password does not end the sessions already authenticated with it. A connection pool holds dozens of them, and a pooler that caches credentials will keep handing out working connections for as long as you let it.
Third-party credentials
These are the ones you cannot design around. The provider decides how many keys can be active, whether an old key keeps working during a grace period, and whether their dashboard allows two keys at the same time. Some do. Some will let you create a second key and immediately invalidate the first, which turns a rotation into a coordinated cutover across every environment you own.
The overlap window
Every safe rotation has a period where the old credential and the new one both work. Make that window explicit rather than incidental. Write down the start time, the end time, and the metric that proves migration is complete. A window without a deadline becomes permanent, and a permanent second key is just a second way in.
The second half of the pattern is instrumentation. Authentication code should record the identifier or version of the credential it used, never the credential itself. A counter labelled by key version, scraped into your metrics system, converts an argument about whether migration is finished into a query. Something like auth_success_total{key_version="3"} falling to zero for a full business cycle is evidence. A team saying they deployed the change is not.
Watch out for the metrics that lie. Success counts drop to zero when a component stops running, so pair them with request volume from the same source. A service that has been quietly broken for a week also reports zero old-key usage.
Rotating database passwords without dropping connections
The sequence that works on Postgres, and adapts to most managed databases:
- Create a second role with the same grants and a new password. Do not touch the existing role yet.
- Deploy the new credential to every consumer, one at a time, and let each service reconnect on its normal restart path.
- Watch active connections grouped by user for the old role. It will fall as pools recycle, and it will not reach zero while any long-lived pooler keeps a backend open.
- Drain deliberately. Restart poolers, terminate idle sessions belonging to the old role, and give anything that survives an explanation or a deadline.
- Revoke the old role's login and drop it. Keep the audit trail of when it was last used.
Running ALTER ROLE ... PASSWORD against the existing role is the shortcut everyone reaches for first. It is also the version that fails in production, because existing sessions keep working, new connections fail, and the failure is spread across whichever pods happen to reconnect first. Half your fleet authenticating and half erroring at the same time is much harder to diagnose than a clean cutover.
Two details cause most of the remaining pain. A pooler with a static userlist file needs that file reloaded, not just replaced, and some poolers validate credentials at connection time and will happily cache a dead password until the process restarts. And migration tooling holds its own credentials, often in a CI variable that nobody rotated because it is not part of the running application.
Signing keys: key identifiers and clock skew
Token signing keys rotate fastest in systems that got the details right, because the pieces are cheap to get right once.
Include a key identifier in the token header and publish a key set that can contain more than one key. Sign with the new key, keep verifying with both, and remove the old one after the longest token lifetime plus a margin. That margin is not paranoia. Clocks drift, caches hold the old key set for their own TTL, and a verifier that fetches the key set once at startup will not see the change until it restarts.
One question tends to get skipped: what happens to tokens signed with the retired key. Accepting them until they expire is usually correct and means the old key stays in the set for longer than feels comfortable. Rejecting them logs out every active user at once. Pick one on purpose, document it, and make sure the choice matches what the business expects from a session.
Key revocation has a related trap. If a signing key leaks, publishing a new key is not enough, because the old public key still validates forged tokens. You need the old key removed from the set immediately and every token it signed treated as untrusted, which usually means a forced re-authentication for everyone. That is the cost of the compromise, and it is cheaper than the alternative.
Encryption keys at rest
Data encrypted with a key that never changes is data you cannot re-key without decrypting it. Most teams solve this with envelope encryption: a key encryption key in a managed service wraps a data key, and the ciphertext stores which data key version it used.
Rotating the key encryption key is then a cheap operation, because it only rewraps the data keys. Rotating a data key means re-encrypting the data it protects, which on a large table is a migration with all the usual properties: batched, resumable, monitored, and able to run while the application writes new rows under the new key.
The workable pattern is a key version column plus a background sweep. New writes use the current version. Reads decrypt whatever version the row carries. The sweep re-encrypts old rows in batches, records progress, and can be paused. When the sweep reports zero rows on the oldest version, that version can be destroyed in the key service, which is the step that actually makes old ciphertext unreadable.
One warning: destroying a key version is irreversible, and it will silently break any backup or replica that still holds rows encrypted with it. Re-encryption and backup retention have to be reasoned about together, or a key rotation quietly turns into a restore failure six months later.
Credentials you do not own
Partner and provider keys need negotiation before they need engineering. Ask three questions before you accept a rotation date: how many keys can be active at once, how long does the old one keep working, and who can see the value after it is created.
When the answer is one active key, you are planning a cutover, not a rotation. That means sequencing environments, having the new credential staged everywhere before the switch, and testing the failure mode where some consumers have migrated and others have not. It also means finding out whether the provider's key creation invalidates the old one immediately, because that turns a planned change into an outage with a countdown.
Inbound credentials deserve equal attention. Webhook signatures verified with a single shared secret cannot rotate without rejecting legitimate traffic, so providers that support multiple active secrets for a window are worth preferring. When the provider does not, you accept a short window of failed deliveries and replay from their side, which works only if you have idempotent handlers and a replay path you have actually tested.
Make the next rotation boring
The difference between a two-hour maintenance window and a fifteen-minute change is mostly administrative, and it is worth building once.
Keep an inventory that names the owner of every credential, where it is consumed, and what breaks if it stops working. This is the artefact that makes the 00:00 UTC deadline survivable, because it turns a hunt into a checklist. Secrets managers with versioning and audit logs do most of this for you, provided nobody copies a value out to a place the manager cannot see.
Eliminate the copies that exist for convenience. Environment variables baked into container images are the worst offender, since the value is now in a registry forever and rotation does not remove it. Values pasted into chat, ticketing systems and runbook screenshots are the same problem with worse blast radius. Fetch at runtime from a managed identity, cache briefly, and never write the value to a log line or an error message.
Automate the mechanical part. Managed database services will rotate credentials on a schedule, and secret managers can run rotation as a lambda or a job. What you cannot automate is the migration of consumers, so keep that path short and tested. A rotation you can rehearse in staging on a Tuesday afternoon is a rotation you can run without a war room.
Finally, measure the thing you actually care about: time from rotation start to old credential revoked. If that number is measured in months, you do not have rotation. You have a second credential, and it is exactly as exposed as the first.
A checklist worth keeping
- Every credential has an owner, a rotation interval and a documented consumer list.
- Authentication events record the credential version, never the credential.
- Rotation windows have an end date and a metric that proves completion.
- Database rotation creates a new role and retires the old one after pool drain, instead of altering a password in place.
- Signing key sets can hold at least two keys, and every token carries a key identifier.
- Encrypted data records its key version, and a resumable sweep exists to migrate it.
- Backups are included in the plan before any key version is destroyed.
- Third-party rotation dates are tracked as project work with a rehearsal, not as a calendar reminder.
- Inbound webhook verification supports overlap, or the replay path has been tested.
- A rotation has been run end to end in staging in the last quarter.
None of this is exotic. It is the same discipline as any other production change, applied to a value that nobody looks at until it stops working. The teams that get it right are not better at cryptography. They are better at counting where their credentials ended up.