BM
Bashar ModallalSOFTWARE · AI · SYSTEMS
SQL and Relational Database Engineering

Advanced · Lesson 9 of 12

Software Architecture

Choose an Isolation Level

Two customers book the last pottery wheel. Reproduce the write skew in PostgreSQL, retry a serializable transaction, and compare the result with a constraint or a lock.

Two booking slips on a studio counter face a single pottery wheel.

Two customers reach the last pottery wheel at the same time. Amal books workshop 17 through the studio website. Bilal books it at the front desk. Each receives a confirmation. When the instructor unlocks the studio, two people have a reservation and only one can take the class. Both payments could be genuine, and every individual database row could be perfectly valid. The error lies in the decision to accept the second reservation.

Our rule is precise enough to test. For workshop 17, the number of committed bookings must never exceed one. A customer may see an outdated availability screen, provided the final booking step enforces that rule. This distinction lets us put concurrency protection where it matters. A page view makes no promise. A committed reservation gives someone a claim on a physical wheel.

Set up two independent sessions

Use a disposable PostgreSQL database and two SQL clients connected to that same database. In either client, create this ordinary table once, outside an explicit transaction. A temporary table would be private to one client and would hide the very interference we want to study.

CREATE TABLE sq09_booking (
    request_id text PRIMARY KEY,
    workshop_id integer NOT NULL
);

The primary key identifies a request. If a phone resubmits the same request, we can look up its booking. Amal and Bilal, however, have different request IDs. The database can store both rows without violating that primary key. We have deliberately left workshop capacity out of the schema so that we can test whether the booking algorithm itself enforces it.

In each client, start a transaction with the statement below. Call the first client A and the second B. Keep both open. If your SQL editor automatically commits each selection, verify that it uses the same connection for the remaining steps. Using successive requests to a connection pool without reserving a connection can turn this exercise into several unrelated transactions.

BEGIN ISOLATION LEVEL REPEATABLE READ;

In A, execute the following statement. Leave the transaction open after it returns. Next execute the same statement in B, changing the literal clay-A to clay-B. Only after both statements have returned should you issue COMMIT in A and then COMMIT in B.

INSERT INTO sq09_booking (request_id, workshop_id)
SELECT 'clay-A', 17
WHERE NOT EXISTS (
    SELECT 1 FROM sq09_booking WHERE workshop_id = 17
)
RETURNING request_id;

The input to each decision is the set of visible bookings for workshop 17. In A that set is empty, so its SELECT supplies one candidate row to the insert. Its RETURNING result is clay-A. In B the set is also empty. A has written a row, but another transaction cannot yet see it. B therefore returns clay-B. Each insert wrote its own primary key. Under PostgreSQL Repeatable Read this sequence permits both transactions to commit.

From either client, now outside those transactions, run the audit query. It lists workshops exceeding our one-wheel limit. On this data its expected output is a single row with workshop_id 17 and bookings 2. Running it before the commits could conceal the violation. An audit should examine the state that subsequent customers and staff actually inherit.

SELECT workshop_id, count(*) AS bookings
FROM sq09_booking
GROUP BY workshop_id
HAVING count(*) > 1;

Explain the history before choosing a level

Try to place these two successful reservations in a line. If Amal's entire transaction happened first, Bilal would see her booking and insert nothing. Reversing their order simply exchanges their names. Neither serial order explains two confirmations. Each customer relied on a fact that the other customer's write invalidated. This is write skew. No two clients edited the same row, so looking for a lost update would send you to the wrong part of the system.

An atomic SQL statement still reads a particular view of the database. Combining the test and the insert into one statement removed an application round trip. It did not establish exclusive ownership of an empty set. Read Committed can also admit this history if B runs its statement while A's row is uncommitted. If A commits before B starts that statement, B sees the booking at Read Committed. A test that always runs the two requests back to back in one client will therefore give misleading reassurance.

Repeatable Read is valuable when several queries need one coherent view. For instance, an instructor can read a roster and then compute a total from the same snapshot while bookings continue elsewhere. Consistency of what one reader observes and consistency between two writers' decisions are different requirements. PostgreSQL documents the precise visibility and anomaly guarantees for each level in Transaction Isolation.

Repeat at Serializable and handle the losing request

After both original transactions have ended, clear only this exercise's rows by running DELETE FROM sq09_booking WHERE workshop_id = 17 in the disposable database and committing it. Start both clients again, this time with the statement below. Repeat the same two conditional inserts, with the same two distinct request IDs, before attempting either commit.

BEGIN ISOLATION LEVEL SERIALIZABLE;

PostgreSQL tracks dependencies between what transactions read and what overlapping transactions write. Here each reader used the absence of a row that the other writer supplied. With both booking paths at Serializable, the database cannot allow both decisions to stand. In this isolated two-client exercise, expect one accepted reservation and a serialization failure identified by SQLSTATE 40001. Be prepared to receive that error during a statement or at commit. The winner's identity is immaterial to capacity, and the application should make no promises about which client wins.

