Preventing stale OAuth refresh tokens when three background agent workers wake up at the exact same millisecond
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:
- All 3 workers see
expires_at < nowat roughly the same millisecond. - All 3 send the same
refresh_tokento the OAuth provider. - Worker 1 succeeds and gets a brand-new rotating
refresh_token_v2. - Workers 2 and 3 arrive 15ms later with
refresh_token_v1, get400 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