fix: Prevent hundreds of keys from being created with eventually consistent storage #323
+249
−2
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Fixes #322
Problem
When deploying to Cloudflare Workers with an empty KV store, the initial request to
/.well-known/jwks.jsonwould create hundreds of signing and encryption keys, causing subsequent requests to take 15-20 seconds and eventually crash.This issue was triggered by Cloudflare's KVs eventual consistency behavior.
Root Cause
The
signingKeys()andencryptionKeys()functions had a race condition with eventually consistent storage:Why this works:
Testing
Added comprehensive tests in test/keys.test.ts that:
Test results:
Trade-offs
Potential for 2 keys with concurrent requests:
if two requests hit an empty storage at exactly the same time, both might create a key (2 total instead of 1). This is acceptable because:
Migration Notes
No breaking changes. Existing deployments with keys in storage will continue to work normally. Only affects the initial key generation when storage is empty.