Menu

1 / 2

Single-Flight Token Refresh in Swift with Alamofire

DEV Community: swift·Raaju Pahlowan·11 days ago
#2IZKmMeo
#devtoswift#devto#dev#refresh#task
Long article (922 words) — no AI summary yet.
Reading 0:00
15s threshold

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

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.