Chain multiple Alamofire requests
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
Chaining Alamofire requests means one network call depends on data from a previous one, such as fetching a user profile first and then loading that user’s orders. The main engineering goal is to keep the flow linear, fail early, and avoid turning networking code into nested callback pyramids.
Start With the Dependency Graph
Before writing code, decide whether the requests are truly sequential. Some chains are unavoidable because request two needs an identifier or token returned by request one. Others can start in parallel once the first call completes.
That distinction affects both readability and performance.
Callback Chaining Works, but It Scales Poorly
The classic Alamofire style uses completion handlers.
This is acceptable for one or two steps, but it gets harder to maintain as the chain grows.
Prefer async and await for New Code
Modern Swift concurrency makes dependent requests read like straight-line code.
This is usually the clearest form because error propagation becomes natural and you do not need nested completion handlers.
Keep Authentication Chains Isolated
A common chain is token refresh followed by a protected resource request. Do not spread token logic across view controllers or screens.
A dedicated networking or auth service makes this flow easier to test and change later.
Run Independent Follow-Up Requests Concurrently
Once the initial dependency is satisfied, later requests may not need to wait on each other.
This keeps the logical dependency while avoiding unnecessary serial latency.
Test the Chain as a Service, Not Inside the UI
Networking orchestration belongs in a service layer, not directly in a view controller. That way you can mock the service in UI tests and mock lower-level clients in unit tests.
Keep the chain’s responsibilities narrow:
- request ordering
- decoding
- error propagation
- optional retry policy
The UI should mostly react to success or failure, not orchestrate transport details.
Common Pitfalls
The biggest mistake is deeply nesting callbacks when the codebase already supports async and await.
Another issue is treating every sequence as strictly serial even when some follow-up calls could run concurrently.
A third problem is mixing token refresh, decoding, retry, and screen-state updates all in one method, which makes failure handling hard to reason about.
Summary
- Chain Alamofire requests only where data dependencies actually require it.
- Callback chaining works, but
asyncandawaitis usually clearer for new code. - Keep token-refresh logic in a dedicated service.
- Run independent follow-up requests concurrently after the required first step.
- Put request orchestration in a service layer rather than directly in UI code.

