Batch delete patterns in Rest API - Time & Space Complexity
When deleting many items at once using a batch delete in a REST API, it is important to understand how the time taken grows as the number of items increases.
We want to know how the work done changes when we delete more items in one request.
Analyze the time complexity of the following code snippet.
// Example batch delete endpoint
app.delete('/items', async (req, res) => {
const ids = req.body.ids; // array of item IDs to delete
for (const id of ids) {
await database.deleteItemById(id);
}
res.send({ message: 'Items deleted' });
});
This code deletes each item one by one by looping through the list of IDs and deleting each from the database.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through the list of IDs and deleting each item individually.
- How many times: Once for each item in the input list.
As the number of items to delete grows, the total work grows roughly the same amount.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 delete calls |
| 100 | 100 delete calls |
| 1000 | 1000 delete calls |
Pattern observation: The work grows linearly with the number of items to delete.
Time Complexity: O(n)
This means the time to delete items grows directly in proportion to how many items you want to delete.
[X] Wrong: "Deleting multiple items in one batch always takes the same time as deleting one item."
[OK] Correct: Each item still needs to be deleted, so the total time adds up with more items.
Understanding how batch operations scale helps you design efficient APIs and explain your choices clearly in interviews.
"What if the batch delete used a single database query to delete all items at once? How would the time complexity change?"