skip to content

In a mobile wallet app, five in-flight calls all get 401 when the access token expires; how does the client refresh once and replay them?

level: middleimportance: must knowfreq 60%

answer

  1. one gate, many waiters
  2. remember which token each call carried
  3. store the new refresh token first
  4. two refreshes can look like token theft
  5. invalid_grant means signed out

basics

~20 s

Route every 401 through one shared refresh gate: the first caller starts the refresh, the rest wait for its result, then each replays once with the new token. A refresh failing with invalid_grant fails them all and signs out.

solid answer

~50 s

The auth step of the pipeline keeps a single shared refresh task. When a call gets `401`, it checks which token it was sent with: if a newer one already exists it just replays; otherwise it joins the in-flight refresh or starts it if none is running. Exactly one request goes to the token endpoint, the new access and refresh tokens are stored together before anyone uses them, and every waiter replays its call once. Refreshing once matters beyond saving a round trip: installed apps are public clients, so servers commonly rotate their refresh tokens, and a second concurrent refresh presents a token that was just replaced, which the server can read as theft and revoke the whole session. If the refresh returns `invalid_grant`, every waiter fails with a session-ended error and the app goes to signed-out; if it fails on the network, the tokens are kept and the calls fail as retryable.

code

pseudocode · 37 lines
pseudocode
function send(request):
    sentWith = tokens.access
    response = transport(request.withBearer(sentWith))
    if response.status != 401:
        return response
    if request.replayed:
        endSession()
        return error(SESSION_ENDED)
    outcome = freshToken(sentWith)
    if outcome == SIGNED_OUT:
        return error(SESSION_ENDED)
    if outcome == TRANSIENT:
        return error(RETRYABLE)
    return send(request.markReplayed())

function freshToken(sentWith):
    lock:
        if tokens.access != sentWith:
            return REFRESHED
        if inFlight == none:
            inFlight = startRefresh(tokens.refresh)
        task = inFlight
    return await task

function startRefresh(refreshToken):
    reply = postToTokenEndpoint(grant = refresh_token, token = refreshToken)
    if reply.ok:
        tokens.storeTogether(reply.access, reply.refresh or refreshToken)
        result = REFRESHED
    else if reply.error == "invalid_grant":
        endSession()
        result = SIGNED_OUT
    else:
        result = TRANSIENT
    lock:
        inFlight = none
    return result

go deeper

for a junior

Recall the shape: one refresh request for all the calls that failed together, the others wait, and each call is replayed once with the new token.

for a middle

Explain the gate itself: comparing the token a call carried, joining or starting one shared task, storing both tokens before release, and bypassing auth for the refresh call.

for a senior

Demonstrate the rotation hazard, the difference between invalid_grant and a network failure, and why every process holding the credential must share one gate.

for a principal

Weigh where the gate lives when several app processes share a credential, and agree with the server team on rotation grace behaviour so lost refresh responses do not sign users out.

