Resource expansion (embed related data) in Rest API - Time & Space Complexity
When a REST API expands resources to include related data, it fetches more information in one go.
We want to know how this extra fetching affects the time it takes to get the data.
Analyze the time complexity of the following code snippet.
GET /orders?expand=customer,items
// The API fetches orders, and for each order, it also fetches the related customer and items data.
This code fetches a list of orders and expands each order with its related customer and items details.
- Primary operation: For each order, fetching related customer and items data.
- How many times: Once per order in the list.
As the number of orders grows, the API does more work fetching related data for each order.
| Input Size (n orders) | Approx. Operations |
|---|---|
| 10 | Fetch 10 orders + 10 customers + 10 items sets |
| 100 | Fetch 100 orders + 100 customers + 100 items sets |
| 1000 | Fetch 1000 orders + 1000 customers + 1000 items sets |
Pattern observation: The work grows roughly in direct proportion to the number of orders.
Time Complexity: O(n)
This means the time to get all data grows linearly with the number of orders requested.
[X] Wrong: "Expanding related data only adds a small fixed cost regardless of how many orders there are."
[OK] Correct: Each order adds extra fetches for its related data, so the cost grows with the number of orders, not fixed.
Understanding how expanding related data affects performance helps you design APIs that stay fast as data grows.
What if the API also expanded nested related data, like each item's supplier? How would the time complexity change?