The bug report says "the app logged me out for no reason". It happens a few times a week across all users, never on a developer's phone, and the logs show nothing useful. Most of the time the cause is the same: two requests refreshed the access token at the same moment.
How the race happens
A typical setup: a short-lived access token (say 15 minutes) and a long-lived refresh token. When a request gets a 401, the client calls /token/refresh, saves the new tokens and retries.
Now open a screen that fires three requests at once after the access token has expired:
- Requests A, B and C all go out with the expired access token.
- All three get
401. - All three call
/token/refreshwith the same refresh tokenR1. - The first refresh succeeds and returns
R2. Many servers rotate refresh tokens and treat a reused one as theft, soR1is now revoked. - The second and third refresh calls send
R1and get401orinvalid_grant. - The client sees "refresh failed" and logs the user out. Or it saves whichever response came back last, overwriting the good token with an error.
On a fast office network the three 401s arrive a few milliseconds apart and the refreshes often happen to line up harmlessly. On a phone that just woke up on cellular, they don't.
Why it's hard to see
- It needs an expired token, which developers rarely have because they restart the app all the time.
- It needs two or more requests in flight, which depends on the screen.
- Refresh token rotation, the thing that makes the race fatal, is a server setting the mobile team may not know about.
To reproduce it on purpose, shorten the access token lifetime in a dev environment to 30 seconds, open the busiest screen, wait 40 seconds and pull to refresh. Watch the requests: if you see more than one call to the refresh endpoint, you have the race.
The fix: one refresh at a time
Every request that hits a 401 should wait for a single shared refresh, then retry with the new token.
Swift, with an actor:
actor TokenRefresher {
private var refreshTask: Task<Tokens, Error>?
func validTokens(refreshingFrom stale: Tokens) async throws -> Tokens {
if let task = refreshTask {
return try await task.value
}
let task = Task { try await api.refresh(using: stale.refreshToken) }
refreshTask = task
defer { refreshTask = nil }
let tokens = try await task.value
try store.save(tokens)
return tokens
}
}
Kotlin, with a Mutex:
class TokenRefresher(private val api: AuthApi, private val store: TokenStore) {
private val mutex = Mutex()
suspend fun refreshIfNeeded(failedWith: String): String = mutex.withLock {
val current = store.accessToken()
if (current != failedWith) return current // someone else already refreshed
val tokens = api.refresh(store.refreshToken())
store.save(tokens)
tokens.accessToken
}
}
The Kotlin version shows a detail that matters: compare the token the request failed with against the current one. If they differ, another request already refreshed, so just retry with the new token. OkHttp's Authenticator is the usual place to call this. It runs on OkHttp's own thread and isn't a suspend function, so call the refresher with runBlocking there.
Details that still bite
- Only log out on a definite answer. A refresh that fails with a timeout or a 5xx should leave the tokens alone and show an error. Log out only when the server says the refresh token itself is invalid.
- Save atomically. Write the access and refresh token together. A crash between two writes leaves a new access token next to an old refresh token.
-
Refresh before expiry. If the token carries an
exp, refreshing 30-60 seconds early removes most401s in the first place. Keep the401path anyway, since clocks drift. - Several processes. A widget, a share extension or a background task can refresh too. They need the same lock, or a shared store they re-read before refreshing.
- Server grace period. Some auth servers accept the previous refresh token for a few seconds after rotation. That hides the bug instead of fixing it, but it's a useful safety net.
Checking the fix
Use the same 30-second token lifetime, open the busiest screen after expiry, and count the calls to the refresh endpoint in a network capture. It should be exactly one, followed by retries of every request that failed.
This article was created with the help of AI.
Top comments (0)