Two customers, one item left: preventing overselling with one PostgreSQL UPDATE
Two customers. One kurta left. Both press Place order within the same second. In many stores, both orders go through. Somebody finds out later, usually the shop owner, on the phone, apologising. I'm building ShopKit PK , a platform that runs many online shops for Pakistani sellers from one codebase. Most of those sellers ship cash on delivery, where every wrong order becomes a refused parcel. So…
Two customers attempting to purchase the last item in stock simultaneously can result in overselling if proper measures are not taken. In the ShopKit PK platform, used by many online shops run by Pakistani sellers, overselling is a critical issue due to the cash on delivery shipping method. To prevent this, the platform uses a single PostgreSQL UPDATE statement to both check and update the stock levels. This approach avoids the need for explicit locks and ensures only one order can be processed when stock is insufficient.
The key to this solution is reserving stock in a single conditional update statement. The query subtracts the quantity being reserved from the available stock and returns the updated stock levels if enough stock is available. If the stock is insufficient, the query returns no rows, indicating the item is out of stock. This method leverages PostgreSQL's row locking, which prevents other requests from modifying the stock levels while the update is in progress.
To avoid deadlocks when reserving multiple items in a single order, the platform ensures that all reservations are made in the same order by sorting them by the variant_id. This consistent ordering allows multiple orders to be processed in a queue-like manner without interfering with each other.
Reserving stock at the time of order placement rather than during the checkout process helps prevent items from appearing sold out due to abandoned carts. For cash on delivery orders, the reservation remains valid indefinitely since the order itself is valid. For online payments, the reservation expires at the payment deadline set by the store.
To handle cases where reservations may expire, the platform employs a lazy cleanup process where expired reservations are released whenever a reservation fails. This approach ensures that stock levels remain accurate without relying on a separate cron job, which may not always be reliable on free hosting tiers.
Lastly, to protect against duplicate orders caused by issues like double-clicks or flaky mobile networks, the platform uses an idempotency key for each checkout request. This key is included in the transaction, allowing the system to detect and reject duplicate orders, ensuring each order is processed only once.
Rewritten by urgent.news; may contain errors — check the original.
Source: dev.to