Scrivio Interview library
DesignAdvanced7 min read · updated 12 November 2026

A service used a ReentrantLock to make sure only one reservation per seat is created. After scaling to four instances behind a load balancer, double bookings appear. Design a correct approach and discuss the distributed-lock options.

A ReentrantLock only protects threads inside one JVM, so four instances have four unrelated locks and two of them can book the same seat at once. The correct design lets the database enforce the rule, ideally with a unique index on (event, seat), or with optimistic versioning or SELECT ... FOR UPDATE inside a transaction. Distributed locks in Redis or ZooKeeper are possible but need leases and fencing tokens, and the operation should be idempotent so retries never create a second booking.

Why this question is asked

This is a classic scaling bug: code that was correct on one instance becomes wrong the day a second instance starts, and nothing in the code changed. Interviewers ask it because it shows whether we understand the scope of a lock, and whether we reach for the simplest reliable tool, which is usually the database, before reaching for distributed locking. In this answer, we will see why the in-JVM lock stopped working, design the fix around a database constraint, look at optimistic and pessimistic row locking as alternatives, examine what distributed locks really need, and make the operation safe to retry.

1Why the ReentrantLock Stopped Working

A ReentrantLock is an object in the heap of one Java process. Threads in that process coordinate through it because they share that memory. A second instance behind the load balancer is a different process, often on another machine, with its own heap and its own lock object. The two locks know nothing about each other.

So when two customers click the same seat at the same moment and the load balancer sends them to instance 1 and instance 3, each request takes its own instance's lock, each checks the database, each sees the seat as free, and each inserts a reservation. The lock still works perfectly within each instance; it just no longer covers the whole system.

Step throughTwo instances, two locks, one seat
Request AInstance 1Instance 3Database
book seat 12F
local lock acquired
local lock acquired (request B)
is 12F free?
is 12F free?
yes
yes
INSERT reservation
INSERT reservation
two rows for 12F

10 messages in order. Play them, or step through them one at a time.

Each lock is held correctly, but they guard different processes, so both check-then-insert sequences succeed.

2Let the Database Enforce the Rule

The rule 'one reservation per seat per event' is a fact about the data, and the database is the one component that every instance shares. A unique index states the rule once, and the database checks it atomically on every insert, whichever instance sends it and however many instances we run.

SQL
CREATE UNIQUE INDEX uq_reservation_seat ON reservation (event_id, seat_id);
INSERT INTO reservation (event_id, seat_id, customer_id) VALUES (42, '12F', 1001); -- 1 row
INSERT INTO reservation (event_id, seat_id, customer_id) VALUES (42, '12F', 2002); -- ERROR: duplicate key

In Spring the second insert surfaces as a DataIntegrityViolationException (more precisely a DuplicateKeyException in many setups; check your driver and version). We catch it and answer 409 Conflict with 'seat already taken'. No lock is needed in Java at all, and the check-then-insert race disappears because the insert itself is the check.

If cancelled reservations stay in the table, the index must only cover active rows. PostgreSQL supports a partial unique index such as CREATE UNIQUE INDEX ... ON reservation (event_id, seat_id) WHERE status = 'ACTIVE'. MySQL 8.4 has no partial indexes, so there we model it differently, for example by deleting or moving cancelled rows, or with a nullable column that is only set for active rows.

3Alternatives: Optimistic Versions and SELECT ... FOR UPDATE

Sometimes the model has one row per seat with a status column, created when the event is set up. Then two other database techniques fit. With optimistic locking, the row carries a version number, and the update only succeeds if the version is still the one we read. In JPA a field annotated with @Version does this for us.

SQL
UPDATE seat SET status = 'BOOKED', customer_id = 1001, version = version + 1
WHERE event_id = 42 AND seat_id = '12F' AND status = 'FREE' AND version = 7; -- 1 row updated
-- the second instance sends the same statement with version = 7
-- 0 rows updated: someone changed the row first, so report "seat taken"

With pessimistic locking, the transaction first runs SELECT ... FROM seat WHERE ... FOR UPDATE. The database locks that row until commit, so a second transaction on another instance waits at its own SELECT, then sees the status BOOKED and stops. This works well when conflicts on one seat are frequent, but it holds row locks for the length of the transaction, so the transaction must stay short and must not call remote services while holding them.

For seat booking, conflicts are rare compared with total traffic, so the unique index or the conditional update is usually the better choice: no waiting, and the losing request learns immediately that the seat is gone.

4Distributed Locks and Their Catch

