Getting writes right
Forty customers tap Place order for the last twelve thalis. What the database guarantees, where its guarantees stop, and how to stay correct when payment happens somewhere else.
At 8:02 pm on Diwali, a cloud kitchen in Gurugram has 12 portions left of a limited festival thali. Dabba has just featured it on the home screen, and 40 customers tap Place order within the same second. Each request, run on its own, is correct: check that portions remain, create the order, take a portion. Run together, they can sell far more than 12 thalis. Reads that are a little stale cost a confusing screen. Writes that interleave badly cost money, food and trust.
This chapter builds the write path for placing an order. We will state what must stay true, see what the database promises when many transactions run at once and where those promises stop, choose the smallest mechanism that protects each rule, and then deal with the part no database transaction can cover: a payment provider that confirms payments in its own time.
What placing an order must leave true
Before choosing mechanisms, we write down the rules, because each rule will get its own enforcement and some rules are easy to forget until they break.
| Rule | What breaking it looks like | Enforced by |
|---|---|---|
| One order per checkout attempt | two identical tickets in the kitchen, two charges | idempotency key with a unique constraint (API chapter) |
| Limited stock never goes below zero | 15 thalis sold, 12 cooked, 3 refunds and angry customers | a conditional update in the order transaction |
| A once-per-customer coupon is used once | WELCOME100 redeemed twice from two phones | a unique constraint on the redemption |
| No paid order is lost; no unpaid order is cooked | money taken with no food, or food sent without payment | order states plus webhook handling and reconciliation |
| Every paid order reaches the restaurant exactly once in effect | a paid order that never appears on the tablet | an outbox written in the same transaction, and consumers that ignore duplicates |
What the database promises when forty transactions run at once
A transaction groups several reads and writes so that they commit together or not at all. Atomicity and durability are the easy promises to understand: either every row in the order is written or none is, and once the commit returns, a crash will not undo it. The promise that decides whether the thali oversells is isolation: what one transaction can see of others that are running at the same time.
Postgres, like most databases, does not isolate transactions completely by default. Its default level, read committed, gives each statement a view of all data committed before that statement began. That rules out reading another transaction’s uncommitted changes. It does not stop two transactions from reading the same value, each making a decision from it, and each writing a result that ignores the other’s.
The order code runs, under Postgres’s default isolation: SELECT remaining FROM limited_stock WHERE item_id = 9001; then, if remaining ≥ 1, it computes remaining − 1 in the application and runs UPDATE limited_stock SET remaining = <that value>. Twelve portions remain and forty requests arrive together. How many thalis are sold, and what does the counter say afterwards?
Show the worked answer
Possibly all forty, with the counter saying something like 11. Many transactions run the SELECT at nearly the same moment and all see 12. Each concludes a portion is available, creates its order, and writes 11. The updates queue behind each other’s row locks, but each one writes the value its own code computed from the old read, so they all write 11. Every order commits.
This is called a lost update: each transaction’s change overwrote the others’ instead of adding to them. Nothing failed, no error was logged, and the kitchen discovers the problem when it runs out of thalis with 28 paid orders still to cook.
The fix for this case is small. Instead of reading the value into the application and writing back a computed number, the application asks the database to make the change only if the rule still holds:
UPDATE limited_stock
SET remaining = remaining - $2
WHERE item_id = $1 AND remaining >= $2;
-- 1 row updated: the portions are ours
-- 0 rows updated: sold out; roll back and return ITEM_UNAVAILABLEThis works under read committed because of how Postgres handles an update that meets a row another transaction has just changed. The second transaction waits for the first to commit, then re-checks its WHERE clause against the new version of the row. The twelfth order sees remaining = 1 and succeeds; the thirteenth waits, re-checks, sees 0 and updates nothing. The check and the change happen as one step on the row, so there is no gap for another transaction to slip into. Adding CHECK (remaining >= 0) to the table is a cheap second line of defence in case some other code path forgets the condition.
Order state changes use the same shape. A restaurant tapping Accept and a customer tapping Cancel at the same moment both run conditional updates: SET status = 'ACCEPTED' WHERE order_id = $1 AND status = 'PLACED', and the cancel with its own condition. Exactly one finds the order still in PLACED; the other updates no rows and tells its user the order has moved on.
The coupon that was used twice
Stronger isolation levels exist, and it is tempting to think they make every rule safe. Postgres’s repeatable read gives each transaction one consistent snapshot for its whole life, and if two transactions update the same row, the second fails with a serialization error that the code retries. That would also have stopped the thali oversell. But some rules are not about one row.
Dabba’s welcome coupon may be used once per customer. The order code checks SELECT count(*) FROM coupon_redemptions WHERE customer_id = $1 AND code = 'WELCOME100', and if the count is zero, inserts a redemption with the order. A customer places two orders at once, one from her phone and one from the website. Both transactions take their snapshots, both count zero redemptions, both insert a new row and both commit. They wrote different rows, so even repeatable read sees no conflict. The rule depended on a row being absent, and no snapshot protects the absence of a row. This pattern, where two transactions each read something, then each write something the other read depended on, is called write skew.
Postgres’s serializable level would catch it, by tracking what each transaction read and aborting one of a dangerous pair. Here there is a simpler fix that works at every isolation level:
ALTER TABLE coupon_redemptions
ADD CONSTRAINT one_use_per_customer UNIQUE (customer_id, code);Now the second insert waits for the first transaction, sees its committed row, and fails with a unique violation, which the order code turns into a COUPON_ALREADY_USED response. The rule has moved from application code, where it could be raced, into the database, where it cannot. Many rules that seem to need careful locking can be stated as a constraint, and when they can, that is the cheapest enforcement available.
| Mechanism | Fits when | What it costs |
|---|---|---|
| Unique or check constraint | the rule is about one row or a unique combination | errors that must be mapped to clear responses |
| Conditional update | counters and state transitions on one row | logic in the WHERE clause; the code must check rows affected |
SELECT … FOR UPDATE | read several rows, decide, then write; conflicts are common | lock waits; deadlocks if transactions lock rows in different orders |
| Version column, checked on write | conflicts are rare, such as two staff editing one menu | a retry or a “changed by someone else” message |
| Serializable isolation for one transaction | a rule spans many rows and no constraint expresses it | aborts under contention, and retry code that must exist and be tested |
The table is ordered roughly by cost. Dabba’s order path uses the first two for nearly everything, a version column for restaurant menu edits, and has no rule yet that needs serializable isolation.
The write path, step by step
Putting it together, placing an order does its local work in one short transaction, and only after that transaction commits does it talk to anything outside the database.
BEGIN;
INSERT INTO idempotency_keys (customer_id, key, request_hash, status)
VALUES ($cust, $key, $hash, 'in_progress'); -- conflict: replay or 409
INSERT INTO orders (...) VALUES (..., 'PAYMENT_PENDING', ...);
INSERT INTO order_items (...) VALUES (...), (...);
UPDATE limited_stock SET remaining = remaining - 2
WHERE item_id = 9001 AND remaining >= 2; -- 0 rows: ITEM_UNAVAILABLE
INSERT INTO stock_reservations (order_id, item_id, qty, expires_at)
VALUES ($order, 9001, 2, now() + interval '10 minutes');
INSERT INTO coupon_redemptions (customer_id, code, order_id)
VALUES ($cust, 'WELCOME100', $order); -- unique violation: COUPON_ALREADY_USED
INSERT INTO outbox (event_id, type, payload)
VALUES ($event, 'order_created', $json);
UPDATE idempotency_keys SET status = 'completed', response_code = 201, response_body = $resp
WHERE customer_id = $cust AND key = $key;
COMMIT;
-- after commit, outside the transaction:
payment = provider.createPayment(amount, idempotencyKey = order_id)The transaction touches perhaps eight rows and takes a few milliseconds. If anything in it fails, everything in it is undone, including the idempotency key, so the customer’s retry starts cleanly. After commit, the order service asks the payment provider to create a payment, passing the order ID as the provider’s idempotency key, and returns the order and the payment details to the app. If the provider call fails, the order still exists in PAYMENT_PENDING; the app’s retry, with the same key, gets the stored order back, and the service asks the provider again with the same order ID, receiving the same payment rather than a new one.
Two things in that transaction need explaining: why stock is reserved rather than simply taken, and why the payment call is outside. They come from the same incident.
The transaction that waited for the bank
An earlier version of the order code did everything in one transaction: lock the stock row with SELECT … FOR UPDATE, insert the order, call the payment provider, and commit once the provider answered. It looked tidy. If the payment call failed, the transaction rolled back and the stock was never taken.
On a busy evening the payment provider slows down, and its responses take about 4 seconds instead of 300 ms. Every order transaction now stays open for 4 seconds. Two things go wrong. Orders for the festival thali queue on its stock row’s lock, and since each holder keeps the lock for 4 seconds, the item can be sold at a quarter of an order a second, however many customers want it. Worse, every open transaction holds a database connection. By Little’s law, 150 orders a second × 4 seconds = 600 connections busy at once. The order service’s pools across 30 servers hold 20 connections each, exactly 600, and Postgres would not accept many more anyway. The pools run dry. Orders that do not involve the thali, or even the slow payment method, wait for a connection and time out. A slowdown at a third party has become an outage of all ordering.
The rule that came out of this incident: a database transaction never waits on a network call to another system. Local work commits first, quickly. Anything external happens afterwards, and the order’s state records where it has got to. The thali’s stock is taken in the local transaction with a reservation that expires in 10 minutes, roughly the time a UPI payment can remain pending. When payment succeeds, the reservation becomes permanent. When payment fails, or the reservation expires, a background job returns the portions to stock and cancels the order (the background jobs chapter builds that job properly).
The fix has a visible cost. For up to 10 minutes, portions held by customers who will never pay look sold out to everyone else. On a twelve-portion item, three abandoned checkouts can turn away paying customers. Dabba shortens the expiry for limited items and shows “a few left, being ordered now” rather than “sold out” while reservations are pending. And there is one more moving part, the expiry job, which must itself be reliable.
When the write spans Dabba and the payment provider
No transaction can include the payment provider. The provider will not hold locks on Dabba’s behalf, and protocols that coordinate a commit across systems, such as two-phase commit, require every participant to support them and stall when the coordinator fails. So the order and the payment are kept consistent by states, idempotent steps and checks, rather than by one atomic commit.
The provider tells Dabba about payment outcomes with a webhook: an HTTP request to Dabba’s endpoint. Webhooks can arrive late, more than once, or out of order, and the handler is written for all three. It verifies the provider’s signature. It records the provider’s event ID in a table with a unique constraint, so a repeated delivery is recognised and acknowledged without being processed again. And it moves the order with a conditional update, inside a transaction that also writes an outbox row:
BEGIN;
INSERT INTO payment_events (provider_event_id, order_id, outcome) VALUES (...); -- duplicate: stop
UPDATE orders SET status = 'PLACED'
WHERE order_id = $1 AND status = 'PAYMENT_PENDING';
-- 1 row: write outbox 'order_placed', confirm the stock reservation
-- 0 rows: look at the current status and decide (below)
COMMIT;The zero-row case is where the business rules live. If the order is already PLACED, this was a late duplicate and nothing more is needed. If the order was cancelled because its reservation expired, and the payment succeeded anyway (the customer approved the UPI request at minute eleven), Dabba now holds money for an order it will not cook. The handler issues a refund, keyed by the payment ID so a retry cannot refund twice, and notifies the customer. That refund is a compensating action: a new step that undoes the business effect of an earlier one, used because the earlier one cannot be rolled back.
Webhooks can also fail to arrive at all. A reconciliation job asks the provider for the status of every order that has been in PAYMENT_PENDING for more than two minutes, and applies the answer through the same handler. With that job in place, the webhook is a way to learn quickly, and reconciliation is the way to be sure.
The same structure covers the rest of the order’s life. If the restaurant rejects a paid order because the kitchen is overwhelmed, the compensation is a refund plus releasing any reserved stock. A sequence of local steps with a compensation for each is often called a saga. Its intermediate states are visible to customers and staff, so they need honest names: “payment pending” and “waiting for the restaurant” are true statements a support agent can act on, where a status that claims more than has happened is not.
Finally, the outbox. When an order becomes PLACED, the kitchen tablet, the notification service and analytics all need to know. If the handler commits and then publishes a message to a broker, a crash between the two loses the message, and a paid order never reaches the kitchen. If it publishes first and then the commit fails, the kitchen cooks an order that does not exist. Writing the event as a row in an outbox table, in the same transaction as the status change, makes the two succeed or fail together. A separate relay reads new outbox rows and publishes them, marking each as sent. If the relay crashes after publishing and before marking, it publishes the row again on restart, so consumers must ignore events whose ID they have already handled. The streams chapter builds the relay and the consumers in detail.
When this is more than the write needs, and when it is not enough
Most of Dabba’s writes do not need any of this. A customer renaming a saved address, a rider toggling availability, a restaurant uploading a photo: each touches one row with no competing writer and no external system, and a plain update is correct. Running everything at serializable isolation “to be safe” would add aborts and retry code to all of them for no benefit. The care in this chapter belongs where money, stock or external systems are involved.
The design has a limit worth knowing in advance. A single hot row, the thali’s stock, is locked by each order from its update until commit, a few milliseconds, which caps that one item at a few hundred orders a second. Dabba is far from that. A flash sale of one item to millions of customers would reach it, and the usual answer is to split the stock into several rows (ten buckets of 100 portions instead of one of 1,000) and take from a random bucket. We should also revisit the write path when order volume approaches what one primary sustains, or when orders must be written in more than one region, because both break the assumption that one database sees every order.
That assumption is where this part of the course ends. Every chapter so far has relied on one Postgres primary for orders, and the arithmetic in the first chapter said that was safe for now. The next chapter, Sharding and partitioning, picks up the day it stops being safe: how to split orders, and later rider locations, across machines, and which of the queries from the data modelling chapter stay easy once the data no longer lives in one place.
Why the standard isolation levels are underspecified, and what the anomalies really are.
Free in full. A curated tour of the field with editorial commentary on why each paper mattered.