## The situation A wallet app opens its home screen and fires five calls at once: balance, recent transactions, pending requests, saved cards and contacts. The **access token** (the short-lived credential sent on each call) expired a minute ago, so all five come back `401` within milliseconds of each other. Each response carries a `WWW-Authenticate` challenge with `error="invalid_token"`, which the bearer-token rules say the client may fix by getting a new access token and retrying. The naive pipeline lets each failed call refresh on its own. That sends five refresh requests, and on a server that rotates refresh tokens it does real damage, not just extra traffic. ## Why five refreshes are dangerous, not just wasteful An installed app is a **public client**: it cannot keep a client secret, so anyone who extracts its refresh token could use it. The current OAuth security best practice therefore requires refresh tokens for public clients to be either sender-constrained or **rotated**: every refresh returns a new refresh token and invalidates the one presented. The original refresh rules already say that when the server issues a new refresh token, the client must discard the old one. As the security best practice describes it, rotation comes with reuse detection. If an invalidated refresh token is presented again, the server cannot tell the attacker from the legitimate app, so it revokes the active token for that grant. Now replay the five-refresh scenario: on such a server the first refresh succeeds and rotates the token; the other four present the token that was just invalidated; the server sees reuse and revokes the session. The user, who did nothing wrong, is signed out. The rule that prevents this is **single-flight refresh**: at most one refresh in flight for a session, everyone else waits for its result. ## The mechanism 1. **Attach and remember.** The auth step attaches the current access token to each attempt and records which token that was. 2. **On 401, compare.** If the stored token is already newer than the one this call carried, a refresh has happened since it left; replay immediately. 3. **Join or start.** Under a lock, if a refresh task exists, wait on it; if not, create it. Only the creator talks to the token endpoint. 4. **Persist before release.** On success, write the new access token and the new refresh token (or keep the old one if none came back) to storage in one step, then release the waiters. 5. **Replay once.** Each waiter resends its original call with the new token, marked so a second `401` does not trigger another round. 6. **Fail together.** Every waiter receives the same outcome as the refresh. The refresh request itself must bypass the auth step, or a `401` from the token endpoint would try to refresh the refresh. ## Reading the refresh's outcome | Refresh result | What it means | Client reaction | |---|---|---| | Success | new access token, maybe a new refresh token | store both, replay every waiter once | | `invalid_grant` | refresh token expired, revoked or reused | clear tokens, fail waiters as session-ended, show sign-in | | Timeout or `5xx` | outcome unknown or server trouble | keep the tokens, fail waiters as retryable, refresh again later | The `invalid_grant` error covers a refresh token that is invalid, expired or revoked, and nothing the client can do recovers it: the only correct reaction is the signed-out state. A network failure is different. Signing the user out because the token endpoint timed out on a train turns a bad signal into a forced sign-in. ## Edges that decide the design - **One gate per session, across the whole app.** Every caller that holds the credential must share it: foreground screens, a background sync and any second process the app runs, such as a home-screen widget or a background task. Two processes with two gates recreate the race. - **A refresh that dies mid-flight.** If the response with the rotated token is lost, the stored refresh token is now invalid on the server and the next attempt may get `invalid_grant`. A client can only shrink this window by persisting promptly; whether the server tolerates a short grace period is the server's policy. - **Proactive refresh.** Refreshing shortly before expiry, using the token's `expires_in` lifetime counted from when the response arrived, avoids most `401`s. It still goes through the same gate, and reactive handling stays, because a token can be revoked early. - **Writes waiting on a refresh.** A replayed money transfer must reuse its original idempotency key, so the replay cannot pay twice.

  • Why does refresh-token rotation make concurrent refreshes from one mobile app dangerous rather than merely wasteful?
    With rotation, each refresh invalidates the token it presented. A second concurrent refresh therefore presents a token the server just replaced, which is exactly what reuse by a thief looks like. The server cannot tell who is legitimate, so it revokes the session and the real user is signed out. Single-flight refresh keeps the app from ever presenting a rotated token twice.
  • Should a mobile app refresh before the access token expires instead of waiting for a 401?
    It can, and it smooths the common case: count the `expires_in` lifetime from when the token arrived, using the device's elapsed time rather than its wall clock, and refresh a little early through the same single-flight gate. The `401` path must stay anyway, because a token can be revoked before its lifetime ends.
  • The token endpoint times out during a refresh in a mobile wallet app. Should the user be signed out?
    No. A timeout says nothing about the refresh token's validity, so keep the stored tokens, fail the waiting calls as retryable and let the next call try again through the gate. Only an explicit `invalid_grant` from the token endpoint means the grant is gone and the app should move to the signed-out state.

Five hotel guests find their key cards stopped working at the same moment. One goes to the front desk while the others wait in the lobby; the desk reprograms the room and hands back new cards. If all five queued with the old card, the desk would see the same card presented again after it was replaced, suspect a stolen copy and cancel the room for everyone.

  • Let each failed call run its own refresh; extra refreshes only cost bandwidth.
  • Keep using the old refresh token after the server returned a new one.
  • Sign the user out whenever the refresh request fails for any reason.
  • The refresh call can go through the same auth interceptor as every other call.
  • Proactive refresh before expiry removes the need to handle 401 at all.