0
0
Rest APIprogramming~5 mins

Why advanced patterns solve real problems in Rest API - Performance Analysis

Choose your learning style9 modes available
Time Complexity: Why advanced patterns solve real problems
O(n)
Understanding Time Complexity

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.

Scenario Under Consideration

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.

Identify Repeating Operations

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.
How Execution Grows With Input

As the number of posts grows, the number of comment fetches grows the same way.

Input Size (posts)Approx. Operations
1010 comment fetches
100100 comment fetches
10001000 comment fetches

Pattern observation: The work grows directly with the number of posts.

Final Time Complexity

Time Complexity: O(n)

This means the time to complete grows in a straight line as the number of posts increases.

Common Mistake

[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.

Interview Connect

Understanding how advanced patterns affect time helps you explain your design choices clearly and confidently in real projects.

Self-Check

"What if we fetched comments in batches instead of one by one? How would the time complexity change?"