← Case study

02 · DATABASE

Protect the last position

Make allocation a transaction, then prove two callers cannot both win.

Learning objective

Explain the serialization boundary and reproduce a competing-booking conflict.

The engineering problem

Two requests can both read the same vacancy before either writes a reservation. Availability displayed in the browser provides no allocation guarantee.

STEP 1

Choose the authority

The reference service stores organizations, positions, quotes, allocations, pallets, movements, and accepted tariffs in PostgreSQL. Operational changes and their billing evidence commit together.

STEP 2

Lock before validating

Every allocation-changing reference operation locks the warehouse row using SELECT … FOR UPDATE. A separate subsequent statement reads current state under READ COMMITTED. The same boundary covers receiving, release, amendments, blocks, and cancellation.

STEP 3

Retry the whole operation

Transient lock, deadlock, and serialization failures restart the entire transaction with bounded retries. Hold creation checks every point in the requested interval; confirmation validates the still-active hold atomically.

YOUR TURN

Make the behavior visible.

  1. Use the sandbox's capacity-race exercise to create two quotes for all eight Denver positions.
  2. Submit both holds against the same workspace revision.
  3. Observe one committed hold; the other attempt must refresh and is then rejected for insufficient capacity.
Open the sandbox ↗

Acceptance evidence

At most eight positions are promised. The PostgreSQL reference integration test competes through the actual database; the hosted exercise competes through server-side compare-and-set.

Read the working source.

These files belong to the downloadable PostgreSQL reference. The hosted companion has its own bounded state machine and persistence adapter.

Design review

Why must the availability query run after the warehouse lock has been acquired?

Review the tradeoff

READ COMMITTED starts a fresh snapshot for each statement. Acquiring the shared warehouse lock before reading current allocations prevents a waiting caller from validating against a stale pre-lock view.