The 30 second answer
The bug is check-then-act: both threads see the seat as free, then both book it. In one JVM I make the check and the write a single atomic step with ConcurrentHashMap.putIfAbsent, so exactly one caller gets null back. With several servers I push that atomic step into the database: a unique constraint on event and seat, or a conditional UPDATE where the seat is still free. The loser gets zero rows or a constraint error and I return "already taken".
The race. The naive version reads first and writes second: if (!booked.containsKey(seat)) booked.put(seat, user). Two threads can both pass the check before either writes, and then both users get a confirmation. Making the method synchronized fixes this inside one JVM, but production runs several instances, and a Java lock does nothing across them.
In memory: one atomic call. ConcurrentHashMap.putIfAbsent only sets the value if the key is absent, and the whole check-and-set is atomic. It returns null only to the caller that actually inserted the value.
import java.util.concurrent.ConcurrentHashMap;
public class SeatBooking {
// seatId -> userId of the person who booked it
private final ConcurrentHashMap<String, String> bookedBy = new ConcurrentHashMap<>();
// true only for the one caller that actually got the seat
public boolean book(String seatId, String userId) {
return bookedBy.putIfAbsent(seatId, userId) == null; // atomic check-and-set
}
}I tested this with 16 threads released together by a CountDownLatch, 200 times. Every round had exactly one winner.
Across servers: let the database decide. I use one of two patterns, depending on whether seats are rows or a counter.
-- Reserved seating: the constraint guarantees one booking per seat
CREATE TABLE booking (
event_id bigint NOT NULL,
seat_id text NOT NULL,
user_id bigint NOT NULL,
UNIQUE (event_id, seat_id)
);
INSERT INTO booking (event_id, seat_id, user_id) VALUES (?, ?, ?);
-- the second insert fails with a unique violation -> "seat already taken"
-- Seat rows with a status: a conditional update is the check-and-set
UPDATE seat SET status = 'BOOKED', user_id = ?
WHERE event_id = ? AND seat_id = ? AND status = 'FREE';
-- 1 row updated = you got it; 0 rows = someone else didWhy the conditional update is safe in PostgreSQL's default Read Committed level: the second UPDATE waits for the first transaction's row lock. When the first commits, the second re-evaluates its WHERE clause against the new row version. It now sees BOOKED and updates 0 rows.
What to say next. Keep the unique constraint even if you also add Redis seat holds or optimistic locking, because it's the last line of defense. If the user needs a few minutes to pay, use a temporary hold with an expiry and confirm it with the same conditional update.
Sources (3)
- ConcurrentHashMap Javadoc (Java 21)docs.oracle.com
- PostgreSQL 17 docs: Read Committed isolation levelpostgresql.org
- PostgreSQL 17 docs: Constraints (unique constraints)postgresql.org