Batch create endpoint design in Rest API - Time & Space Complexity
When designing a batch create endpoint, it is important to understand how the time to process requests grows as the number of items increases.
We want to know how the server's work changes when more items are sent to be created at once.
Analyze the time complexity of the following code snippet.
POST /items/batch
Request Body: [item1, item2, item3, ..., itemN]
for each item in request body:
validate(item)
save item to database
return success response
This code receives a list of items, validates each one, saves them one by one, and then returns a success message.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each item to validate and save it.
- How many times: Exactly once per item in the batch.
As the number of items increases, the total work grows in direct proportion.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 validations and saves |
| 100 | About 100 validations and saves |
| 1000 | About 1000 validations and saves |
Pattern observation: Doubling the number of items roughly doubles the work done.
Time Complexity: O(n)
This means the time to process grows linearly with the number of items sent in the batch.
[X] Wrong: "Processing multiple items at once will always take the same time as processing one item."
[OK] Correct: Each item requires its own validation and save, so more items mean more work and more time.
Understanding how batch operations scale helps you design efficient APIs and explain your reasoning clearly in interviews.
"What if the endpoint used a bulk database insert instead of saving items one by one? How would the time complexity change?"