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

POST/v1/orders

Place an order, at most once per Idempotency-Key

Request body JSON
  • restaurant_idintegerrequired
  • linesobject[]required
    • item_idintegerrequired
    • sizestringrequired
    • chosenmap of integer[]required
    • qtyintegerrequired

      1 to 50

Response 200 OK
  • idintegerrequired
  • restaurant_idintegerrequired
  • status"PLACED" | "ACCEPTED" | "PREPARING" | "READY" | "PICKED_UP" | "DELIVERED" | "CANCELLED" | "REJECTED"required
  • versionintegerrequired
  • total_paiseintegerrequired
  • created_atstring (date-time)required
  • eventsobject[]

    Only on GET /v1/orders/{id}.

    • event_idstringrequired
    • from_statusstringrequired
    • to_statusstringrequired
    • actor"customer" | "restaurant" | "rider"required
Response 201
  • idintegerrequired
  • restaurant_idintegerrequired
  • status"PLACED" | "ACCEPTED" | "PREPARING" | "READY" | "PICKED_UP" | "DELIVERED" | "CANCELLED" | "REJECTED"required
  • versionintegerrequired
  • total_paiseintegerrequired
  • created_atstring (date-time)required
  • eventsobject[]

    Only on GET /v1/orders/{id}.

    • event_idstringrequired
    • from_statusstringrequired
    • to_statusstringrequired
    • actor"customer" | "restaurant" | "rider"required
Response 400 Bad Request

invalid_bodyinvalid_parameterinvalid_order

Response 401

unauthorized

Response 403

forbidden

Response 409

request_in_progress

Acceptance criteria

  • A request without Idempotency-Key or with a 37-character key returns 400 with error invalid_parameter and field Idempotency-Key. A 36-character key is accepted, and a valid order returns 201.
  • Repeating a completed request with the same customer's key returns 200 with the original order ID and unchanged total, even when the retry requests a different quantity. Using a different key creates a different order and returns 201.
  • Two different customers using the same idempotency key each receive 201 and different order IDs.
  • Fifty concurrent requests from one customer using the same key produce exactly one order and exactly one 201 response. Every response has status 201, 200 or 409. Successful responses identify the same order, and the database contains exactly one order for that customer. A conflicting request returns request_in_progress.
  • The server calculates the total from configured menu prices and quantities. A Farmhouse line (item_id = 1) with size M, Cheese burst, Olives and Paneer, at quantity 2, costs 111600 paise. A second Farmhouse line (item_id = 1) with size R and the Classic hand tossed crust, at quantity 1, costs 19900 paise. The combined order returns 201 with total_paise = 131500, even when the client sends total_paise = 1. The order has status PLACED, version 1 and restaurant_id = 1.
  • Placing an order with two Farmhouse lines, one with quantity 2 and one with quantity 1, writes two matching order_lines rows with item_id = 1 and unit_paise = 55800. It also writes exactly one order_events row from '' to PLACED by customer, and exactly one outbox row whose key_ is the order ID.
  • An invalid order returns 400 with error invalid_order and lists every pricing problem with its zero-based line index. The tested invalid lines produce 1/size_not_offered and 2/unknown_item. The rejected request creates no order, and retrying the same key with a valid order returns 201.
  • Ordering an item belonging to restaurant 1 while requesting restaurant 2 returns 400 with error invalid_order and includes an unknown_item error.
  • Malformed JSON returns 400 with error invalid_body. A missing restaurant_id returns 400 with error invalid_parameter and field restaurant_id. An empty lines array, a quantity of 0 or a quantity of 51 returns 400 with error invalid_parameter and field lines.
  • Rider and restaurant accounts receive 403 with error forbidden when placing an order. A request without authentication receives 401 with error unauthorized.

Constraints

  • Idempotency-Key must 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, 200 or 409.
  • Only authenticated customers may place orders.
  • Require restaurant_id and a non-empty lines array. 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:

bash
cd backend && make up
cd backend && make test W=W3B4

Read the first failing assertion. Its status, response body or database count identifies which part of the order contract failed.

Finished Exercise 3.10?

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

Order lifecycle API

Up next · Module 3 · 2 items · about 3 h

Start module 3

Implementation

Run locally

Write the code in your editor inside zomato-prep, then work through this list.

  1. Validate the Idempotency-Key header.
  2. Replay completed requests with the original order.
  3. Scope keys to the authenticated customer.
  4. Price every line using the Week 2 configurator.
  5. Write the order, lines, event and outbox row together.
  6. Handle invalid requests and enforce customer-only access.

Commands

terminal
cd backend && make up
terminal
cd backend && make test W=W3B4

Tests

  1. the endpoint rejects a missing key and a 37-character key, while accepting a 36-character key.

    POST/v1/orders
    Headers
    AuthorizationBearer {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/orders
    Headers
    AuthorizationBearer {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 37 k characters, then with a 36-character numeric key.

    Expected The first two requests return 400 invalid_parameter with field Idempotency-Key. The final request returns 201 with an order.

    TestW3B4_PlacingNeedsAnIdempotencyKeyOfOneTo36Characters in backend/e2e/w3_orders_test.go