If your iOS app talks to a REST API with expiring tokens, you will eventually hit this bug: the access token expires, five requests fire at once, all five get a 401, and all five try to refresh the token. The server sees five refresh calls. Depending on how your backend rotates refresh tokens, the second call can invalidate the first and log your user out for no reason.
The fix is called single-flight refresh: no matter how many requests fail at once, only one refresh call runs, and everyone else waits for its result. Here is how I approach it with Alamofire's RequestInterceptor and Swift concurrency.
1. Guarantee only one refresh with an actor
An actor gives us thread safety for free. We store the in-flight refresh as a Task, and every caller awaits the same one.
swift
actor TokenRefresher {
private var refreshTask: Task<String, Error>?
func freshToken(using refresh: @escaping () async throws -> String) async throws -> String {
if let task = refreshTask {
return try await task.value // join the refresh already running
}
let task = Task { try await refresh() }
refreshTask = task
defer { refreshTask = nil } // allow a new refresh later
return try await task.value
}
}
The first caller starts the task. Anyone arriving while it runs awaits the same task and receives the same new token.
2. Plug it into an Alamofire interceptor
The interceptor does two jobs: attach the token to each request (adapt), and react to a 401 by refreshing and retrying (retry).
swift
final class AuthInterceptor: RequestInterceptor {
private let tokenStore: TokenStore
private let refresher = TokenRefresher()
init(tokenStore: TokenStore) { self.tokenStore = tokenStore }
func adapt(_ urlRequest: URLRequest,
for session: Session,
completion: @escaping (Result<URLRequest, Error>) -> Void) {
var request = urlRequest
if let token = tokenStore.accessToken {
request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
}
completion(.success(request))
}
func retry(_ request: Request,
for session: Session,
dueTo error: Error,
completion: @escaping (RetryResult) -> Void) {
guard request.response?.statusCode == 401, request.retryCount < 1 else {
return completion(.doNotRetry)
}
Task {
do {
let newToken = try await refresher.freshToken {
try await self.tokenStore.refreshFromServer()
}
self.tokenStore.accessToken = newToken
completion(.retry)
} catch {
completion(.doNotRetryWithError(error))
}
}
}
}
Two details matter here:
request.retryCount < 1 stops an endless loop if the new token is also rejected.
If the refresh itself fails, you should treat the session as ended and send the user to the login screen.
3. Store tokens in the Keychain, not UserDefaults
Access and refresh tokens are credentials, so keep them in the Keychain. A small TokenStore wrapper keeps the interceptor clean and makes it easy to swap in a fake store for tests.
4. Refresh before expiry by reading the JWT
If your tokens are JWTs, you can avoid many 401s by checking the exp claim before sending a request, and refreshing early.
swift
func isExpiringSoon(_ jwt: String, leeway: TimeInterval = 60) -> Bool {
let parts = jwt.split(separator: ".")
guard parts.count == 3 else { return true }
var base64 = String(parts[1])
.replacingOccurrences(of: "-", with: "+")
.replacingOccurrences(of: "_", with: "/")
while base64.count % 4 != 0 { base64 += "=" }
guard let data = Data(base64Encoded: base64),
let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
let exp = json["exp"] as? TimeInterval else { return true }
return Date(timeIntervalSince1970: exp).timeIntervalSinceNow < leeway
}
Call it in adapt, and if it returns true, go through the same TokenRefresher before attaching the token. Because both paths share one refresher, a proactive refresh and a reactive one can never run twice at the same time.
5. Add a feature flag and a test harness
Authentication code touches every request in your app, so I wrap it in a feature flag. If something goes wrong in production, you can turn the new logic off without shipping a new build. I also write a small test harness that fires many parallel requests with an expired token and checks that the refresh endpoint is called exactly once. It is the quickest way to prove the single-flight behavior works.
Wrapping up
Single-flight refresh comes down to three ideas: one shared task, a retry limit, and secure token storage. With an actor and Alamofire's interceptor, the whole thing fits in about fifty lines of Swift.
I'm Raaju Pahlowan, an iOS developer in Dhaka, Bangladesh, working with Swift, SwiftUI and UIKit. You can see my projects at raajupahlowan.github.io and connect with me on LinkedIn.

