API analytics and usage metrics in Rest API - Time & Space Complexity
When tracking API usage and analytics, it is important to understand how the time to process data grows as more requests come in.
We want to know how the system handles increasing amounts of usage data efficiently.
Analyze the time complexity of the following code snippet.
// Example: Counting API calls per user
function countApiCalls(requests) {
const counts = {};
for (const req of requests) {
counts[req.userId] = (counts[req.userId] || 0) + 1;
}
return counts;
}
This code counts how many API calls each user has made from a list of requests.
- Primary operation: Looping through each API request once.
- How many times: Exactly once for each request in the input list.
As the number of API requests grows, the time to count calls grows in a similar way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 steps |
| 100 | About 100 steps |
| 1000 | About 1000 steps |
Pattern observation: The work grows directly with the number of requests, so doubling requests doubles the work.
Time Complexity: O(n)
This means the time to count API calls grows in a straight line with the number of requests.
[X] Wrong: "Counting API calls takes the same time no matter how many requests there are."
[OK] Correct: The code must look at each request once, so more requests mean more work and more time.
Understanding how API usage data scales helps you design systems that handle growing traffic smoothly.
"What if we also needed to find the top user with the most API calls? How would the time complexity change?"