Skip to content

fix(async): synchronize token refresh to avoid race condition (#708) - #710

Closed
pranavv00 wants to merge 3 commits into
marcospereirampj:masterfrom
pranavv00:master
Closed

pranavv00 wants to merge 3 commits into
marcospereirampj:masterfrom
pranavv00:master

Conversation

@pranavv00

Copy link
Copy Markdown

Summary

Fixes a race condition where concurrent async calls could trigger multiple redundant token refresh requests.

When multiple coroutines executed simultaneously (e.g., via asyncio.gather), they all passed the token expiry check and independently called the refresh endpoint, resulting in N duplicate refresh requests.


Solution

Introduced an asyncio.Lock to synchronize token refresh:

  • Ensures only one coroutine performs the token refresh
  • Other coroutines wait for the refresh to complete
  • Added a double-check inside the lock to avoid unnecessary refresh if another coroutine already updated the token

Example (Before vs After)

Before

await asyncio.gather(*[admin.a_get_realms() for _ in range(10)])

→ 10 token refresh requests ❌

After

→ 1 token refresh request ✅
→ Remaining calls reuse refreshed token


Safety & Scope

  • ✅ No changes to public APIs
  • ✅ No changes to existing behavior (except eliminating redundant refresh calls)
  • ✅ Fully async-safe (no blocking operations introduced)
  • ✅ Minimal and localized change

Notes

This follows a standard concurrency control pattern for async systems to prevent race conditions during shared resource updates.

Happy to adjust if there’s a preferred synchronization approach.

@pranavv00 pranavv00 closed this by deleting the head repository Jun 13, 2026
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.

1 participant