Composite operations (multi-resource) in Rest API - Time & Space Complexity
When a REST API performs multiple resource calls in one operation, the total time depends on all those calls combined.
We want to know how the total work grows as we add more resources to handle.
Analyze the time complexity of the following code snippet.
async function compositeOperation(resources) {
const results = [];
for (const resource of resources) {
const response = await fetch(`/api/${resource}`);
const data = await response.json();
results.push(data);
}
return results;
}
This code fetches data from multiple API endpoints one after another and collects the results.
- Primary operation: Fetching each resource from the API.
- How many times: Once for each resource in the input list.
Each additional resource adds one more fetch call, so the total work grows directly with the number of resources.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 fetch calls |
| 100 | 100 fetch calls |
| 1000 | 1000 fetch calls |
Pattern observation: The total work increases in a straight line as more resources are added.
Time Complexity: O(n)
This means the total time grows proportionally with the number of resources we fetch.
[X] Wrong: "Fetching multiple resources at once is always faster and takes constant time."
[OK] Correct: Each resource still requires a separate fetch call, so total time grows with how many resources there are, even if done sequentially.
Understanding how multiple API calls add up helps you design efficient systems and explain your reasoning clearly in interviews.
"What if we changed the code to fetch all resources in parallel instead of one by one? How would the time complexity change?"