How to Rotate Secrets Without Downtime
Give keys identifiers, verify with any active key while signing with the newest, overlap windows generously, and drain old usage to zero before removal.
On this page
Introduction
Secret rotation is operationally inevitable, certificates expire, keys leak, personnel change, compliance demands periodic rotation, and the naive implementation is an outage with a timestamp on it: replace the key, restart, and every in-flight token signed with the old key fails, every replica that has not restarted yet disagrees with the ones that have, and every consumer holding a cached verification key breaks on its own schedule. Downtime-free rotation is a state machine with a simple invariant: at every moment, every verifier can verify everything still in circulation. Achieving it requires three mechanisms. Key identity: keys carry ids, so verification can address a specific key rather than implicitly using whichever one is loaded. Ordering: the new key is added to verifiers before anyone signs with it, and the old key is removed from signing long before it leaves verification. Drain measurement: usage by key id is monitored to zero before retirement, because the schedule of when old-key artifacts expire out of circulation is the real rotation clock, not the calendar. This tutorial implements the pattern for signing keys and extends it to data encryption through envelope encryption, then covers the coordination failures that turn rotations into incidents.
The invariant and the state machine
The invariant, every verifier can verify everything in circulation, defines a small state machine per key. A key is future: distributed to verifiers but not yet used to sign, and nothing references it. Active: used for signing and verification, the current production key. Retired: verification only, no new signatures, while previously-signed artifacts expire out. Removed: gone from the system, after usage has drained to zero. The transitions have strict ordering: future to active requires every verifier to hold the key first, because a signature that arrives at a verifier lacking the key is an outage; active to retired requires only the signing side to stop, since verification continues. The mirror-image anti-patterns each violate one transition: flip the key everywhere at once, future to active with no distribution phase, and in-flight tokens fail; remove from verification while signing still uses the key, and every new token fails somewhere. The state machine is also the audit artifact: a key’s phase transitions, with timestamps and the operator who triggered them, are the compliance record that rotation actually happened, and they belong in a changelog that outlives the keys.
Implement signing-key rotation
Signing keys surface the pattern in its purest form, because signatures are artifacts that outlive the moment of signing, tokens, webhooks, cookies. The implementation gives each key an id, embeds it in the artifact, and makes the verifier a keyring lookup.
export class SigningKeyring {
private keys = new Map<string, KeyMaterial>();
private activeId: string;
add(id: string, material: KeyMaterial, activate = false) {
this.keys.set(id, material);
if (activate) this.activeId = id;
}
sign(payload: object): SignedToken {
const key = this.keys.get(this.activeId)!;
const kid = this.activeId;
const body = canonicalJson(payload);
const signature = hmac(key, body);
return { kid, body: base64url(body), sig: base64url(signature) };
}
verify(token: SignedToken): boolean {
const key = this.keys.get(token.kid);
if (!key) return false;
return constantTimeEqual(hmac(key, token.body), token.sig);
}
active() { return this.activeId; }
}
The rotation choreography on this primitive: add the new key with activate false, confirm distribution, then activate, new signatures carry the new kid, old tokens still verify through the old key entry, and the monitor counts verifications by kid until the old key’s count hits zero for a full token-lifetime period. JWT expresses the same choreography with the kid header and a JWKS endpoint that publishes the public keys, where updating the JWKS is the distribution phase and consumers cache it on a TTL that becomes part of the overlap arithmetic.
Envelope encryption for data keys
Signing-key rotation is cheap because signatures expire on their own. Data encryption keys are harder: ciphertext does not expire, and rewriting every ciphertext on rotation is prohibitive at volume. Envelope encryption solves the cost structure: each data-encryption key, DEK, encrypts the data; the DEK itself is stored encrypted by a master key, key-encryption key, KEK; rotating the KEK re-wraps the DEKs without touching the data, and rotation cost becomes proportional to the number of DEKs, not the bytes they protect. Each encrypted value carries its wrapping version, so the reader knows which KEK unwrapped the DEK it needs.
// rotate: re-wrap DEKs under the new KEK, data untouched
for (const dek of store.listDataKeys()) {
const material = unwrap(dek.wrapped_v3, keks.v3);
store.saveWrapped(dek.id, wrap(material, keks.v4), 'v4');
}
Managed services, AWS KMS automatic rotation, HashiCorp Vault’s transit engine with its key versions, implement the same structure and add the operational wins: keys never leave the service, operations are audited, and rotation is an API call. The in-house version is justified mainly by constraints that forbid the managed option, and it inherits every obligation this tutorial describes, distribution ordering, drain measurement, version-tagged storage, plus the key-protection problem the managed service was solving.
Ordering and coordination
The rotation incident is almost always an ordering violation, so the choreography deserves mechanical enforcement. Distribution before activation: the new key reaches every verifier, every replica, every consumer service, before the first signature exists, verified by a canary, one signature verified by every consumer, or by configuration inspection, because a verifier that misses distribution fails on the first token it sees. Consumers that cache keys, JWKS caching is the canonical case, have a cache TTL that participates in the schedule: the overlap window must exceed the cache TTL plus the artifact lifetime, or a consumer with a stale cache rejects a token signed with a key it could have had. Retire after drain: removal waits for usage-by-kid to reach zero and stay there for a full artifact lifetime, because a token issued one minute before deactivation still verifies for its TTL. The coordination failure that hurts most is the silent one: a consumer embedded in a cron job, a rarely-run batch process, a forgotten integration, which holds the old key and breaks a month later when it finally runs. The defense is the inventory: key consumers are enumerated, and the drain metric counts not just verifications but distinct consuming identities, so the batch job that has not called since last quarter shows up as a nonzero entry that blocks removal.
Measure drain to zero
The rotation is finished when the old key is gone, and the only honest signal is usage telemetry by key id. For signing keys: count verifications per kid, and the old key’s curve decays with the artifact lifetime, a clean exponential toward zero if token TTLs are uniform, a long tail if some artifacts live for days. The removal criterion is zero for one full maximum-lifetime window, graphed, because a nonzero blip after a quiet week is the forgotten consumer announcing itself. For encryption keys: count unwraps per wrapping version, where a permanently cached DEK might show zero traffic, and the criterion becomes no unwraps plus a re-wrap migration that has rewritten all stored versions, a metric the key store can export directly. Alert on the anomalies in both directions: old-key usage that persists past the expected drain, the forgotten consumer, and new-key verification failures, the consumer that missed distribution, which is the rotation incident in its first minute. The dashboard’s job is to make the rotation’s progress legible, keys by phase, usage curves by id, so the operator promoting a key from future to active is looking at evidence rather than a checklist.
Test rotation under traffic
Rotation correctness is only visible under live traffic, so the tests simulate it. Overlap test: with tokens signed under key A in circulation, activate key B and assert A-signed tokens verify throughout, B-signed tokens verify immediately, and the transition produces zero verification failures. Missed-distribution test: remove key A from one verifier replica and assert tokens signed with A fail on that replica only, which documents the blast radius the distribution phase exists to prevent. Cache-TTL interaction: with a consumer caching keys for 300 seconds, rotate and assert verification succeeds continuously across the cache refresh boundary, which requires the old key in the JWKS past the TTL. Drain test: fast-forward the clock past token lifetimes, assert usage-by-kid reaches zero, remove the key, and assert nothing breaks. Emergency rotation, the leak scenario, deserves its own drill: compress the schedule, revoke signing immediately, accept in-flight token failures, and measure how quickly the fleet converges, because the emergency path is the one with no rehearsal time when it is real.
it('verifies across the activation boundary', async () => {
const before = ring.sign({ sub: 'u1' }); // key A
ring.add('B', keyB, /* activate */ true);
const after = ring.sign({ sub: 'u2' }); // key B
expect(ring.verify(before)).toBe(true);
expect(ring.verify(after)).toBe(true);
});
Common pitfalls
- **Flip-and-restart. ** Replacing the key in place fails every in-flight artifact and every un-restarted replica at once; rotation is overlap, not replacement.
- **Activation before distribution. ** The first signature with the new key becomes the first outage wherever the key has not arrived.
- **Removal on a calendar date. ** The schedule is usage telemetry, not a date; drain to zero plus one artifact lifetime.
- **Cache TTLs outside the arithmetic. ** Consumers holding cached keys break at their refresh boundary unless the overlap exceeds TTL plus artifact lifetime.
- **Rewriting ciphertext on rotation. ** Prohibitive at volume; envelope rotation re-wraps keys instead of data.
- **No key inventory. ** The forgotten batch consumer resurfaces a month later; the consumer list is what makes removal safe.
Conclusion
Secret rotation without downtime is an ordering problem wearing a security badge, and the invariant is that every verifier can always verify everything in circulation. Give keys ids so artifacts address them, choreograph the transitions, distribute, activate, retire after drain, remove after zero, and publish the state changes as the compliance record. For data encryption, use envelope structure so rotation re-wraps key material instead of rewriting ciphertext, and let managed key services carry the protection obligations when the constraints allow. Measure usage by key id as the rotation’s true clock, enumerate consumers so the forgotten batch job blocks removal instead of breaking later, and test the boundaries under live traffic, activation, cache TTL, drain, and the compressed emergency path. Rotation then becomes the routine hygiene it should be, instead of the quarterly gamble it usually is.
Sources: HashiCorp Vault: transit engine, OWASP: key management cheat sheet, AWS KMS: rotating keys.
FAQ
- Why does swapping a key in place cause errors?
- In-flight tokens signed with the old key fail verification against the new one, and every cache or replica that held the old key independently breaks on its own schedule. Rotation must be an overlap of two keys, not a replacement of one.
- How long should the overlap window be?
- At least the longest lifetime of anything referencing the key: token TTLs, cache entries, DNS TTLs if keys ride service discovery. Two weeks is a common floor for API signing keys; shorter is workable when every consumer is under your control.
- How does this work for data encryption keys?
- Through envelope encryption: data keys encrypt data and are themselves encrypted by a master key. Rotating the master key re-wraps the data keys without touching the data, so rotation cost is proportional to key count, not data volume.
Report a problem with this articleOpens a pre-filled issue on GitHub.