Leveraging Alamofire Interceptors in iOS: A Real-World Case Study
Article Summary
Bevan Christian uncovered why users were mysteriously logged out of a major startup's iOS app for years. The culprit? A homegrown token refresh mechanism that created race conditions nobody noticed.
This IDN Engineering case study walks through a real debugging journey in an iOS app using Alamofire. The author discovered that a custom refresh token implementation with a shared singleton was causing unexpected logouts when users made rapid API requests to different endpoints.
Key Takeaways
- Custom token refresh used boolean flag causing race conditions across endpoints
- Singleton NetworkService shared state triggered premature forceUserRelog on concurrent requests
- Alamofire's RequestInterceptor centralizes refresh logic in adapt() and retry() methods
- Adding .validate() triggers interceptor retry only for non-2xx status codes
- Interceptor automatically retries failed requests after successful token refresh
Replacing custom token refresh logic with Alamofire's built-in RequestInterceptor eliminated years of mysterious user logouts by properly handling concurrent API requests.
About This Article
Bevan Christian's team found a bug in their token refresh mechanism. A shared boolean flag called hasBeenError lived in a Singleton NetworkService. When concurrent requests hit different endpoints, the flag would get stuck as true, which triggered unexpected forceUserRelog calls.
The team switched to Alamofire's RequestInterceptor protocol instead. They added .validate() to catch non-2xx status codes and built out the adapt() and retry() methods. This centralized the token refresh logic and let requests automatically retry with fresh tokens.
Moving away from the custom boolean flag to Alamofire's RequestInterceptor fixed a long-standing issue where users would get logged out unexpectedly. The new approach handles concurrent API requests properly without race conditions or needing manual retries.