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 .…