Designing a JWKS endpoint: caching, rotation, and kid selection
Every service that validates a JWT from your authorization server fetches your JWKS — the JSON Web Key Set that publishes the public keys they use to verify signatures. It looks like a static file. It is not. It is a hard dependency in the request path of every token validation across your entire fleet, and the day you rotate a key badly, it becomes the single point of failure that takes all of them down at once.
The failure mode is specific and I have watched it happen: a team rotates their signing key, the new key's public half is not yet in the JWKS cache that resource servers hold, every token signed with the new key fails verification, and authentication breaks everywhere simultaneously. Nothing in the logs says "JWKS" — it just looks like every token suddenly went invalid. Getting the endpoint's caching, rotation, and kid discipline right is what prevents that outage.
What the endpoint serves
A JWKS is a JSON document with a keys array. Each entry is a public key plus metadata, and the metadata is what makes correct validation possible.
{
"keys": [
{
"kty": "RSA",
"use": "sig",
"kid": "sig-2026-q2-a",
"alg": "RS256",
"n": "0vx7agoebGcQSuu...",
"e": "AQAB"
},
{
"kty": "RSA",
"use": "sig",
"kid": "sig-2026-q2-b",
"alg": "RS256",
"n": "sXchDaQebHnPiGv...",
"e": "AQAB"
}
]
}The kid (key ID) is the hinge of the whole design. A token's header carries a kid; the validator looks up the matching key in the JWKS by that ID. Serve multiple keys at once, give each a stable unique ID, and validators can always find the one they need — including during the overlap window when some tokens are signed with the old key and some with the new.
Caching: the two failure directions
Validators cache the JWKS because fetching it on every request would add a network hop to every API call and hammer your endpoint. Caching introduces two opposite risks, and a good design bounds both.
Cache too long and rotation breaks
If a validator caches for 24 hours and you rotate a key, tokens signed with the new key fail for up to a day. Set a sane Cache-Control max-age — minutes to a low number of hours — so caches refresh on their own within your rotation overlap window.
HTTP/1.1 200 OK
Content-Type: application/json
Cache-Control: public, max-age=3600
ETag: "jwks-2026-q2-rev3"Cache too short and you DDoS yourself
If every validator refetches aggressively, a traffic spike turns into a thundering herd against your JWKS endpoint. Serve it from a CDN or edge cache, support ETag so unchanged fetches return 304, and make sure the endpoint can survive being the most-requested path you own.
kid it refetches the JWKS once (rate-limited), then retries verification. That way a freshly rotated key is picked up within one request instead of one cache lifetime — but a flood of bogus kids cannot be used to hammer your endpoint.Rotation: overlap is mandatory
Key rotation is not "swap the key." It is a staged process with an overlap window, and skipping the overlap is precisely the outage described at the top.
- Publish the new public key in the JWKS alongside the current one. Keep signing with the old key. Validators now have both keys in cache.
- Wait at least one full cache lifetime so every validator has had the chance to pick up the new key. This is the step teams skip when they are in a hurry.
- Start signing with the new key. Tokens now carry the new
kid; validators already have the matching public key, so verification succeeds. - Keep the old public key published until every token signed with it has expired. Only then remove it.
The invariant: a public key must appear in the JWKS before any token references it and must stay there until no live token references it anymore. Both ends of that window matter.
kid for a new key. If you rotate a key but keep the same kid, caches holding the old public key under that ID will silently fail to verify tokens signed with the new one, and nothing will tell you which key is stale. Make kid values unique forever — a date plus a random suffix works well.kid selection on the validator side
A robust validator does not assume there is exactly one key. It reads the token header's kid, finds the matching key in the set, and verifies against that one.
import { createRemoteJWKSet, jwtVerify } from 'jose';
// createRemoteJWKSet handles caching, 304s, and refetch-on-unknown-kid
const JWKS = createRemoteJWKSet(
new URL('https://auth.example.com/.well-known/jwks.json'),
{ cooldownDuration: 30_000, cacheMaxAge: 600_000 }
);
async function verify(token: string) {
const { payload } = await jwtVerify(token, JWKS, {
issuer: 'https://auth.example.com',
audience: 'billing-api',
algorithms: ['RS256'], // pin the algorithm
});
return payload;
}Two non-negotiables in that call. First, pin algorithms — never let the token's own header choose, or you reopen algorithm-confusion attacks where a token claims alg: none or swaps RSA for HMAC. Second, if the token has no kid and your set has more than one key, reject it rather than guessing; ambiguity here is a correctness bug waiting to become a security one.
Operational guardrails
- Serve over HTTPS only. The JWKS is the root of trust for every verification; an attacker who can MITM it can substitute their own keys and forge tokens.
- Make it highly available. Treat it as tier-0 infrastructure. A static CDN origin with a short TTL is often more reliable than serving it dynamically from the auth service.
- Alert on fetch failures and unknown-kid spikes. A surge of unknown-
kiderrors is the early warning that a rotation went wrong or a validator's cache is wedged. - Keep the key list small. Two keys during overlap, one the rest of the time. A JWKS that accumulates a dozen stale keys is a sign rotation cleanup is not happening.
The endpoint is a contract
Once other teams point their validators at your JWKS, its behavior — the cache headers, the overlap discipline, the stability of kid values — becomes a contract you cannot break without breaking them. That is exactly why it belongs to infrastructure you control end to end: when you run the authorization server, you set the rotation cadence, the cache policy, and the key lifetimes to match your own risk tolerance, instead of discovering a hosted provider's rotation schedule the hard way during an incident.
Run it yourself
Bastionary is free, open-source software. Follow the quick start to have it running on your own server, or browse the releases on Git.