WILLIAM TECH LABLEARN · BUILD · DEPLOY
PostgreSQL

PostgreSQL: prevent two sales from consuming the same stock

Two requests may read the same stock at the same time. Correctness requires a transactional approach.

← Blog

Two requests may read the same stock at the same time. Correctness requires a transactional approach.

The concurrency problem

If two operations both read a quantity of one and update it independently, both may assume the item is available.

A safer approach

Use a transaction and either row locking with SELECT ... FOR UPDATE or a conditional atomic UPDATE that only succeeds when stock is sufficient.

Test the behavior

Write concurrent PostgreSQL integration tests to confirm that only one sale succeeds when a single unit remains.