· 7 min read
Check Then Write: Race Conditions Between Concurrent Requests
Checking that a seat is free before selling it, or that a quote is still pending before recording a decision, feels natural. The pattern is called check-then-act. With one user it always works. When two requests arrive at the same moment, both see "free" and both write. This post is about how I handled that race condition in two projects: with a partial UNIQUE index in my airline reservation system, and with PostgreSQL's row version (optimistic concurrency) in Tamirhane, my repair shop app.
How the race happens
Selling a seat goes like this:
- Is seat 17C taken? Ask the database.
- If it is, return an error; if not, write the ticket.
When two requests run these steps at the same time:
| Time | Request A | Request B |
|---|---|---|
| 1 | Is 17C taken? No. | |
| 2 | Is 17C taken? No. | |
| 3 | Write the ticket. | |
| 4 | Write the ticket. |
The check was correct, but B got in between A's check and A's write. Result: two passengers in one seat. However carefully the code is written, as long as the time between those two steps is not zero, the race is possible.
The lasting fix is to enforce the rule at write time, in a single atomic step. Databases have their own tools for that.
Airline: a partial UNIQUE index
My airline reservation system is a desktop app on SQLite. When selling a seat, it first reads the occupied seats and gives a clear error if the chosen one is taken:
final Set<String> taken = FlightService.occupied(c, flight.id());
// ...
if (taken.contains(seat.code()))
throw new AirlineException("seatTaken", seat.code());
That check exists to give the user a good message. The real rule lives in the database:
-- A seat on a flight can be on only one valid ticket: the database blocks double sales too.
-- Cancelled tickets (active = 0) are not in the index, so the seat can be sold again.
CREATE UNIQUE INDEX IF NOT EXISTS tickets_seat ON tickets(flight_id, seat) WHERE active = 1
Two decisions here.
Why a partial index? A plain UNIQUE(flight_id, seat) would count cancelled tickets too, and that seat could never be sold again. With WHERE active = 1 the index covers only valid tickets; cancelling a ticket frees the seat.
Why an index when there is already a check? In this app, writes go through a single connection and a synchronized method, so two sales inside the app cannot interleave. But that guarantee depends on application code. Another path that touches seats, such as changing a seat, a second program opening the database later, or a new feature written without the lock, would fall outside it. A rule that lives next to the data holds whichever way you come in.
If the index is violated, the database raises an error; the service catches it and tells the user "this seat was just taken" instead of showing a technical message:
} catch (DataException e) {
// If another operation took the same seat at the same moment, the UNIQUE index blocks it
if (e.isUniqueViolation())
throw new AirlineException("seatJustTaken");
throw e;
}
I wrote the test with requests that really run at the same time. 16 threads wait at a gate to grab the same seat; when the gate opens they all try at once, and exactly one is expected to succeed:
final CountDownLatch start = new CountDownLatch(1);
for (int i = 0; i < 16; i++) {
results.add(pool.submit(() -> {
start.await();
try {
airline.bookings().book(/* same flight, 17C */);
return true;
} catch (AirlineException e) {
return false;
}
}));
}
start.countDown();
// ...
assertEquals(1, ok);
Tamirhane: optimistic concurrency with a row version
Tamirhane is a web app on PostgreSQL, and every request opens its own database context. An in-process lock is no use here: two requests arriving together run separately, and there may be more than one server one day.
The place where the race could happen was quote approval on the customer's tracking page. If a customer presses "Approve the repair" twice, or approves in one tab and declines in another, two requests read the work order at the same moment. Both see "awaiting approval" and both record a decision. Two decisions land in the history, and the work order can end up in the wrong state.
A UNIQUE index is not a natural fit here, because what needs protecting is not one column but the whole state of the work order. The options:
- Pessimistic locking: lock the row while reading (
SELECT ... FOR UPDATE). It works, but it means holding a lock on every read and carrying it until the transaction ends. - Optimistic concurrency: no lock. At write time, check "is the version I read still the same?"; if it changed, reject the write.
When conflicts are rare, optimistic concurrency fits better. Every PostgreSQL row has a system column called xmin: the ID of the transaction that last changed the row. It changes on every update, so it is a ready-made row version. Declaring it as a version column in EF Core takes one line:
// Row version (PostgreSQL's xmin system column): a state change cannot be saved twice at once
// (e.g. if a customer double-clicks quote approval, the second request gets a "changed" error).
b.Property<uint>("Version").IsRowVersion();
From then on, when EF Core updates a work order it adds the version it read to the WHERE clause. If another request changed the row in between, the version does not match, the update affects 0 rows and EF Core throws DbUpdateConcurrencyException.
In Clean Architecture the application layer does not know EF Core, so the infrastructure layer translates the error into its own type:
async Task IUnitOfWork.SaveChangesAsync(CancellationToken ct)
{
try
{
await SaveChangesAsync(ct);
}
catch (DbUpdateConcurrencyException e)
{
throw new ConcurrencyConflictException(e);
}
}
The use case turns that into a result, so the user sees a clear message rather than a 500 error:
try
{
await unitOfWork.SaveChangesAsync(ct);
}
catch (ConcurrencyConflictException)
{
return ApplicationErrors.ConcurrentChange;
}
In that case the tracking page says that a decision has already been made for this quote and the page shows the latest state. The buttons are also disabled after submitting, but that is only a convenience; the real protection is in the database.
The test replays the moment two requests read at the same time, using two separate database contexts against a real PostgreSQL:
// Two requests read the work order at the same time; both see "awaiting approval".
var a = (await first.Orders.GetByTrackingCodeAsync(code, default))!;
var b = (await second.Orders.GetByTrackingCodeAsync(code, default))!;
Assert.True(a.DecideQuote(true, "Ayşe Kaya", null, Now).IsSuccess);
await first.UnitOfWork.SaveChangesAsync(default);
Assert.True(b.DecideQuote(false, "Ayşe Kaya", null, Now).IsSuccess);
await Assert.ThrowsAsync<ConcurrencyConflictException>(() => second.UnitOfWork.SaveChangesAsync(default));
This test does not leave the race to timing. The interleaving is written out step by step, so it gives the same result on every run.
How the two fixes differ
| Partial UNIQUE index | Row version (optimistic concurrency) | |
|---|---|---|
| Protects | One rule: one seat, one ticket | The whole state of a record |
| On conflict | The insert is rejected | The update is rejected |
| Fits when | The rule can be expressed as a column combination | The rule spans several fields and business logic |
There is a third example in Casus: a room code is saved to Redis in one command with a "write only if the key does not exist" rule. Same idea: check and write in one atomic step.
What I took away
- Check-then-act is always open to a race. The check can stay to give the user a good message, but the rule itself has to be enforced atomically at write time.
- Putting the rule next to the data makes it hold on every path through the app: a UNIQUE or partial index, a row version, "write if absent" in Redis.
- An in-process lock trusts a single process. That can be enough on the desktop; on the web, requests run in separate contexts and, later, on separate servers.
- There are two ways to test a race: threads that really start at the same moment, or a deterministic test that writes the interleaving out step by step. The second one never fails for no reason.