A distributed lock is a lock held in a shared service, such as a Redis key set with SET key value NX PX 30000, or an ephemeral node in ZooKeeper. Because a process may crash while holding it, such a lock is always a lease: it expires after a time unless renewed. And this is the catch. A process can be paused, by a long garbage collection, a VM migration or a network partition, for longer than the lease. The lease expires, another instance takes the lock, and then the first process wakes up still believing it holds the lock, and writes.

The defence is a fencing token: a number that increases each time the lock is granted. The holder sends its token with every write, and the protected resource rejects any write with a token lower than the highest it has already seen. Notice what this means: the resource itself must check the token, which for a database means storing it and comparing it, which is a conditional update again. That is why, for data that lives in one database, the database constraint is simpler and safer than any distributed lock.

Step throughA paused holder and a fencing token
Instance 1Lock serviceInstance 3Database
acquire
granted, token 33
long GC pause, lease expires
acquire
granted, token 34
write with token 34
ok
write with token 33
rejected: 33 < 34

9 messages in order. Play them, or step through them one at a time.

Without the token check in the database, instance 1's late write would silently overwrite the newer booking.

5Making the Booking Idempotent

Even with a correct constraint, retries can still cause trouble. A client sends 'book 12F', the booking succeeds, the response is lost on the network, and the client retries. With the unique index the retry fails with 'seat taken', which is wrong from the customer's point of view: they did get the seat. Worse, if the client retries with a different seat after an error, they may end up with two bookings.

The usual fix is an idempotency key: the client generates an id for the attempt and sends it as a header. The server stores the key with the reservation, under its own unique index, and if the same key arrives again it returns the original result instead of trying again. Retries then become safe, which matters because timeouts and retries are normal in a system with a load balancer and four instances.

Ways to guarantee one booking per seat
ApproachWhat enforces itMain cost
Unique index (event, seat)Database on every insertHandle duplicate-key error as 409
Conditional update with versionRow version checkNeeds one row per seat; retry or report
SELECT ... FOR UPDATERow lock until commitWaiting; keep transactions short
Redis or ZooKeeper lockLease in a shared serviceNeeds fencing tokens; extra moving part
In-JVM ReentrantLockOne process onlyWrong with more than one instance

6Follow-up questions

Is Redis with SET NX PX good enough for this?

For efficiency, such as avoiding duplicate work, it is often fine. For correctness, such as never double-booking, it is not enough on its own, because a paused holder can outlive its lease and Redis itself gives no fencing token by default. If the data is in a relational database anyway, the constraint there is the right tool.

What about Redlock across several Redis nodes?

Redlock reduces the risk of one Redis node failing, but it still depends on timing assumptions about clocks and pauses, and it still needs the resource to check something like a fencing token to be safe. Using it does not remove the need to think about the paused-holder case.

Would serializable isolation solve it?

In PostgreSQL, SERIALIZABLE would detect the check-then-insert conflict and abort one transaction, which the application must then retry. It works, but a unique index expresses this particular rule more directly and cheaply.

7Conclusion

In this answer, we saw that an in-JVM lock protects one process only, which is why scaling to four instances produced double bookings. We moved the rule into the shared database with a unique index on event and seat, looked at a versioned conditional update and SELECT ... FOR UPDATE as alternatives, explained why distributed locks need leases and fencing tokens because a paused process may still think it holds the lock, and made the booking idempotent so retries cannot create duplicates.

What to say in the interviewAbout 80 seconds aloud

Open with

The ReentrantLock only ever protected threads inside one JVM. With four instances there are four independent locks, so two requests for the same seat on different instances both check that it's free and both insert.

Then, if they want more

The fix is to put the rule where all instances meet, which is the database. I'd add a unique index on event and seat, so the insert itself is the check; the losing request gets a duplicate key error, which I map to a 409 seat taken.

If the model has one row per seat with a status, a conditional update with a version column works the same way, or I can use SELECT FOR UPDATE inside a short transaction when conflicts are frequent. I'd be careful with distributed locks in Redis or ZooKeeper.

They're leases, and a process can pause in a GC or a partition past its lease while still believing it holds the lock, so a safe design needs fencing tokens that the database checks, and at that point the constraint is simpler.

Finally, I'd make the booking idempotent with a client-supplied idempotency key, stored under its own unique index, so a retry after a lost response returns the original booking instead of an error or a second seat.

About this answer

Last updated
12 November 2026
Versions it names
MySQL 8.4
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "A service used a ReentrantLock to make sure only one reservation per seat is created....": https://scrivio-interview-library.netlify.app/java/locks/1f003dfa04/