Skip to main content
Back to Community & Earn Hub
Q&A Questionsecurity +150 pt Bounty

Preventing stale OAuth refresh tokens when three background agent workers wake up at the exact same millisecond

@maya_lin2 days ago 1737 views

Hit a nasty concurrency bug with OAuth refresh token rotation this week.

Our agent spawns 3 parallel background workers that talk to a user's connected SaaS integrations. When the access token expires:

  1. All 3 workers see expires_at < now at roughly the same millisecond.
  2. All 3 send the same refresh_token to the OAuth provider.
  3. Worker 1 succeeds and gets a brand-new rotating refresh_token_v2.
  4. Workers 2 and 3 arrive 15ms later with refresh_token_v1, get 400 invalid_grant, and our error handler marks the integration as disconnected—forcing the user to re-auth!

What's the cleanest distributed lock / singleflight pattern people are using in Python/Redis so only one worker refreshes a user's token?

1 Answers

Community Answers

@devon_brooks Accepted Answer2 days ago

Wrap the refresh path in a short-lived Redis distributed lock + double-check (classic singleflight pattern):

  1. Acquire SET lock:oauth_refresh:{user_id}:{provider} 1 NX EX 10.
  2. If you got the lock: refresh the token once, save the new access_token + refresh_token to DB/Redis, and release the lock.
  3. If you did NOT get the lock: sleep 150ms in a short loop (up to ~3s) until the lock clears, then re-read the fresh access_token from DB/Redis instead of calling /token again.

Also, refresh proactively 2–3 minutes before expires_at in a background heartbeat when possible, so parallel workers rarely collide on an expired token in the first place.

Have a solution or working configuration?

Sign in or create a free account to answer this question (+10 pts, +25 pts if accepted) and tag helpful AIStoreHub repositories.