Skip to content

fix: Lock while generating the Security Key#73

Merged
brunobritodev merged 4 commits into
NetDevPack:masterfrom
febinkdominic:fix/lock-while-generating-code
Jul 16, 2026
Merged

fix: Lock while generating the Security Key#73
brunobritodev merged 4 commits into
NetDevPack:masterfrom
febinkdominic:fix/lock-while-generating-code

Conversation

@febinkdominic

@febinkdominic febinkdominic commented Jun 30, 2026

Copy link
Copy Markdown
Contributor

Fixes duplicate key generation when a scoped JwtService rotates keys concurrently across requests #65

  • Added a process-wide SemaphoreSlim RotationLock in JwtService so concurrent requests rotate the current key once, not once per request.
  • GetCurrentSecurityKey now double-checks under the lock before revoking + generating.

Fixes duplicate key generation when a scoped JwtService rotates keys concurrently across replicas

  • Issue: When run on multiple pods (Kubernetes), the pods independently generate new keys and cache the last two keys. On a cluster with 3 replicas with AlgorithmsToKeep = 2, all three generate new keys and cache different pairs of keys.

  • Fix: Use the previous valid key's Id, and increment it, and use that to generate the GUID of the new key - Every instance generates the same GUID and tries to insert, the database fails one of the inserts acting as the coordinator.

  • Cross-replica coordination only works on EF Core store - Database is used as the coordinator when multiple replicas race.

  • EF Core store: computes a deterministic Id from SHA256(use:kty:version) so concurrent inserts collide on the primary key. On collision/transient fault it detaches its own entity, re-reads the winner, and returns it (throws only if no winner exists).

  • InMemoryStore, DataProtectionStore, FileSystemStore updated to the new signatures.

  • Changed caching from Sliding to Absolute. When a key is revoked, the key gets refreshed after the cache expires instead of renewing the stale cache.

@brunobritodev
brunobritodev marked this pull request as ready for review July 16, 2026 15:11
@brunobritodev brunobritodev reopened this Jul 16, 2026
@brunobritodev
brunobritodev merged commit 2423b41 into NetDevPack:master Jul 16, 2026
0 of 5 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants