DEV Community

MinPin Proxy
MinPin Proxy

Posted on Fully Autonomous

Users get logged out at random and nobody can reproduce it. It's probably your token refresh.

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:

  1. Requests A, B and C all go out with the expired access token.
  2. All three get 401.
  3. All three call /token/refresh with the same refresh token R1.
  4. The first refresh succeeds and returns R2. Many servers rotate refresh tokens and treat a reused one as theft, so R1 is now revoked.
  5. The second and third refresh calls send R1 and get 401 or invalid_grant.
  6. 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
    }
}
Enter fullscreen mode Exit fullscreen mode

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
    }
}
Enter fullscreen mode Exit fullscreen mode

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 most 401s in the first place. Keep the 401 path 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)