If you are interviewing for a Junior+ or Middle Java Backend role, there is a high chance you will get a classic take-home assignment: build a ticket, seat, or inventory booking service.
At first glance, it looks like a trivial CRUD task:
- Check if
availableSeats > 0. - Decrement
availableSeats. - Save the booking.
In reality, this naive approach fails almost every code review. When 20 users try to book the last 5 tickets at the exact same millisecond, a classic race condition (Lost Update) occurs, and your service ends up selling 15 tickets when only 5 existed.
Here is how to build a production-grade solution using Spring Boot 3, PostgreSQL, and JUnit 5 that passes senior-level code reviews.
1. Database-Level Defense: CHECK Constraints
Never rely solely on Java application logic to protect data integrity. Manual SQL queries, batch jobs, or future microservice endpoints might bypass your service layer.
Always enforce invariants directly in your Flyway/Liquibase PostgreSQL migration:
CREATE TABLE events ( id BIGSERIAL PRIMARY KEY, title VARCHAR(255) NOT NULL, total_seats INT NOT NULL CHECK (total_seats > 0), available_seats INT NOT NULL CHECK (available_seats >= 0) ); If a bug ever slips through your Java code, PostgreSQL physically refuses to commit a negative seat count.
2. Solving the Race Condition with Pessimistic Locking
For high-contention booking endpoints (many threads fighting over a few remaining seats), Optimistic Locking (@Version) triggers massive OptimisticLockException failures, forcing you to write complex retry loops.
Instead, Pessimistic Locking (SELECT ... FOR UPDATE) queues competing transactions cleanly at the database row level:
public interface EventRepository extends JpaRepository<Event, Long> { @Lock(LockModeType.PESSIMISTIC_WRITE) @Query("SELECT e FROM Event e WHERE e.id = :id") Optional<Event> findByIdForUpdate(@Param("id") Long id); } Inside your @Transactional service method, the thread acquires an exclusive row lock, validates availability, decrements the counter, and releases the lock upon commit:
@Transactional public BookingResponse bookSeat(Long eventId, String userEmail) { Event event = eventRepository.findByIdForUpdate(eventId) .orElseThrow(() -> new ResourceNotFoundException("Event not found")); if (event.getAvailableSeats() <= 0) { throw new NoSeatsAvailableException("No seats available for this event"); } event.setAvailableSeats(event.getAvailableSeats() - 1); eventRepository.save(event); Booking booking = Booking.createPending(event, userEmail); return BookingResponse.from(bookingRepository.save(booking)); } 3. Don't Forget Unpaid Reservation Cleanup (@Scheduled)
A real-world booking system cannot hold seats forever if a user abandons checkout. Create bookings in a PENDING state with an expiresAt timestamp, and run a periodic cleanup scheduler:
@Scheduled(fixedRateString = "\${booking.cleanup.rate-ms:60000}") @Transactional public void releaseExpiredBookings() { List<Booking> expired = bookingRepository.findAllByStatusAndExpiresAtBefore( BookingStatus.PENDING, Instant.now() ); for (Booking booking : expired) { Event event = eventRepository.findByIdForUpdate(booking.getEvent().getId()) .orElseThrow(); booking.setStatus(BookingStatus.EXPIRED); event.setAvailableSeats(event.getAvailableSeats() + 1); } } (Pro tip for interviews: be ready to explain how you would prevent duplicate execution across multiple app instances using **ShedLock).
4. Writing a True Multithreaded Test with CountDownLatch
Simply starting 20 threads in a for loop does not test concurrency properly—the first thread often finishes its DB transaction before thread #15 even starts.
Use ExecutorService + CountDownLatch as a starting gate so all 20 threads hit bookSeat() at the exact same instant:
@Test void shouldPreventOverbookingUnderHighConcurrency() throws InterruptedException { int threadCount = 20; int initialSeats = 5; Long eventId = createEventWithSeats(initialSeats); ExecutorService executor = Executors.newFixedThreadPool(threadCount); CountDownLatch readyLatch = new CountDownLatch(threadCount); CountDownLatch startLatch = new CountDownLatch(1); AtomicInteger successCount = new AtomicInteger(0); AtomicInteger failCount = new AtomicInteger(0); for (int i = 0; i < threadCount; i++) { final String email = "user" + i + "@example.com"; executor.submit(() -> { readyLatch.countDown(); try { startLatch.await(); bookingService.bookSeat(eventId, email); successCount.incrementAndGet(); } catch (NoSeatsAvailableException e) { failCount.incrementAndGet(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }); } readyLatch.await(); startLatch.countDown(); // Fire all 20 threads simultaneously executor.shutdown(); executor.awaitTermination(10, TimeUnit.SECONDS); assertEquals(5, successCount.get()); assertEquals(15, failCount.get()); assertEquals(0, eventRepository.findById(eventId).orElseThrow().getAvailableSeats()); } Want the Complete Reference Project + Code Review Cheatsheet?
If you want to save hours of boilerplate setup and prepare for the follow-up interview questions, I packaged the complete Spring Boot 3.5 + Java 21 + PostgreSQL 16 reference repository along with an 8-Question Team Lead Code Review Cheatsheet (covering deadlocks, isolation levels, ShedLock, and scaling to 10k RPS).
