POST /v1/orders: idempotent checkout
You build POST /v1/orders to price menu lines on the server and create an order with its lines, first event and outbox row. A customer-scoped idempotency key makes completed retries return the original order and prevents concurrent duplicates.
Ticket
Implement POST /v1/orders for authenticated customers. The endpoint prices every requested line through the Week 2 configurator, then returns the created order.
Checkout needs safe retries because a client may not receive the response to its first request. Week 4's Expo app will send an Idempotency-Key so a completed retry returns the original order. The order, its lines, initial order event and outbox row must commit together in one MySQL transaction.
Endpoint
Place an order, at most once per Idempotency-Key
restaurant_idintegerrequiredlinesobject[]requireditem_idintegerrequiredsizestringrequiredchosenmap of integer[]requiredqtyintegerrequired1 to 50
idintegerrequiredrestaurant_idintegerrequiredstatus"PLACED" | "ACCEPTED" | "PREPARING" | "READY" | "PICKED_UP" | "DELIVERED" | "CANCELLED" | "REJECTED"requiredversionintegerrequiredtotal_paiseintegerrequiredcreated_atstring (date-time)requiredeventsobject[]Only on GET /v1/orders/{id}.
event_idstringrequiredfrom_statusstringrequiredto_statusstringrequiredactor"customer" | "restaurant" | "rider"required
idintegerrequiredrestaurant_idintegerrequiredstatus"PLACED" | "ACCEPTED" | "PREPARING" | "READY" | "PICKED_UP" | "DELIVERED" | "CANCELLED" | "REJECTED"requiredversionintegerrequiredtotal_paiseintegerrequiredcreated_atstring (date-time)requiredeventsobject[]Only on GET /v1/orders/{id}.
event_idstringrequiredfrom_statusstringrequiredto_statusstringrequiredactor"customer" | "restaurant" | "rider"required
invalid_bodyinvalid_parameterinvalid_order
unauthorized
forbidden
request_in_progress
Acceptance criteria
- A request without
Idempotency-Keyor with a 37-character key returns400with errorinvalid_parameterand fieldIdempotency-Key. A 36-character key is accepted, and a valid order returns201. - Repeating a completed request with the same customer's key returns
200with the original order ID and unchanged total, even when the retry requests a different quantity. Using a different key creates a different order and returns201. - Two different customers using the same idempotency key each receive
201and different order IDs. - Fifty concurrent requests from one customer using the same key produce exactly one order and exactly one
201response. Every response has status201,200or409. Successful responses identify the same order, and the database contains exactly one order for that customer. A conflicting request returnsrequest_in_progress. - The server calculates the total from configured menu prices and quantities. A Farmhouse line (
item_id = 1) with sizeM, Cheese burst, Olives and Paneer, at quantity2, costs111600paise. A second Farmhouse line (item_id = 1) with sizeRand the Classic hand tossed crust, at quantity1, costs19900paise. The combined order returns201withtotal_paise = 131500, even when the client sendstotal_paise = 1. The order has statusPLACED, version1andrestaurant_id = 1. - Placing an order with two Farmhouse lines, one with quantity
2and one with quantity1, writes two matchingorder_linesrows withitem_id = 1andunit_paise = 55800. It also writes exactly oneorder_eventsrow from''toPLACEDbycustomer, and exactly oneoutboxrow whosekey_is the order ID. - An invalid order returns
400with errorinvalid_orderand lists every pricing problem with its zero-based line index. The tested invalid lines produce1/size_not_offeredand2/unknown_item. The rejected request creates no order, and retrying the same key with a valid order returns201. - Ordering an item belonging to restaurant
1while requesting restaurant2returns400with errorinvalid_orderand includes anunknown_itemerror. - Malformed JSON returns
400with errorinvalid_body. A missingrestaurant_idreturns400with errorinvalid_parameterand fieldrestaurant_id. An emptylinesarray, a quantity of0or a quantity of51returns400with errorinvalid_parameterand fieldlines. - Rider and restaurant accounts receive
403with errorforbiddenwhen placing an order. A request without authentication receives401with errorunauthorized.
Constraints
Idempotency-Keymust contain between 1 and 36 characters.- Scope idempotency keys to the authenticated customer.
- For concurrent requests using one customer's key, create exactly one order. Responses must have status
201,200or409. - Only authenticated customers may place orders.
- Require
restaurant_idand a non-emptylinesarray. Each line quantity must be between 1 and 50. - Calculate line prices and the order total using server-side pricing. Ignore any client-supplied
total_paise. - Include every pricing problem with its zero-based line index. A rejected order must not consume its idempotency key.
Design direction
Keep the HTTP handler responsible for request validation, authentication checks and response status codes. Read the authenticated caller from the request context populated by the existing bearer-token HTTP middleware, using the value stored in the request context rather than trusting an account ID supplied by the client.
Give idempotency coordination a separate responsibility. Use Redis SET NX to claim each idempotency key within the customer's scope. Distinguish a pending claim from a completed result. A pending claim means another request is still running. A completed claim identifies the order to replay.
Keep database writes together in one MySQL transaction. Price all lines before opening the transaction so invalid menu selections do not hold database locks. The transaction should create the order, its lines, its first order event and its outbox row as one unit. Any layout that meets the contract passes.
Think about the gap between Redis and MySQL. The database commit can succeed while recording the completed result in Redis fails. A retry may then see a pending claim until it expires. Also keep event identity separate from request identity. A fresh event ID belongs to the order event, not to the customer's idempotency key. The database's duplicate-key error illustrates why those identifiers have different uniqueness rules.
How to check your work
From the project root, run:
cd backend && make up
cd backend && make test W=W3B4Read the first failing assertion. Its status, response body or database count identifies which part of the order contract failed.
The reference solution passes every check for this exercise. Try the hints first; reading the answer before you have struggled with the problem teaches much less.
Order creation
5 items
- 3.6Migration 0006: order tablesnot completed
- 3.7Transactions in Go and MySQLnot completed
- 3.8Isolation levels and anomaliesnot completed
- 3.9Idempotency keysnot completed
- 3.10POST /v1/orders: idempotent checkoutnot completed
Up next · Module 3 · 2 items · about 3 h
Implementation
Run locally
Write the code in your editor inside zomato-prep, then work through this list.
- Validate the
Idempotency-Keyheader. - Replay completed requests with the original order.
- Scope keys to the authenticated customer.
- Price every line using the Week 2 configurator.
- Write the order, lines, event and outbox row together.
- Handle invalid requests and enforce customer-only access.
Commands
cd backend && make upcd backend && make test W=W3B4Tests
the endpoint rejects a missing key and a 37-character key, while accepting a 36-character key.
POST/v1/ordersHeadersAuthorization Bearer {access_token} Body raw JSON{ "restaurant_id": 1, "lines": [ { "item_id": 1, "size": "M", "chosen": { "1": [2], "2": [3, 5] }, "qty": 1 } ] }Response 400 Bad Request{ "error": "invalid_parameter", "message": "…", "field": "Idempotency-Key" }POST/v1/ordersHeadersAuthorization Bearer {access_token} Idempotency-Key {36 characters} Body raw JSON{ "restaurant_id": 1, "lines": [ { "item_id": 1, "size": "M", "chosen": { "1": [2], "2": [3, 5] }, "qty": 1 } ] }Response 201{ "id": 41, "restaurant_id": 1, "status": "PLACED", "version": 1, "total_paise": 55800, "created_at": "2026-01-05T10:00:00.000Z" }Input Place a valid farmhouse order without an
Idempotency-Key, then with 37kcharacters, then with a 36-character numeric key.Expected The first two requests return 400
invalid_parameterwith fieldIdempotency-Key. The final request returns 201 with an order.TestW3B4_PlacingNeedsAnIdempotencyKeyOfOneTo36Charactersinbackend/e2e/w3_orders_test.go