# Two Shoppers, One Item Left. What Does Postgres Do?

> Two shoppers try to buy the last mug. Run two Postgres sessions side by side to see how one conditional update prevents an oversale, even when a checkout rolls back.

Published: 2026-11-25
Canonical: https://layerbase.com/blog/postgres-two-shoppers-last-item

There’s one mug left in the Black Friday sale. Two shoppers click Buy. Both checkouts read a stock count of one. By the time the warehouse opens, the database shows zero mugs on the shelf and two orders to pack.

You can make that happen on a laptop. You can also fix it, leave one checkout halfway through, and watch the other one wait. I ran the examples below in two local psql sessions on PostgreSQL 19.0 at its default isolation level, `read committed`. The terminal output comes from those runs.

## Open a terminal for each shopper

Use a fresh local database so you can reset the stock between checkouts. With the [Layerbase CLI](https://layerbase.com/docs/cli), run this in terminal A. If you need the CLI first, install it with `pnpm add -g layerbase`.

```sh
lbase create last-mug --engine postgresql --start
lbase connect last-mug
```

In terminal B, run `lbase connect last-mug` as well. Each window now has its own database session. In A, create the two tables and put one mug on the shelf.

```sql
CREATE TABLE inventory (
  sku text PRIMARY KEY,
  stock integer NOT NULL CHECK (stock >= 0)
);
CREATE TABLE orders (
  buyer text PRIMARY KEY,
  sku text NOT NULL REFERENCES inventory
);
INSERT INTO inventory VALUES ('mug', 1);
```

## Sell one mug twice

Run these two lines in A, then in B. Leave both transactions open.

```sql
BEGIN;
SELECT stock FROM inventory WHERE sku = 'mug';
```

Both terminals print the same answer.

```text
 stock
-------
     1
(1 row)
```

Suppose the checkout code subtracts one from the value it just read and sends the result back to Postgres. Both shoppers’ apps calculate zero. Run this in A, then repeat it in B with `'B'` as the buyer.

```sql
UPDATE inventory SET stock = 0 WHERE sku = 'mug';
INSERT INTO orders VALUES ('A', 'mug');
COMMIT;
```

Count the orders alongside the remaining stock.

```sql
SELECT stock, (SELECT count(*) FROM orders WHERE sku = 'mug') AS orders
FROM inventory WHERE sku = 'mug';
```

```text
 stock | orders
-------+--------
     0 |      2
(1 row)
```

The stock constraint passed both times. Zero is a perfectly legal value, and the second checkout asked Postgres to write zero to a row that already held zero. The mistake was treating an earlier read as permission to place an order.

## Make the update claim the mug

Reset the example in A. Use this same reset between the next two runs, after both transactions have ended.

```sql
TRUNCATE orders;
UPDATE inventory SET stock = 1 WHERE sku = 'mug';
```

This time, ask Postgres to decrement the current stock only while there’s a mug left. In **terminal A**, run the following and leave the transaction open.

```sql
BEGIN;
UPDATE inventory SET stock = stock - 1
WHERE sku = 'mug' AND stock > 0
RETURNING stock;
```

```text
 stock
-------
     0
(1 row)

UPDATE 1
```

That zero is good news for A. One row came back, and zero is the stock **after** A claimed the last mug. In A, run `INSERT INTO orders VALUES ('A', 'mug');`. Leave the transaction open so the order and the stock change still share the same fate.

In **terminal B**, run the same `BEGIN;` and conditional `UPDATE ... RETURNING stock;` shown above. B’s prompt stays busy. It has reached the inventory row and is waiting for A. Leave B alone and switch back to A.

### First run: A commits

In A, type `COMMIT;`. Here’s what the two windows printed.

| Terminal A | Terminal B |
| --- | --- |
| `COMMIT;` returns `COMMIT` | The waiting update finishes and prints the result below. |

```text
 stock
-------
(0 rows)

UPDATE 0
```

B got zero **rows**. At Read Committed, Postgres checks the updated row against B’s `WHERE` clause after A commits. The stock is now zero, so B has nothing to claim. The checkout should report sold out. In B, run `ROLLBACK;` to end its transaction, then `SELECT buyer, sku FROM orders;`.

```text
 buyer | sku
-------+-----
 A     | mug
(1 row)
```

### Second run: A rolls back

In A, run the reset, then repeat A’s `BEGIN`, conditional update, and order insert. In B, repeat `BEGIN` and the same conditional update. Once B is waiting again, change just one line in terminal A.

| Terminal A | Terminal B |
| --- | --- |
| `ROLLBACK;` returns `ROLLBACK` | The waiting update finishes and prints the result below. |

```text
 stock
-------
     0
(1 row)

UPDATE 1
```

Rolling back put A’s mug back on the shelf and discarded A’s order. B could now decrement the stock itself. In B, finish the order and check who gets the mug.

```sql
INSERT INTO orders VALUES ('B', 'mug');
COMMIT;
SELECT buyer, sku FROM orders;
```

```text
INSERT 0 1
COMMIT
 buyer | sku
-------+-----
 B     | mug
(1 row)
```

## What to put in your checkout handler

Check the **number of rows returned** by the conditional update. With one row, insert the order using the same connection and transaction, then commit. With zero rows, end the transaction and tell the shopper the item sold out. Testing whether the returned stock value is truthy would turn away the customer who successfully claimed the last mug.

Keep the transaction short. We held A open so you could see the wait. In a real checkout, commit the reservation before calling a payment provider and decide when an unpaid reservation should expire. The concurrency behavior above is specific to Read Committed. [PostgreSQL’s transaction isolation guide](https://www.postgresql.org/docs/19/transaction-iso.html#XACT-READ-COMMITTED) explains how the other levels handle competing updates.

When you’re finished, type `\q` in both windows and run `lbase stop last-mug` from your shell. The database stays on disk if you want to try the race again.
