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?"
Practice
Solution
Step 1: Understand the purpose of advanced patterns
Advanced patterns like pagination and consistent error handling help organize API responses and interactions.Step 2: Connect patterns to real-world benefits
These patterns improve usability, maintainability, and scalability of APIs in practical applications.Final Answer:
They make APIs easier to use, maintain, and scale. -> Option CQuick Check:
Advanced patterns improve API usability = They make APIs easier to use, maintain, and scale. [OK]
- Assuming patterns only add complexity
- Believing patterns slow down APIs
- Thinking patterns are for small projects only
Solution
Step 1: Recall standard pagination header naming
Common practice uses custom headers starting with 'X-' like 'X-Pagination-Page' to indicate page number.Step 2: Compare options to standard naming
Only 'X-Pagination-Page: 1' follows the common convention for pagination headers.Final Answer:
X-Pagination-Page: 1 -> Option AQuick Check:
Standard pagination header = X-Pagination-Page: 1 [OK]
- Using generic header names without 'X-' prefix
- Confusing query parameters with headers
- Assuming 'Page' alone is a header
{
"data": ["item1", "item2"],
"page": 2,
"per_page": 2,
"total": 5
}What is the total number of pages available?
Solution
Step 1: Identify total items and items per page
Total items = 5, items per page = 2.Step 2: Calculate total pages needed
Divide total by per_page: 5 / 2 = 2.5, round up to 3 pages.Final Answer:
3 -> Option DQuick Check:
5 items with 2 per page = 3 pages [OK]
- Using integer division without rounding up
- Confusing current page with total pages
- Ignoring total count and using data length
{
"error": "Invalid ID",
"code": 400
}But your client expects error details under the key "message" instead of "error". How can you fix this to follow consistent error patterns?
Solution
Step 1: Identify the inconsistency
The API returns error details under "error" but client expects "message" key.Step 2: Fix the API response to match client expectation
Change the API to use "message" key for error details to keep consistent error format.Final Answer:
Change the API to return {"message": "Invalid ID", "code": 400} -> Option AQuick Check:
Consistent error keys = Use "message" key in API response [OK]
- Ignoring client expectations
- Retrying without fixing error format
- Removing important error code info
Solution
Step 1: Identify best practices for filtering and pagination
Filters are commonly passed as query parameters; pagination also uses query parameters for page and size.Step 2: Combine with consistent error handling
Returning consistent error messages helps clients handle issues gracefully.Final Answer:
Use query parameters for filters and pagination, and return consistent error messages. -> Option BQuick Check:
Filters + pagination via query params + consistent errors = Use query parameters for filters and pagination, and return consistent error messages. [OK]
- Ignoring pagination causing large responses
- Using POST instead of GET for filtering
- Sending filters in headers which is non-standard
Ready to prove it?
Pass the test and this pattern moves unknown
