SteelReed

Search

Search posts, questions…

5. Spring Boot

The hotel booking example: APIs, preventing overbooking and the Spring Boot plan

The API list, preventing overbooking with a conditional update, idempotency keys, package layout, controller, service, the search query, milestones and a testing strategy with Testcontainers.

17 Nov 20267 min readMid

–

1. The problem

The first create reads available rooms and, if there are enough, decrements and saves a booking. The single-threaded test is green. 20 threads booking the last room: 3 bookings succeed. The mobile app resends on a flaky network: a fourth booking.

2. Key idea

Like a ticket counter: only tear the ticket if the seat is free at the moment of tearing, not when the customer asked "any seats left?". Reading and then writing (check-then-act) leaves a gap for another request to slip in.

Merge "check" and "decrement" into one conditional UPDATE across every night. An InnoDB UPDATE reads the latest version and holds the write lock until commit, so the second request waits, then updates nothing. It succeeds if and only if the affected row count equals the number of nights; otherwise throw a RuntimeException to roll back the nights already decremented.

Preventing overbooking Use when Don't use when
Conditional update the default: one SQL statement, no prior read the condition is too complex to express in SQL
SELECT ... FOR UPDATE multi-step checks in Java locking many rows in inconsistent order: deadlocks
Optimistic locking (version) low contention hot rooms, holidays: endless retries
Holds in Redis with a TTL very high load (flash sales) a pet project: another system, two sources of truth

2.1 API and code structure

  • Search is GET /api/v1/hotels?city=&sleeps=&checkin=&checkout=: read-only, cacheable, shareable. Errors use Problem Details (RFC 9457).
  • Booking is POST /api/v1/bookings with an Idempotency-Key header: 201 + Location, sold out 409, invalid coupon 422.
  • Package by feature (hotel, inventory, booking), with api → application → infra inside: no backwards or skipping calls; entities don't leave the service. Enforce it with ArchUnit.
  • Nights are the half-open range [checkin, checkout), consistent across inventory, night count and price. "Today" is in the hotel's time zone: inject a Clock, don't use @FutureOrPresent on a JVM running UTC.

3. In Java

JAVA
public interface RoomInventoryRepository extends JpaRepository<RoomInventory, RoomInventoryId> {
    @Modifying
    @Query(value = """
        UPDATE room_inventory SET booked_rooms = booked_rooms + :qty
        WHERE room_type_id = :roomTypeId AND stay_date >= :checkin AND stay_date < :checkout
          AND total_rooms - booked_rooms >= :qty""", nativeQuery = true)
    int reserve(long roomTypeId, LocalDate checkin, LocalDate checkout, int qty);
}
 
@Transactional
public BookingResponse create(long userId, String idemKey, CreateBookingRequest req) {
    int nights = (int) ChronoUnit.DAYS.between(req.checkin(), req.checkout());
    int updated = inventory.reserve(req.roomTypeId(), req.checkin(), req.checkout(), req.quantity());
    if (updated != nights) throw new RoomUnavailableException(req.roomTypeId());  // rolls back every night
    PriceBreakdown price = pricing.calculate(inventory.pricesFor(req), req.quantity());
    Booking booking = Booking.pending(userId, req, nights, price, idemKey,
            Instant.now(clock).plus(Duration.ofMinutes(15)));
    return BookingResponse.from(bookings.saveAndFlush(booking));  // UNIQUE (user_id, idempotency_key)
}

Two requests with the same key arriving together both miss the old booking via findBy...; the second violates UNIQUE, so catch DataIntegrityViolationException and return the existing booking. Money is BigDecimal, compared with compareTo (2.0 doesn't equals 2.00).

Testing strategy
  • Unit: PricingService (nightly prices, fees, coupons, rounding), booking status rules.
  • Integration on real MySQL (Testcontainers): H2 doesn't match MySQL's locking or CHECK. The key test: 1 room left, 20 threads booking at once via a CountDownLatch, expecting exactly 1 success, 19 RoomUnavailableExceptions, and booked_rooms = total_rooms.
  • Idempotency: two parallel requests with the same key, expecting one booking.
  • API: MockMvc checks 201 + Location, 409 as application/problem+json, 400 when checkout <= checkin.
  • Architecture: ArchUnit tests that controllers don't call repositories and domain doesn't depend on api.
  • Milestones M0 (skeleton, CI) to M6 (load test p95 < 300 ms at 50 req/s): each has a measurable definition of done.

4. Working with AI

Delegate to AI: controllers, DTOs with Bean Validation, mappers, MockMvc tests, Testcontainers setup.

Check yourself:

  • No check-then-act on inventory; the changed row count is compared with the night count.
  • There's UNIQUE (user_id, idempotency_key) and DataIntegrityViolationException is handled.
  • Business exceptions are unchecked; create is called through the proxy.
  • Concurrency tests run on real MySQL, not H2.
  • "Today" comes from a Clock in the hotel's time zone.

5. Exercises

Exercise 1: Review a create that "prevents overbooking"

AI wrote if (inventoryRepo.available(roomTypeId, checkin, checkout) >= qty) { inventoryRepo.decrement(...); bookings.save(...); } inside @Transactional, with a green single-threaded test. Find the bug, name a test that proves it, fix it.

Solution to Exercise 1
  • Check-then-act: two requests both read "1 left" and both decrement. @Transactional at the default isolation doesn't stop it (plain reads are snapshots).
  • Test: Testcontainers MySQL, 1 room left, 20 threads via a CountDownLatch; count bookings: more than 1.
  • Fix: one UPDATE ... WHERE total_rooms - booked_rooms >= :qty across every night, compare rows with nights, throw a RuntimeException if short. Keep CHECK (booked_rooms BETWEEN 0 AND total_rooms) as the final net.

Exercise 2: Extend the requirements: cancellations

Product wants "free cancellation up to 24 hours before check-in". Write the BDD and list what has to change.

Solution to Exercise 2
GHERKIN
Scenario: Free cancellation
  Given a CONFIRMED booking with check-in in 3 days
  When the owner calls POST /api/v1/bookings/1001/cancel
  Then the status is CANCELLED and each night's rooms are returned
Scenario: Too late
  Given check-in in 10 hours
  When they cancel
  Then 422 "cancellation window closed"
Scenario: Cancelling twice
  Given the booking is already CANCELLED
  When they cancel again
  Then 200 with the same status, and rooms aren't returned again

What changes: a CONFIRMED/PENDING → CANCELLED transition; the room-return update is conditional on WHERE status IN ('PENDING','CONFIRMED') so it happens once; "24 hours before check-in" is in the hotel's time zone, so hotels need a time_zone column. A small requirement forces a schema change: catch that at the spec stage.

Summary

  • Check-then-act causes overbooking; one conditional UPDATE doesn't.
  • Compare changed rows with nights; a RuntimeException rolls back the decremented nights.
  • The idempotency guard is UNIQUE, not findBy.
  • Package by feature, three layers, enforced with ArchUnit.
  • Test on real MySQL: 20 threads for 1 room, exactly 1 wins.

Next: Part 3: Interview review.

Practice interview questions on this topic

All Web & REST API questions →All JPA & Hibernate questions →

Loading comments…