Bulk Operations
You'll learn to
- -Add a batch endpoint, and decide what happens when some items fail
- -Report each item's result with 207 Multi-Status, keyed by an index
- -Know when all-or-nothing is the right model instead, and run both
Creating a hundred resources with a hundred separate HTTP requests is slow and wasteful when a client has a hundred things to submit at once. A batch endpoint takes many items in one request. It raises a design question plain CRUD does not have: what happens when some items succeed and others fail?
An Analogy: Posting a Pile of Letters
If you hand the post office ten letters and one has no address, you want the other nine delivered and a note about the bad one. But if you hand over a bank transfer slip with three linked steps, you do not want step one done and step two refused. Some batches are piles of independent letters, and some are one transaction in pieces.
Batch Endpoints
POST /orders/batch
{
"orders": [
{"product_id": 1, "quantity": 2},
{"product_id": 999, "quantity": 1},
{"product_id": 3, "quantity": -5}
]
}Partial Success: 207 Multi-Status
HTTP/1.1 207 Multi-Status
{
"results": [
{"index": 0, "status": 201, "id": 501},
{"index": 1, "status": 404, "error": "product_id 999 does not exist"},
{"index": 2, "status": 422, "error": "quantity must be positive"}
]
}An all-or-nothing rule is simpler to build, but often wrong for batch work. A client submitting 100 items rarely wants 99 good ones rejected because of one bad one. A 207 Multi-Status response reports a result per item inside one overall response, so the client sees exactly which items worked and why the others failed, and resubmits only those.
When All-or-Nothing Is Actually Correct
Partial success is not always right. If the batch is one logical transaction, such as moving funds between several accounts as a single operation, partial success would leave the system in an inconsistent in-between state. Then all-or-nothing, with one clear error saying what failed, is correct. The rule: independent items batched for efficiency want partial success, and one operation split into pieces wants atomicity.
The demo runs both. First, three independent orders produce three separate results, and the overall answer would be a 207. Then two linked transfers are applied as one unit: when the second one fails, the first is undone.
Always echo an index or a client-supplied id for each item in a 207 response. Without it, a client told "item 2 failed" has no reliable way to map that back to what it submitted, especially in a large batch.
Interview Signal is part of Pro
See a real weak answer next to a real strong one for this exact topic.
Quiz is part of Pro
Test what you just read with a short quiz, and bank the XP.
Design Bulk Operations HQ in the API Design Lab's Production Patterns act.
Discussion0
Join the Discussion
Sign in to leave comments, reply to others, or like insights.
No comments yet. Be the first to start the thread!