Suppose Amal commits. Bilal must abandon the failed transaction, clear any failed transaction state on his connection and start a fresh Serializable transaction. First look up his stable request ID. The query below returns no booking in this example. Run his conditional insert again. This time the capacity probe sees Amal's committed row, so RETURNING yields zero rows. Commit that outcome and tell Bilal the workshop is full. The audit now returns zero violations. A separate count for workshop 17 returns one booking.

SELECT request_id, workshop_id
FROM sq09_booking WHERE request_id = 'clay-B';

The error and the empty result have different meanings. A serialization failure says the database could not accept this attempt's view of concurrent activity. It gives no final answer about availability. An empty result after the fresh attempt is a business decision. Retrying that result in a tight loop would make a full workshop expensive to visit. If the ID lookup instead finds the caller's own committed reservation, verify it matches the requested workshop and return the existing confirmation. Reusing an ID for a different workshop calls for a request conflict.

A real retry loop encloses the ID lookup, capacity test, write and commit. Discard in-memory decisions from the failed attempt. Bound the number of attempts and total elapsed time, add a short randomized delay between conflicts, and release the connection while waiting. When that budget runs out, report a temporary failure and let the caller reuse the same request ID. Keep sending confirmation mail outside the retry loop. One option is to store a uniquely keyed notification alongside the accepted booking, then deliver it separately with duplicate handling. See PostgreSQL's Serialization Failure Handling for the transaction boundary that a retry must cover.

Choose what fits the studio

For exactly one wheel per workshop, a unique constraint on workshop_id expresses the rule directly. Clean up conflicting historical rows before adding it. Then a conditional insert using ON CONFLICT (workshop_id) DO NOTHING can report the occupied wheel, even when a different writer bypasses the website. Preserve the request key as a separate guarantee. Repeated submission by the same customer and competition from a different customer require different responses, and the application needs enough information to distinguish them.

Suppose tomorrow's workshop has six wheels, any two of which might be reserved for maintenance. A unique workshop ID would reject valid bookings. If availability belongs to one inventory row, every booking path can update that row conditionally while positive capacity remains and create the booking in the same transaction. Another design locks a persistent parent workshop row first. Under Read Committed, count the bookings in a subsequent statement after acquiring the parent lock. That fresh statement sees the preceding holder's commit. All paths that change the relevant capacity or consume a seat must cooperate. Locking just the matching booking rows in an empty workshop has nothing to lock. PostgreSQL describes the competing lock modes in Explicit Locking.

Serializable becomes attractive when the decision spans several changing sets, such as instructor assignments, maintenance windows and reservations, and every participant in that decision can follow the protocol. There is a price when many users want the same seat. Work done by an aborted transaction must be repeated, and longer transactions keep potentially conflicting decisions in flight longer. A parent lock also has a price. Waiters queue even when a recount would be cheap. Evaluate both designs with the booking traffic you expect, including cancellations and concentrated bursts when registration opens.

For a comparison, send the same number of distinct requests against the same initial inventory. Record confirmed seats, invariant violations, serialization failures, attempts per request and the slowest five percent of response times. Separate sold-out results from technical failures. A design returning quick errors can appear faster while serving fewer customers. Compare completed decisions within the same deadline and inspect the hot workshop separately from the quiet ones. Any committed overbooking disqualifies a design before latency enters the discussion.

Exercise

Give workshop 17 two wheels and start it with one committed booking. Replace the absence check with a count of bookings for that workshop below two. Use two new IDs. Predict the final count under Repeatable Read when both clients finish their inserts before either commits. Then repeat with Serializable and retry the failed request from the beginning. Record the row counts and distinguish a retryable error from a sold-out decision.

A passing result explains why both snapshots initially count one, why three bookings are possible in the first run, and why the second run ends with two. The retried request sees two occupied wheels and inserts zero rows. Finish by naming the fact your production database should protect and the cheapest mechanism that protects it across every path that can sell a seat.

اقرأ الدرس بالعربية

YOUR TAKE

What did you think?

Choose one reaction for this article.

Was this useful?

A cookie helps limit repeat responses. Your feedback is private.

Share this noteLinkedIn ↗X ↗Email ↗

Keep exploring.

Software Architecture9 min read

Migrate a Busy Table Online

Move a live parcel table from a Boolean to a service code. Backfill in batches, find stale values, and prove when label readers can switch.

Software Architecture9 min read

Read a PostgreSQL Query Plan

A fee report returns one summary row, but its scan finds a thousand tickets where the planner expects roughly ten. Diagnose the estimate and test the I/O hypothesis.

Software Architecture9 min read

Design an Index for a Real Query

A dispatch clerk needs twenty ready tickets from 100,000 records. Choose a composite index for her queue and measure what the faster lookup costs on inserts.