Skip to content

Optimize Token Refresh Synchronization in RefreshTokenDelegatingHandler to Reduce Unnecessary Lock Contention #127

@BartoGabriel

Description

@BartoGabriel

The current implementation of RefreshTokenDelegatingHandler uses a SemaphoreSlim to synchronize access to the access and refresh tokens. This synchronization strategy results in every token read being subjected to a lock, potentially leading to performance bottlenecks in high-concurrency environments.

Suggested Enhancements

To address these issues, two main enhancements are proposed:

  1. Implement ReaderWriterLockSlim for Token Access: Replace the SemaphoreSlim with a ReaderWriterLockSlim, which allows multiple concurrent reads of the access token without blocking, while still ensuring that token writes (refreshes) are exclusive and thread-safe. This change could significantly improve read performance by reducing contention.
    Potential Issue with ReaderWriterLockSlim: While this approach reduces read contention, it may still lead to multiple queued write requests if many threads simultaneously detect an expired token.

  2. Single Active Refresh Operation: Implement a mechanism that ensures only one refresh operation is queued or in progress at a time. This could be achieved by:

    • Introducing a timestamp or flag that marks the initiation of a refresh operation.
    • Before entering a write lock to refresh the token, check whether another thread has already started the refresh process.
    • If a refresh is in progress, other threads should wait or poll until the refresh is completed before retrying their requests with the new token.

Benefits

  • Improved Read Performance: By allowing multiple concurrent reads, applications can achieve lower latency and better scalability.

Metadata

Metadata

Assignees

Labels

impact/non-breakingThe fix or change will not be a breaking one

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions