How to Handle Concurrent 401 Responses With One Token Refresh on Android
Coordinate concurrent Android HTTP 401 failures with one in-flight refresh per session and generation, and only replay eligible requests.
Table of Contents9 sections

Four Android API calls leave with the same access token. All four get an HTTP 401. Refreshing once per response turns one expired session into a burst of token requests and can make the client race against its own rotated credentials.
Quick solution:
Give each sign-in session one refresh coordinator. If another request already replaced the failed token, reuse the newer credentials from that same session. Otherwise, join one in-flight refresh. Retry an eligible original request at most once, and never let a late result restore a signed-out session.
Four 401 responses for session S, token generation 8
One refresh for S/8 → commits credentials for S/9
Eligible requests use S/9 once; another 401 ends recovery
The example assumes an app talking to its own documented OAuth bearer-token API. Login and authorization policy still belong to the server.
Check whether the response actually calls for refresh
Start with the failed request and the response challenge. For an API using the bearer-token convention, RFC 6750 section 3.1 describes an invalid token as a case where the client can request a new token and retry. It also describes insufficient scope separately. A missing permission doesn’t turn into permission because the app refreshes more often. Rate limits, transient server errors, and login or token-endpoint failures also should not be routed to the ordinary resource-request refresh handler.
An HTTP status alone is not always enough. Your service might distinguish session expiration, a disabled user, a tenant mismatch, and a different authentication scheme through the response challenge or documented error codes. Refresh only when the failed request carried credentials for the intended resource and the result meets that contract. Use the service’s specified issuer, client, and account context. Keep tokens confined to the intended service; don’t attach a new Authorization header to an arbitrary redirected host or run the logic for unauthenticated endpoints.
This situation can occur even when the app’s feature calls are correctly parallel. Parallelizing independent Android refreshes is about coordinating reads and making their errors visible. Here the shared resource is different: several otherwise independent requests may all depend on one session and one safe way of advancing its credentials. They can stay parallel for normal reads while recovering through a shared authentication path.
Record the sign-in instance and token generation
When sending a request, keep a non-secret reference to which sign-in instance and credential generation it used. Use a session identity that changes on sign-out and on a new login, even when the same account signs back in. Use a generation or comparable version that changes when the credential pair is replaced. These identifiers help the app compare state without treating raw bearer tokens as log keys.
Suppose request A used generation 8 and failed first. The coordinator refreshes and publishes generation 9. If the response for request B arrives a moment later and still represents generation 8, B should not start a generation 9 refresh just because its own response says 401. It should verify that the active session is still the one it used and, if replay is allowed, send using generation 9. If the app switched accounts since B started, there is no valid replay. Do not substitute the credentials that happen to be current for an older request tied to a different session.
Store the access and refresh credentials as a consistent pair using the app’s credential store and security policy. With refresh-token rotation, advancing the access token while leaving an old refresh token behind can appear to work until the next refresh. OAuth Security Best Current Practice discusses rotation and replay detection. It is a reason to coordinate the legitimate client’s concurrent attempts, not a reason to disable rotation or weaken provider protections.
Share one in-flight result, not just a lock
A common first fix is to protect the refresh call with a lock. A lock without a second state check only makes refreshes sequential; it doesn’t stop the second waiter from making another request after the first is over. Another design keeps a shared future or deferred result. Under a short state lock, check the current credentials, look up the in-flight result for the failed generation, or reserve one. Release the lock before doing network I/O, then publish the result to the reserved flight.
In a Kotlin coroutine implementation, a Mutex can protect short suspending-critical-section access to the coordinator’s state. It does not make a network timeout go away, nor does it protect a second process using its own coordinator. If more than one process can refresh the same stored credentials, design a single owner or an appropriate cross-process strategy before relying on the in-memory invariant. The simplest app architecture usually sends all ordinary authenticated requests through one coordinator per active session.
The following is pseudocode for the state decision. The atomic success path, timeout handling, and endpoint contract are called out separately because they can’t safely be inferred from a bare refresh response.
inside coordinator lock:
if active session differs from the request: return SESSION_CHANGED
if original request has already been replayed: return STOP
if active generation advanced: return CURRENT_CREDENTIALS
if a flight exists for this session and generation: join it
if a temporary failure is still in cooldown: return TRY_LATER
otherwise reserve one flight owned and started by the coordinator
outside coordinator lock:
await the shared flight
recheck session identity before replaying an eligible request
The flight needs a lifetime that is not owned by the first screen to encounter the error. If that screen closes, its own waiter can stop, but other requests waiting for the same result should not all be cancelled as collateral damage. At the same time, sign-out should invalidate the flight for that session. Close or detach it as appropriate, discard any stale completion, and make sure waiters resolve rather than hanging behind a cleared entry.
Keep refresh traffic separate from ordinary recovery
Send the refresh request only through the app’s documented token flow. It must not re-enter the same handler that is waiting for that request to complete. Keep authentication recovery off the token endpoint, even if the same networking stack is used, and avoid a configuration where requests waiting for refresh consume the capacity that refresh itself needs. An isolated refresh path with its own bounded request timeout makes both things easier to reason about.
Make errors meaningful rather than normalizing them all to “log in again.” A definitive provider rejection of the refresh credential is different from an offline device, timeout, or temporary server outage. Decide which provider results actually expire the active session. When the outcome is temporary, finish the shared flight for everyone and bound when another attempt is allowed. Otherwise four requests that wait correctly on one failed flight may still trigger four rapid attempts one after another. A new request after backoff is a new recovery opportunity, not a reason to keep the original group waiting indefinitely.
A lost token response is an important special case: the server may have accepted the refresh and advanced rotating credentials before the response was lost. Do not assume the old refresh token is reusable just because the client saw a timeout. Follow the provider’s documented behavior for an uncertain response. If the provider doesn’t offer safe recovery, a fresh sign-in can be more appropriate than repeatedly submitting old credentials. The rule about sharing one in-flight attempt helps contain the failure; it cannot solve an ambiguous remote outcome on its own.
Commit credentials only if the original session still owns the flight
On success, the coordinator should publish the credential pair only if the same sign-in instance and expected generation still own the flight. Make the comparison and publication part of the same state update. A check followed by an unrelated write can still race with account switching. Wake waiters only after the new pair is available for them to use. If persistence fails, do not claim durable recovery. The provider may have rotated the old credential already; use the app’s documented recovery path rather than silently persisting only half of the replacement.
Consider a refresh for account A started just before the user signs out and then signs in as account B. The successful network response for A is not authority to overwrite B’s credential store or fetch B’s data using A’s old request. Discard it when the session reference has changed. If failure handling clears credentials, it needs the same ownership check. A late error for A must not clear B’s session either.
There can also be a race between receiving credentials and resending the business request. Build replay through the same session-aware request path and check the originating identity again. Never assume that a passed state check held across later suspension or asynchronous dispatch. Cancel or suppress session-specific results after logout according to the app’s architecture. This is particularly important for screens that stay mounted while account state changes: success inside an HTTP stack must not become permission to render the old user’s results.
Replay cautiously and stop on a second authentication failure
Separate access-token recovery from the business decision to resend the original request. A read-only request with a repeatable body or no body is usually straightforward under your API’s contract. A write that creates an order, changes a setting, or sends a message should have an explicit policy. Only automatically replay a non-idempotent operation if the service supplies a dependable guarantee about that operation, such as documented deduplication using the same idempotency identifier, or a definitive guarantee that the first attempt wasn’t applied. A body you cannot safely reconstruct is another reason to stop.
HTTP Semantics, RFC 9110 distinguishes idempotent requests and gives conditions for automatic retries of non-idempotent ones. The engineering takeaway here is to decide from the real endpoint semantics, not merely how easy it is to copy a request object. A request marked safe for replay should retain its original operation identity. Never generate a different idempotency identifier just because the Authorization header changed.
Bound the recovery to one replay of the original logical request per failure path. A second eligible-looking 401 after replay may signal a server policy problem, a different challenge, or another invalid credential. Return it to the appropriate error handling rather than starting an unbounded loop. Likewise, if your stack already applies retries below this layer, count or tag the authentication replay explicitly so one layer doesn’t accidentally undo the other’s limit.
Test with simultaneous failures and a late response
In a fake environment for your own client, place a barrier before the requests receive their first response. Start four reads with the same session and generation, release all four failures together, and hold the fake token response until the requests have joined the coordinator. Then return one new credential pair. Verify exactly one refresh call and at most one replay per eligible read. This test is more precise than sleeping between launches and hoping the responses overlap.
| Case | What to assert |
|---|---|
| Four eligible reads get 401 for generation 8 | One refresh for that generation and eligible replays use generation 9 |
| Late 401 for generation 8 arrives after generation 9 is active | No second refresh just for the late result |
| User signs out or switches accounts while refresh runs | No old credential write and no replay in the new session |
| Temporary failure ends the shared flight | All waiters finish; cooldown prevents an immediate follow-on burst |
| Definitive rejection arrives for the active session | Sign-in requirement is surfaced once |
| Unsafe write or one-shot body is not replayable | It isn’t automatically sent again |
| Replay gets another 401 | Original request reaches the retry limit |
| One waiter is cancelled while others remain | Other eligible callers can still receive the shared result |
Also test a rotated token pair after restart and a persistence failure immediately after the provider returns success. Neither can be validated by counting network calls alone. Use synthetic credentials and record only safe telemetry such as counts, timing, failure categories, and retry decisions. Real Authorization headers, token endpoint payloads, and raw credential-store values don’t belong in logs or test artifacts.
Keep the production rule simple enough to review
Write down which responses trigger refresh, who owns the flight, and what conditions permit replay. Then ask the team to explain the logout race, the timeout case, and how non-idempotent calls are handled. Those answers reveal more than the choice of concurrency primitive.
- Associate every authenticated request with its actual sign-in instance and generation.
- Coordinate one refresh in flight, share the outcome, and apply bounded retry policy.
- Route token requests outside ordinary recovery and recheck ownership on completion.
- Persist replacements as a pair and do not resurrect closed sessions.
- Replay only eligible requests, with their original operation identity, at most once.
- Test concurrency deterministically and keep secrets out of telemetry.
The win is not that every 401 becomes a success. It’s that overlapping requests get one coherent recovery decision, and genuine authorization or sign-in failures still reach the user without loops or duplicate actions.
You Might Also Like
View all articles
How to Handle Partial Success in Android ViewModels
A practical pattern for Android mutations that succeed before a follow-up refresh fails, without lying to the user or turning Compose callbacks into orchestration code.

Parallelize Independent Android Refreshes with Coroutines
Learn when Android repository calls can run concurrently, how structured concurrency changes failure behavior, and how to test parallel refreshes safely.

Upload Photos from Android to Google Drive Safely
Design a reliable Android photo upload flow for Google Drive with explicit ownership, narrow OAuth scope, stable folder IDs, retries, and observable upload state.