Test an API at Its Boundaries
Two notebooks cost AED 27, yet the receipt is blank and the order says AED 24. Trace the fault with pricing, PostgreSQL and HTTP tests.
Advanced · Lesson 7 of 12
Software Architecture
One notebook, two confirmed pickups, and a stock counter that still looks right. Follow two checkouts to see where the sale must be decided.

At a Dubai stationery shop, Hala and Omar each tap Buy on the last blue notebook. Both saw “one available.” Both phones receive an order number. A clerk opens the pickup queue and finds two customers entitled to the same notebook. The inventory dashboard says zero, which looks perfectly reasonable until the clerk counts the orders. How could the counter have stayed within its allowed range while the shop sold more stock than it owned?
We will model the shelf as one PostgreSQL row, follow the two checkouts in a particular order, and decide what evidence the shop needs before it sends a confirmation. Assume a single branch, one product code BLUE, and no returns or replenishment during the example. Each buyer wants one unit. A basket is a shopping list. The promise to supply a notebook begins when checkout commits an allocation.
Record one starting unit and give each confirmed order a line containing the quantity allocated to it. At the end of every committed checkout, remaining units must be nonnegative. There is a second requirement: remaining units plus units allocated to confirmed orders must equal the starting stock. A counter of zero with two confirmed lines satisfies the first rule and fails the second. A counter of zero with no confirmed lines also fails the second rule. These are different incidents at the till, but the same reconciliation would detect both.
Give the inventory row a primary key identifying the branch and product, and declare the available quantity an integer with a non-null, nonnegative constraint. Require a positive integer purchase quantity as well. Otherwise subtracting a negative request would increase the stock. In our example the allocation lines are the only claims on inventory. A real shop that also holds units for unpaid reservations must count those holds separately and define exactly when a hold becomes a sale.
Suppose the handler reads the current quantity, checks it in application code, and writes the replacement value it calculated. Hala reads one. Before her write, Omar reads one too. Each calculates one minus one and sends a statement setting the counter to zero. Even if the database makes Omar's write wait behind Hala's, the number his application sends is still zero. Both handlers then insert a confirmed order line. Neither write tried to store a negative quantity, so the check constraint had nothing to reject.
| Point in the example | Available | Confirmed units |
|---|---|---|
| Before either checkout | 1 | 0 |
| After Hala's checkout | 0 | 1 |
| After Omar writes his stale result and confirms | 0 | 2 |
Wrapping each handler in a transaction gives each individual checkout an all-or-nothing outcome. Under PostgreSQL's default Read Committed isolation, a plain read still permits both buyers to observe one. What we need is a decision that stays valid through the write. The stock displayed on the product page can remain a useful estimate; forcing every shopper to lock the shelf just to view it would give the wrong operation control of the queue.
For a single product, put both the availability test and the subtraction in the update itself. Bind the validated quantity as an integer, use the branch and product key, and treat the presence of a returned row as the result of the attempt. The following uses literal inputs so you can follow the numbers in two database sessions.
UPDATE inventory
SET available = available - 1
WHERE branch = 'DXB' AND sku = 'BLUE' AND available >= 1
RETURNING available;
Hala reaches the row first. Her statement changes one to zero and returns a row whose value is zero. That zero is a successful result: she took the last unit. Omar issues the same statement while her transaction remains open. If she commits, PostgreSQL at Read Committed evaluates his condition against the updated row. Zero is too small, so his statement returns no rows. Code that treats a numeric zero as false would reject the very customer who secured the notebook. Test the number of returned rows. PostgreSQL on concurrent updates · UPDATE and its returned rows
Now change just one event. Hala's transaction rolls back while Omar is waiting. The original one is available again and his update can succeed. The winner is whoever obtains a committed allocation, which need not be the first person who saw the listing or even the first person whose statement returned a row. A receipt sent before commit can mislead the customer in this second history. Wait for the database to acknowledge commit before calling the purchase confirmed.
Imagine deploying the conditional update as a statement that commits automatically. Hala secures the last unit. The order insert that follows fails because a required pickup branch is missing. Inventory is now zero, and the clerk has no order to prepare. The guarded update did its job on the counter, yet the stock balance is short by one. For checkout, group the conditional update and the allocation record in one transaction on one connection.
Begin the transaction, execute the update and inspect its returned rows. If there are none, end the transaction and report the item unavailable for this checkout. If one row comes back, insert the order and its line with the agreed quantity. Commit only after every required insert succeeds. An insert failure must roll back the entire transaction. The response that reports success should carry the ID of the committed order. This combination gives the clerk a durable explanation for every unit that disappeared from the shelf. How PostgreSQL groups writes in transactions
There is also a reason to choose a locking read. Suppose checkout must inspect the branch's inventory row to decide between two fulfillment policies, then save the decision with the allocation. Begin a transaction and select the identified row FOR UPDATE. After acquiring the lock, inspect its current quantity, make the decision, write the decrement and the matching order line, then commit. A competing checkout that takes the same lock must wait and use the quantity it obtains after the wait. An ordinary earlier read from a product cache cannot supply that decision. PostgreSQL row-level locks
For one subtraction the guarded statement has fewer round trips. A locking read gives application code room to evaluate several fields together, at the cost of a longer period holding the row. Both approaches require a transaction around related writes. Neither justifies keeping a lock open while the buyer chooses a delivery time or while the service waits for an email provider. Acquire the stock as late as practical and release the lock by committing once the local business records are consistent.
Create a test branch with one BLUE unit and no order lines. Commit that fixture so two independent database connections can see it. In connection A begin a transaction and run the conditional update. Leave it open after receiving zero. In connection B begin another transaction at Read Committed and issue the same update. With A still holding the row lock, B should wait. For an automated test, coordinate independent workers at this point and bound the wait so a failed setup produces a useful test failure.
In A insert Hala's order and its line, then commit. B should resume with an empty result. Have B decline the purchase without inserting an order. From a fresh connection, count confirmed units for the test branch and read the inventory row. Expect one confirmed unit, zero available and exactly one order eligible for pickup. The name of the winner is immaterial in a freely racing test; the committed quantities and the number of successful responses are the evidence that matters.
Reset the fixture and repeat, this time failing A's order insert and rolling A back. B should receive a row containing zero and be able to commit Omar's order. Check from the third connection that Hala has no surviving line. This variant detects a handler that catches the order error but keeps a previously committed decrement. It also separates a legitimate stock rejection from a database timeout. A timeout gives the server no basis to tell the customer that somebody else bought the notebook.
Consider a basket with a notebook and a pen. If the customer requested them as a set, success means that both allocations and their order lines commit together. Update the rows in a consistent branch-and-product order in every checkout. If the second item is unavailable, roll back the first allocation before returning the result. A consistent order reduces avoidable deadlocks; if the database still aborts a transaction, a retry has to repeat the complete decision with current values. Retrying just the final insert loses the reasoning behind the original allocation.
A lost response presents another question. The database can commit Hala's order just before her phone disconnects. Her next attempt should recover the original order for the same checkout request. Give the request a stable identifier and enforce uniqueness for that customer and identifier. A fresh purchase receives a fresh identifier. The last-unit check controls competition for a physical item. The request identifier tells the service whether the same customer is repeating a decision already recorded.
Start with three notebooks. Hala requests two, and Omar requests two. Hala obtains the row first, sees one remaining after her update, then her order insert fails. Omar is waiting. What should he receive, what should the clerk see, and what would change if Hala had committed?
Answer. After Hala rolls back, Omar can subtract two from three. He receives a successful result with one remaining and can commit an order for two. The clerk should find only Omar's order and should count one available plus two allocated. If Hala had committed, Omar's predicate would fail against the remaining one. He would receive no allocation, even though one notebook is still for sale. In both histories the sums agree and precisely one buyer gets the quantity requested.
YOUR TAKE
Choose one reaction for this article.
A cookie helps limit repeat responses. Your feedback is private.