Why advanced patterns solve real problems in Rest API - Performance Analysis
When using advanced patterns in REST APIs, it is important to understand how they affect the time it takes for the API to respond.
We want to know how the work grows as the API handles more data or requests.
Analyze the time complexity of the following REST API handler using advanced patterns.
async function getUserPosts(userId) {
const user = await db.findUserById(userId);
const posts = await db.findPostsByUser(userId);
const comments = await Promise.all(posts.map(post => db.findCommentsByPost(post.id)));
return { user, posts, comments };
}
This code fetches a user, their posts, and comments on each post using asynchronous calls and mapping.
Look for repeated actions that take time.
- Primary operation: Fetching comments for each post inside a map.
- How many times: Once for each post the user has.
As the number of posts grows, the number of comment fetches grows the same way.
| Input Size (posts) | Approx. Operations |
|---|---|
| 10 | 10 comment fetches |
| 100 | 100 comment fetches |
| 1000 | 1000 comment fetches |
Pattern observation: The work grows directly with the number of posts.
Time Complexity: O(n)
This means the time to complete grows in a straight line as the number of posts increases.
[X] Wrong: "Using advanced patterns always makes the API slower because it adds more steps."
[OK] Correct: Advanced patterns often organize work better, making it easier to handle more data efficiently, not necessarily slower.
Understanding how advanced patterns affect time helps you explain your design choices clearly and confidently in real projects.
"What if we fetched comments in batches instead of one by one? How would the time complexity change?"