Designing the API
The contract for placing an order, written so that a lost response and a second tap still produce one order and one charge, and so that months-old app versions keep working.
A customer in Bengaluru taps “Place order” as she steps into a lift. The spinner turns, the signal drops, and after ten seconds the app says “Something went wrong”. She taps again on the way out of the lift. Has she ordered one biryani or two? Has her bank account been debited once or twice? The answer depends entirely on decisions made in the API contract, long before that evening.
This chapter designs the contract between Dabba’s apps and its backend, with most of the attention on placing an order. By the end we will have a request format that the server can check, an idempotency scheme that makes the second tap harmless, status codes that tell each client exactly what to do next, and rules for changing the contract while millions of old app versions are still in use.
Start from the operations, not the URLs
The brief listed what customers do: browse restaurants near an address, read a menu, place and pay for an order, follow its progress, and look back at past orders. Each operation becomes an endpoint, and the resources fall out of them.
GET /v1/restaurants?zone=pune-baner list for the home screen
GET /v1/restaurants/{id}/menu one restaurant's menu
POST /v1/orders place an order
GET /v1/orders/{id} one order and its status
GET /v1/orders?cursor=... the customer's order history
POST /v1/orders/{id}/cancel ask to cancelTwo choices are already in that list. The first is that there is no cart on the server. The cart lives in the app until checkout, and the order request carries its contents. That saves a write for every “add item” tap, which matters at 16 menu views per order, and it means the server must check the whole cart once, at the moment it matters. The cost is that a customer cannot start a cart on her phone and finish it on the website. Dabba accepts that; if the product later wants shared or cross-device carts, a cart resource comes back.
The second is that cancelling is an action, POST /orders/{id}/cancel, rather than a PATCH that sets status to "cancelled". An order moves through a state machine owned by the server: payment pending, placed, accepted, being prepared, picked up, delivered. Whether a cancel is allowed depends on the current state (before the restaurant accepts, yes; after the rider has picked it up, no) and it has side effects such as a refund. A generic PATCH invites clients to propose any state they like and leaves the server to reject the nonsense. A named action states the intent, and the server decides what it means in the current state.
What the order request carries, and what the server refuses to trust
Here is the body the app sends when the customer taps Place order.
POST /v1/orders
Idempotency-Key: 5b0e7c1e-7f2a-4d0c-9a51-2f3c8e4be1a9
{
"restaurant_id": "r_48213",
"items": [
{ "menu_item_id": "m_9001", "quantity": 2,
"options": ["opt_spice_medium", "opt_extra_raita"] }
],
"address_id": "addr_77",
"payment_method": "upi",
"quoted_total_paise": 58400
}The request names things by ID and says how many. It does not tell the server what anything costs. The server looks up the current price of each item and option, applies offers, delivery fee, packaging and tax, and computes the total itself. A client that sends prices is a client that can be edited to send lower ones.
The client does send quoted_total_paise, the total it showed the customer. This is not trusted either; it is a check. Menus are cached (the reads chapter explains how), so the price on screen can be a few minutes old. If the server’s total differs from the quoted one, it refuses the order with a specific error, and the app shows the new total and asks again. Without that field, the server would have to choose between charging a price the customer never saw and silently honouring a stale one.
Money is an integer number of paise. Binary floating point cannot represent most decimal fractions exactly: 0.1 + 0.2 is 0.30000000000000004 in JavaScript, and rounding errors of that kind, summed over a million orders and split between restaurant payouts, rider pay and taxes, turn into reconciliation work. Integers of the smallest currency unit add exactly.
The response the customer never saw
Back to the lift. When the app’s request times out, there are three possibilities, and the app cannot tell them apart. The request may never have reached the server. It may have reached the server and failed there. Or it may have succeeded on the server, with the order written and payment started, while the response was lost on the way back.
The app has to do something. Not retrying is wrong in the first two cases: the customer is left without dinner and without knowing why. Retrying blindly is wrong in the third: it places a second order. A design that is correct in all three cases needs the server to recognise a retry as a retry.
The app times out after 10 seconds and retries once. Suppose the first request did create the order and start a payment. With no idempotency key, what does the retry do, and who notices first?
Show the worked answer
The server sees a valid, new-looking order request and creates a second order with its own payment. If the customer approves both UPI requests, which is easy when the app shows a payment screen again, she is charged twice. If she approves only one, a second order sits in “payment pending” until it expires.
The restaurant usually notices first: two identical tickets arrive a few seconds apart. If both were paid, the kitchen may cook both, a rider may be assigned to each, and support handles the refund the next morning. At 150 orders a second, even a 0.1% retry rate on lost responses is about 9 duplicate orders a minute at peak.
Idempotency keys, built so they actually work
An operation is idempotent if doing it twice has the same effect as doing it once. Reading an order is naturally idempotent. Creating one is not, so we make it so. The client generates a random key (a UUID) for each checkout attempt and sends it in an Idempotency-Key header. Every retry of that attempt sends the same key. The server stores the key together with the outcome, and when it sees the key again it returns the stored outcome instead of repeating the work. Stripe’s public API made this header pattern widely known, and its documentation is a good reference.
The details decide whether it works. Start with when the client creates the key. It must be once per checkout attempt, not once per HTTP request. A key generated inside the HTTP retry loop is a new key on each retry, which protects nothing. The app should create the key when the customer taps Place order for a particular cart and store it with the cart on the phone, so that even if the app is killed and reopened, a retry uses the same key. If the customer changes the cart, that is a new attempt and gets a new key.
On the server, the key lives in a table with a unique constraint.
CREATE TABLE idempotency_keys (
customer_id bigint NOT NULL,
key uuid NOT NULL,
request_hash bytea NOT NULL, -- hash of the request body
status text NOT NULL, -- 'in_progress' | 'completed'
response_code int,
response_body jsonb,
created_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (customer_id, key)
);The key is scoped to the customer, so one customer’s key can never return another customer’s order. The request hash catches a client bug where the same key is reused with a different cart; returning the first order for a different cart would be wrong, so that case gets an error instead. Keys expire after a day, which is far longer than any retry and short enough to keep the table small: about a million rows.
The handler then runs this logic. Try to insert the key with status in_progress. If the insert succeeds, this is the first attempt: create the order, store the response against the key, mark it completed. If the insert hits the unique constraint, read the existing row. If it is completed and the hash matches, return the stored response. If the hash differs, return an error saying the key was reused. If it is still in progress, another copy of this request is being handled right now (the customer’s first request is slow, not lost), so return a “still processing, retry shortly” error rather than starting a second order.
One failure needs particular care: the server crashes after inserting the key and before finishing. If the key insert committed on its own, the key is stuck in in_progress and every retry is told to wait forever. The clean solution is to insert the key, create the order and record the response in the same database transaction, so that a crash rolls all three back together and the retry starts fresh. The writes chapter builds the full transaction around this.
The payment provider sits outside that transaction, so the same idea has to extend to it. When Dabba asks the provider to create a payment, it passes the order ID as the provider’s own idempotency key. If Dabba’s call to the provider times out and is retried, the provider returns the existing payment instead of creating another. Every step that crosses a network and might be retried needs its own key, chosen so that retries of the same logical step carry the same value.
Status codes are the client’s retry policy
Every client Dabba will ever have, including old app versions nobody can update, decides what to do next from the response. HTTP status classes carry a broad meaning: 2xx succeeded, 4xx means the request itself is wrong and sending it again unchanged will not help, 5xx means the server failed and a retry may work. If the API returns 500 for an invalid address, well-behaved clients retry a request that can never succeed. If it returns 400 for a database timeout, they give up on a request that would have worked a second later.
Broad classes are not enough for the order endpoint, so the body carries a stable machine-readable code, and the app branches on that code, not on the human-readable message.
| Result | Status and code | What the app does |
|---|---|---|
| Order created | 201 | go to the payment screen |
| Retry of a completed attempt | 201, same body as the first | the same as above; it cannot tell, and does not need to |
| Price changed since the menu loaded | 409 PRICE_CHANGED with new total | show the new total; on confirm, send with a new key |
| Item sold out | 409 ITEM_UNAVAILABLE with item IDs | remove the items, show the cart again |
| Same key still being processed | 409 IN_PROGRESS | wait a second, retry with the same key |
| Same key, different body | 422 KEY_REUSED | a client bug; log it, start a new attempt |
| Address outside delivery zone | 422 ADDRESS_NOT_SERVICEABLE | ask for another address; do not retry |
| Too many requests | 429 with Retry-After | wait as told, retry with the same key |
| Server or upstream failure | 503 or 504 | retry with backoff and the same key |
Notice which rows say “same key” and which say “new key”. Retrying a failure keeps the key, because it is the same attempt. Confirming a new price makes a new key, because the customer has agreed to a different order. The body of each error looks like this:
{
"error": {
"code": "PRICE_CHANGED",
"message": "Prices at this restaurant have changed.",
"retryable": false,
"details": { "new_total_paise": 61200 }
}
}Lists that stay correct while they change
Order history is a list that grows while the customer scrolls it. The obvious design, ?page=3&size=20, asks the database to skip 40 rows and return the next 20. If a new order is created while the customer is on page 2, every row shifts by one, and page 3 repeats an order she already saw. Skipping also gets slower as pages get deeper, because the database still has to walk past every skipped row.
A cursor fixes both problems. Each page ends with an opaque token that encodes the position of its last row, here (created_at, order_id). The next request asks for rows strictly after that position, which an index on (customer_id, created_at, order_id) answers directly, however deep the page. New orders appear at the top and do not disturb the pages behind them. The token is opaque (base64 of the values, ideally signed) so clients cannot build their own and the server can change what is inside later.
Changing the contract when old apps never update
A web page can change its API calls on every deploy. A phone app cannot: a customer who installed Dabba in March may still run that version in November. So every response the server sends must be readable by every app version still in use, and every request those versions send must still be accepted.
Some changes are safe. Adding a new endpoint is safe. Adding an optional field to a request is safe if the server has a sensible default. Adding a field to a response is safe if clients ignore fields they do not know, which is a rule to put in the client code on the first day. Other changes break old apps: removing or renaming a field, changing its type, making an optional request field required, or changing what a value means.
One break is easy to miss. Suppose Dabba adds an order status, RIDER_REASSIGNED, for when a rider drops an order and another takes it. An old app that maps status strings to screens with an exhaustive switch meets a value it has never seen. Depending on how it was written, it crashes, shows a blank screen, or shows “Delivered”. None of these is the server’s bug, but all of them are the server’s problem. The defence has two parts: clients must treat unknown enum values as a generic “in progress” state from day one, and the server can map new values to old ones for app versions that predate them, using the app version the client sends in a header.
When a change really cannot be made compatibly, it goes into a new version, /v2/orders, and both versions run side by side. The app version header lets the team watch v1 traffic fall as people update. For versions that are too old to support, the API returns a specific “upgrade required” response that the app shows as a full-screen prompt. That prompt has to have been built into the app years earlier, which is why it belongs in the first release.
One screen, one request: when the shape is not plain REST
The first chapter found that round trips on a mobile network cost more than server work. Dabba’s home screen draws on eight endpoints: the restaurant list, banners, the active order, saved addresses and so on. Even over one HTTP/2 connection, eight calls made in sequence because each depends on the last cost eight round trips. Dabba adds a backend-for-frontend endpoint, GET /v1/screens/home, that makes those calls inside the data centre, where a round trip is under a millisecond, and returns one composed response.
The cost is coupling. That endpoint exists for one screen of one app, so it changes whenever the screen does, and it must be versioned with the app as carefully as any other endpoint. GraphQL addresses the same problem differently, letting each client ask for exactly the fields it needs, at the price of a query planner on the server, harder HTTP caching and the risk of clients writing expensive queries. Between Dabba’s own services, where both sides deploy together and typed contracts and deadlines matter, gRPC is a reasonable choice. Plain JSON over HTTP remains the default for the public API until a measured problem names one of these alternatives.
When this machinery is not needed
Idempotency keys are for operations that create or change things and might be retried. Reads do not need them. A PUT that sets a field to a value is already idempotent, as is a delete of a specific ID. An internal batch job that runs once a night and checks its own results may be simpler with a natural key (the restaurant and the payout date, say) and a unique constraint. Adding a key table to every endpoint is cost without benefit.
We should revisit the contract when the product changes who calls it. A partner integration, such as a restaurant chain that wants to receive orders in its own point-of-sale system, brings clients that Dabba does not write and cannot force to upgrade. That is the moment to publish the contract formally, with an OpenAPI description, documented limits and deprecation dates.
The contract tells clients what to send and what to expect. It says nothing about where those requests land. The next chapter, Load balancing, gateways and discovery, follows a request from the edge of Dabba’s network to one of thirty identical servers, and looks at how the boxes in between can fail a healthy fleet.