JAVA-260 · Lesson 12 of 12 · 28 min

Capstone: a REST service for a small business

▶ Video coming soon A video version of this lesson is on the way.

In the second week of April 2028, Hamza took four days off the counter to finish the booking service. Odile had agreed the plan in January: the shop's booking website would go live later in the year, and before Tamsin built its pages, the API behind it had to be finished, tested, documented and running on Leif's server. Hamza built it from Monday, April 10 to Thursday, April 13, working in the back room during the day, and presented it on Wednesday, April 19, to Ingrid, Odile, Kofi and Leif. This lesson follows that week: the requirements, the design, the core logic you can run here, the Spring code and the review.

The requirements

Odile and Kofi wrote the requirements with Hamza in March, in the shop's words. Each has a number so that the tests, the pull requests and the review could refer to it. R6 to R8 came from the lessons on security and observability, and Leif insisted they be written down like the others.

The booking service requirements, March 2028.
No.RequirementWhere it is met
R1A visitor can see the free repair slots for a day: Tuesday to Saturday, starts every half hour from 09:00 to 15:00, one bike per startGET /api/v1/repair-slots
R2A visitor can book a free slot with name, phone, bike and problem, and gets a booking number and referencePOST /api/v1/repair-bookings, 201
R3Two people cannot book the same slot409 from the service, a unique index in the database
R4A visitor can see whether a part is in stock, low or out, with an expected date when outGET /api/v1/parts/{code}/availability
R5Staff at the counter can list a day's bookings and change a booking's statusGET and PATCH, role STAFF
R6Customers' bookings are visible only with their reference; no personal data in logsObject check, redaction
R7Bad requests get clear Problem Details answers; nothing internal leaks@RestControllerAdvice
R8Leif can see health, booking counts and errors without reading the codeActuator, Prometheus, structured logs

The design

The design followed the one Hamza was building for CounterApp on Tuesdays: a hexagon, with business rules in the middle and adapters around them. The booking service reused the same ports, BookRepair, PartCatalog, Notifier and Clock, so the counter app and the website would both drive one set of rules. The REST controllers are driving adapters; the JPA repositories over StockStore's PostgreSQL schema, the supplier clients and the SMS notifier are driven adapters. Spring wires them together, but the domain package has no Spring imports at all, and Leif's ArchUnit check in the build enforces that.

Package layout of the booking service.
PackageContainsDepends on
org.secondgear.booking.domainSlot, Booking, BookingStatus, SlotCalendar, Availability rulesNothing but the JDK
org.secondgear.booking.applicationBookingService, ports BookRepair, PartCatalog, Notifier, SupplierStockdomain
org.secondgear.booking.adapters.webControllers, request and view records, ApiErrors, SecurityConfigapplication
org.secondgear.booking.adapters.persistenceJPA entities and repositories, Flyway V5 and V6application
org.secondgear.booking.adapters.suppliersVelotek RestClient, Larchmont HTTP service client, circuit breakerapplication
org.secondgear.booking.adapters.smsSmsNotifier (prod), LogNotifier (others)application
A hexagon in the middle marked booking domain and application, containing BookingService and SlotCalendar. On the left, outside the hexagon, two driving adapters point in: REST controllers used by the booking website and the counter app. On the right, four driven adapters are pointed at from the hexagon: JPA repositories to a PostgreSQL cylinder holding StockStore and bookings, a Velotek client, a Larchmont client, and an SMS notifier. Around everything, a dashed border marked Spring Boot application, with Actuator and Spring Security shown as bands along its top edge.
The capstone booking service: ports in the middle, adapters around them, Spring Boot around the whole.

Free slots

R1 is a pure calculation, so it lives in the domain and has fast tests. Given a date, the open days, the first and last start, the slot length and the bookings already made, it returns the free starts. The shop's rules came from BookingProperties in lesson 6, and the example passes them in directly. It also refuses dates in the past using a fixed clock, so the output never changes.

Java Example · Main.java
import java.time.*;
import java.util.*;

public class Main {
    record Rules(Set<DayOfWeek> openDays, LocalTime firstStart, LocalTime lastStart, Duration step) {}

    static List<LocalTime> freeStarts(LocalDate day, Rules rules, Set<LocalDateTime> booked, Clock clock) {
        if (!rules.openDays().contains(day.getDayOfWeek())) return List.of();
        LocalDateTime now = LocalDateTime.now(clock);
        List<LocalTime> free = new ArrayList<>();
        for (LocalTime t = rules.firstStart(); !t.isAfter(rules.lastStart()); t = t.plus(rules.step())) {
            LocalDateTime start = day.atTime(t);
            if (start.isAfter(now) && !booked.contains(start)) free.add(t);
        }
        return free;
    }

    public static void main(String[] args) {
        Rules rules = new Rules(EnumSet.range(DayOfWeek.TUESDAY, DayOfWeek.SATURDAY),
                LocalTime.of(9, 0), LocalTime.of(15, 0), Duration.ofMinutes(30));
        Clock clock = Clock.fixed(Instant.parse("2028-04-12T14:00:00Z"), ZoneId.of("America/Toronto"));
        Set<LocalDateTime> booked = Set.of(
                LocalDateTime.of(2028, 5, 6, 9, 0), LocalDateTime.of(2028, 5, 6, 10, 30),
                LocalDateTime.of(2028, 5, 6, 11, 0), LocalDateTime.of(2028, 5, 6, 14, 30));

        LocalDate sat = LocalDate.of(2028, 5, 6);
        List<LocalTime> free = freeStarts(sat, rules, booked, clock);
        System.out.println(sat.getDayOfWeek() + " " + sat + ": " + free.size() + " free of 13");
        System.out.println("  " + free);
        System.out.println("MONDAY 2028-05-08: " + freeStarts(LocalDate.of(2028, 5, 8), rules, booked, clock));
        System.out.println("WEDNESDAY 2028-04-12 (today, now 10:00): " + freeStarts(LocalDate.of(2028, 4, 12), rules, Set.of(), clock));
    }
}
Output
SATURDAY 2028-05-06: 9 free of 13
  [09:30, 10:00, 11:30, 12:00, 12:30, 13:00, 13:30, 14:00, 15:00]
MONDAY 2028-05-08: []
WEDNESDAY 2028-04-12 (today, now 10:00): [10:30, 11:00, 11:30, 12:00, 12:30, 13:00, 13:30, 14:00, 14:30, 15:00]

What this code does

freeStarts walks from the first start to the last in steps of thirty minutes, which gives thirteen starts a day, and keeps the ones that are in the future and not already booked. A Monday returns an empty list because it is not an open day. The fixed clock puts now at 10:00 on Wednesday, April 12, so on that day the starts up to and including 10:00 are gone.

Part availability

R4 must say something useful without exposing the stock count, which Odile considered the shop's business. The rule uses StockStore's reorder_level: more than the reorder level is IN_STOCK, from one up to the reorder level is LOW, and zero is OUT, in which case the service asks the supplier for an expected date, with the timeout and circuit breaker from lesson 8. If the supplier cannot answer, the date is simply left out.

Java Example · Main.java
import java.time.LocalDate;
import java.util.*;

public class Main {
    enum Availability { IN_STOCK, LOW, OUT }
    record Part(String code, String name, int quantity, int reorderLevel) {}
    record View(String code, String name, Availability availability, LocalDate expected) {}

    static Availability classify(Part p) {
        if (p.quantity() <= 0) return Availability.OUT;
        return p.quantity() <= p.reorderLevel() ? Availability.LOW : Availability.IN_STOCK;
    }

    static View view(Part p, Map<String, LocalDate> supplierDates) {
        Availability a = classify(p);
        return new View(p.code(), p.name(), a, a == Availability.OUT ? supplierDates.get(p.code()) : null);
    }

    public static void main(String[] args) {
        Map<String, LocalDate> supplier = Map.of("CHAIN-11", LocalDate.of(2028, 4, 20));
        List<Part> parts = List.of(
                new Part("TUBE-700", "Inner tube 700x25", 40, 12),
                new Part("BELL", "Brass bell", 4, 4),
                new Part("CHAIN-11", "11-speed chain", 0, 5),
                new Part("BRAKE-PADS", "Disc brake pads", 0, 8));
        for (Part p : parts) {
            View v = view(p, supplier);
            System.out.println(v.code() + " " + v.availability() + (v.expected() == null ? "" : " expected " + v.expected()));
        }
    }
}
Output
TUBE-700 IN_STOCK
BELL LOW
CHAIN-11 OUT expected 2028-04-20
BRAKE-PADS OUT

What this code does

classify turns the private quantity into one of three public words, so the website never learns how many tubes are on the shelf. view asks for a supplier date only when the part is out. BRAKE-PADS has no date because the supplier had none, which is the same answer a timeout or an open circuit gives.

The whole API in one file

The final example puts the pieces together on the JDK's HttpServer, as a working model of the finished service: free slots, booking with 201 and a Location header, 409 for a taken slot, 422 for a closed day, part availability, and Problem Details for every error. It runs a scripted session against itself, much like the end-to-end test in the build, and prints each request with its status and body.

Java Example · Main.java
import com.sun.net.httpserver.*;
import java.net.*;
import java.net.http.*;
import java.nio.charset.StandardCharsets;
import java.time.*;
import java.util.*;
import java.util.regex.*;

public class Main {
    static final Set<DayOfWeek> OPEN = EnumSet.range(DayOfWeek.TUESDAY, DayOfWeek.SATURDAY);
    static final Map<LocalDateTime, Long> bookings = new TreeMap<>();
    static long nextId = 2041;
    static final Map<String, int[]> stock = Map.of("BELL", new int[] {14, 4}, "CHAIN-11", new int[] {0, 5});

    record Reply(int status, String body, String location) {}

    static Reply problem(int status, String title, String detail) {
        return new Reply(status, "{\"title\":\"" + title + "\",\"status\":" + status + ",\"detail\":\"" + detail + "\"}", null);
    }

    static synchronized Reply handle(String method, String path, String query, String body) {
        if (method.equals("GET") && path.equals("/api/v1/repair-slots")) {
            LocalDate day = LocalDate.parse(query.substring("date=".length()));
            List<String> free = new ArrayList<>();
            if (OPEN.contains(day.getDayOfWeek()))
                for (LocalTime t = LocalTime.of(9, 0); !t.isAfter(LocalTime.of(15, 0)); t = t.plusMinutes(30))
                    if (!bookings.containsKey(day.atTime(t))) free.add("\"" + t + "\"");
            return new Reply(200, "{\"date\":\"" + day + "\",\"free\":" + free.size() + ",\"first\":" + (free.isEmpty() ? "null" : free.get(0)) + "}", null);
        }
        if (method.equals("POST") && path.equals("/api/v1/repair-bookings")) {
            Matcher m = Pattern.compile("\"start\":\"([^\"]+)\"").matcher(body);
            if (!m.find() || !body.contains("\"customer\":\"") || body.contains("\"customer\":\"\""))
                return problem(400, "Invalid booking request", "customer and start are required");
            LocalDateTime start = LocalDateTime.parse(m.group(1));
            if (!OPEN.contains(start.getDayOfWeek())) return problem(422, "The shop is closed then", "No repairs on " + start.getDayOfWeek());
            if (bookings.containsKey(start)) return problem(409, "Slot no longer available", "The " + start + " slot was just booked");
            long id = nextId++;
            bookings.put(start, id);
            return new Reply(201, "{\"id\":" + id + ",\"start\":\"" + start + "\",\"status\":\"BOOKED\"}", "/api/v1/repair-bookings/" + id);
        }
        Matcher part = Pattern.compile("/api/v1/parts/([A-Z0-9-]+)/availability").matcher(path);
        if (method.equals("GET") && part.matches()) {
            int[] q = stock.get(part.group(1));
            if (q == null) return problem(404, "Not Found", "No part " + part.group(1));
            String a = q[0] <= 0 ? "OUT" : q[0] <= q[1] ? "LOW" : "IN_STOCK";
            return new Reply(200, "{\"code\":\"" + part.group(1) + "\",\"availability\":\"" + a + "\"}", null);
        }
        return problem(404, "Not Found", "No route for " + method + " " + path);
    }

    public static void main(String[] args) throws Exception {
        HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
        server.createContext("/", ex -> {
            String in = new String(ex.getRequestBody().readAllBytes(), StandardCharsets.UTF_8);
            URI u = ex.getRequestURI();
            Reply r = handle(ex.getRequestMethod(), u.getPath(), u.getQuery() == null ? "" : u.getQuery(), in);
            byte[] out = r.body().getBytes(StandardCharsets.UTF_8);
            ex.getResponseHeaders().add("Content-Type", r.status() >= 400 ? "application/problem+json" : "application/json");
            if (r.location() != null) ex.getResponseHeaders().add("Location", r.location());
            ex.sendResponseHeaders(r.status(), out.length);
            try (var os = ex.getResponseBody()) { os.write(out); }
        });
        server.start();
        try {
            HttpClient client = HttpClient.newHttpClient();
            String base = "http://127.0.0.1:" + server.getAddress().getPort();
            String ana = "{\"customer\":\"Ana Ferreira\",\"start\":\"2028-05-06T10:30\"}";
            String dev = "{\"customer\":\"Dev Okafor\",\"start\":\"2028-05-06T10:30\"}";
            String[][] script = {
                {"GET", "/api/v1/repair-slots?date=2028-05-06", ""},
                {"POST", "/api/v1/repair-bookings", ana},
                {"POST", "/api/v1/repair-bookings", dev},
                {"POST", "/api/v1/repair-bookings", "{\"customer\":\"Dev Okafor\",\"start\":\"2028-05-08T10:30\"}"},
                {"POST", "/api/v1/repair-bookings", "{\"customer\":\"\",\"start\":\"2028-05-06T11:00\"}"},
                {"GET", "/api/v1/repair-slots?date=2028-05-06", ""},
                {"GET", "/api/v1/parts/BELL/availability", ""},
                {"GET", "/api/v1/parts/CHAIN-11/availability", ""},
                {"GET", "/api/v1/parts/HORN/availability", ""}};
            for (String[] s : script) {
                HttpRequest.Builder b = HttpRequest.newBuilder(URI.create(base + s[1]));
                if (s[0].equals("POST")) b.header("Content-Type", "application/json").POST(HttpRequest.BodyPublishers.ofString(s[2]));
                HttpResponse<String> res = client.send(b.build(), HttpResponse.BodyHandlers.ofString());
                System.out.println(s[0] + " " + s[1] + " -> " + res.statusCode()
                        + res.headers().firstValue("Location").map(l -> " Location: " + l).orElse(""));
                System.out.println("    " + res.body());
            }
        } finally {
            server.stop(0);
        }
    }
}
Output
GET /api/v1/repair-slots?date=2028-05-06 -> 200
    {"date":"2028-05-06","free":13,"first":"09:00"}
POST /api/v1/repair-bookings -> 201 Location: /api/v1/repair-bookings/2041
    {"id":2041,"start":"2028-05-06T10:30","status":"BOOKED"}
POST /api/v1/repair-bookings -> 409
    {"title":"Slot no longer available","status":409,"detail":"The 2028-05-06T10:30 slot was just booked"}
POST /api/v1/repair-bookings -> 422
    {"title":"The shop is closed then","status":422,"detail":"No repairs on MONDAY"}
POST /api/v1/repair-bookings -> 400
    {"title":"Invalid booking request","status":400,"detail":"customer and start are required"}
GET /api/v1/repair-slots?date=2028-05-06 -> 200
    {"date":"2028-05-06","free":12,"first":"09:00"}
GET /api/v1/parts/BELL/availability -> 200
    {"code":"BELL","availability":"IN_STOCK"}
GET /api/v1/parts/CHAIN-11/availability -> 200
    {"code":"CHAIN-11","availability":"OUT"}
GET /api/v1/parts/HORN/availability -> 404
    {"title":"Not Found","status":404,"detail":"No part HORN"}

What this code does

handle is the whole API as one synchronized method, so two requests can never both take the same slot, which is the in-memory version of R3. The script books 10:30 for Ana, then shows Dev getting 409 for the same slot, 422 for a Monday and 400 for a blank name, and the second slots request has one fewer free start. Every error is a small problem document with the application/problem+json type, and the part checks show IN_STOCK, OUT and a 404.

The Spring service

The real service is the same API, built from the lessons' pieces. The controller is thin and delegates to the application service; the service enforces the rules and calls the ports; the database enforces R3 a second time with a unique index, because two requests on two threads could both check the slot before either saved. The unique index turns the second insert into an exception, which the service maps to SlotTaken and the advice class to 409.

Java Example · RepairController.java (needs Spring Boot)
@RestController
@RequestMapping("/api/v1")
@Tag(name = "Repairs")
class RepairController {
    private final BookRepair bookRepair;
    private final SlotQuery slots;

    RepairController(BookRepair bookRepair, SlotQuery slots) {
        this.bookRepair = bookRepair;
        this.slots = slots;
    }

    @GetMapping("/repair-slots")
    SlotsView free(@RequestParam LocalDate date) {
        return SlotsView.of(date, slots.freeStarts(date));
    }

    @PostMapping("/repair-bookings")
    ResponseEntity<BookingConfirmation> book(@Valid @RequestBody NewBooking request, UriComponentsBuilder uris) {
        BookingConfirmation c = bookRepair.book(request.toCommand());
        return ResponseEntity.created(uris.path("/api/v1/repair-bookings/{id}").build(c.id())).body(c);
    }

    @GetMapping("/repair-bookings/{id}")
    BookingView one(@PathVariable long id, @RequestParam(required = false) String reference, Authentication caller) {
        return bookRepair.find(id, reference, caller);
    }
}

What this code does

The controller only converts between HTTP and the BookRepair and SlotQuery ports, which are the same ports the counter app drives. The booking request is validated by @Valid before the port is called, and a successful booking answers 201 with a Location header. The object-level check for R6 happens inside find, where the booking is loaded.

Java Example · BookingService.java (needs Spring Boot)
@Service
@Transactional
class BookingService implements BookRepair, SlotQuery {
    private final BookingRepository bookings;
    private final SlotCalendar calendar;
    private final Notifier notifier;
    private final ReferenceGenerator references;
    private final Clock clock;
    private final Counter created, taken;

    // constructor omitted: all dependencies injected, counters registered

    @Override
    public BookingConfirmation book(BookCommand cmd) {
        if (!calendar.isBookable(cmd.start(), LocalDateTime.now(clock))) throw new ShopClosed(cmd.start());
        try {
            Booking b = bookings.saveAndFlush(Booking.create(cmd, references.next()));
            created.increment();
            notifier.send(cmd.phone(), "Second Gear: repair booked for " + cmd.start() + ", ref " + b.reference());
            return BookingConfirmation.of(b);
        } catch (DataIntegrityViolationException e) {
            taken.increment();
            throw new SlotTaken(cmd.start());
        }
    }

    @Override
    @Transactional(readOnly = true)
    public List<LocalTime> freeStarts(LocalDate day) {
        return calendar.freeStarts(day, bookings.startsOn(day), LocalDateTime.now(clock));
    }
}

What this code does

The service checks the shop's rules with the domain's SlotCalendar, then saves and flushes so that the unique index is checked inside the try block. A duplicate start becomes SlotTaken and 409, and each outcome increments its counter for R8. The notifier is a port, so tests record the message, development logs it and production sends a text.

-- V6__one_booking_per_start.sql
CREATE UNIQUE INDEX repair_bookings_one_per_start
    ON repair_bookings (start_at)
    WHERE status <> 'CANCELLED';

ALTER TABLE repair_bookings ADD COLUMN reference VARCHAR(9) NOT NULL DEFAULT '';
CREATE UNIQUE INDEX repair_bookings_reference ON repair_bookings (reference) WHERE reference <> '';

What this code does

The partial unique index allows only one active booking per start time while ignoring cancelled ones, so a cancelled slot can be booked again. The reference column holds the random booking reference used for R6, generated with SecureRandom in the ReferenceGenerator bean. Flyway applies V6 at the next start-up, after V5 from lesson 5.

Running it

On Wednesday evening, Leif deployed the JAR to the shop's server with the prod profile, the secrets in the service's environment file and Actuator on the management port. On Thursday morning, Hamza ran a short session with curl against it, the same script as the model above, before showing anyone.

Representative session
curl -s 'https://api.secondgear.org/api/v1/repair-slots?date=2028-05-06'
curl -si -X POST https://api.secondgear.org/api/v1/repair-bookings \
  -H 'Content-Type: application/json' \
  -d '{"customer":"Ana Ferreira","phone":"555-555-0142","start":"2028-05-06T10:30","bike":"Trek FX 2","problem":"Rear brake rubs"}'
curl -s https://api.secondgear.org/api/v1/parts/CHAIN-11/availability
Output
{"date":"2028-05-06","free":["09:00","09:30","10:00","10:30","11:00","11:30","12:00","12:30","13:00","13:30","14:00","14:30","15:00"]}

HTTP/2 201
location: https://api.secondgear.org/api/v1/repair-bookings/2041
content-type: application/json

{"id":2041,"reference":"K7QF-29XM","start":"2028-05-06T10:30:00","status":"BOOKED"}

{"code":"CHAIN-11","name":"11-speed chain","availability":"OUT","expected":"2028-04-20"}

What this code does

The first request lists the free starts, the second books one and the third checks a part that is out of stock. Only the headers that matter are shown.

The review

On Wednesday, April 19, the review took ninety minutes in the back room. Hamza walked through the requirements one by one, each with the test that proved it. The suite had 131 unit tests, 28 slice tests and 6 full tests against PostgreSQL in Testcontainers, and it ran in under a minute on Leif's build server. Kofi tried to break it from the counter computer: a booking with a 600-character problem description (400), a booking for Canada Day, Saturday, July 1, which the service accepted with 201 although the shop would be closed, the same slot from two browser windows at once (one 201, one 409), and booking 2042 with Ana's reference (404). Odile asked to see the Grafana chart, and watched the bookings counter tick up as Kofi made test bookings.

Leif's points were all about running it. He wanted the readiness probe tested by stopping PostgreSQL on purpose, which they did: readiness went DOWN within ten seconds, liveness stayed UP, and the service recovered by itself when the database came back. He also asked for a short runbook, a page that says what to check when an alert fires, and for the OpenAPI document to be published to Tamsin's project on every release. Ingrid's comment was about the design: the same BookRepair port now had two drivers, the counter app's screen and the REST controller, and neither knew the other existed.

Findings from the review on April 19, 2028.
FindingRaised byDecision
Public holidays are not in SlotCalendarKofiAdd a closed-dates list to BookingProperties before the website launches
A visitor can book many slots with different namesLeifLimit active bookings per phone number to two (OWASP API6)
Cancelling by the customer is not supported yetOdileAdd DELETE with the reference in the next version; staff can cancel now
Runbook for the two alertsLeifHamza writes it before go-live
OpenAPI document published to the website projectTamsin, by messageA step in the release workflow

Odile closed the review by setting the date: the website would be built over the summer and would go live in the autumn, once Tamsin's pages and the holiday list were done. Until then, the counter app would use the new API for bookings taken by phone, which gave the service months of real use before the public arrived.

Try it yourself

Cancel a booking

Complete cancel so that it removes the booking with the given ID, freeing its slot, and returns 204; an unknown ID returns 404.

After the cancellation, the program books the freed slot again and must print the statuses shown by the comments.

import java.time.*;
import java.util.*;

public class Main {
    static final Map<LocalDateTime, Long> bookings = new TreeMap<>();
    static long nextId = 2041;

    static int book(LocalDateTime start) {
        if (bookings.containsKey(start)) return 409;
        bookings.put(start, nextId++);
        return 201;
    }

    static int cancel(long id) {
        return 404;
    }

    public static void main(String[] args) {
        LocalDateTime sat = LocalDateTime.of(2028, 5, 6, 10, 30);
        System.out.println("book    " + book(sat));      // 201
        System.out.println("again   " + book(sat));      // 409
        System.out.println("cancel  " + cancel(2041));   // 204
        System.out.println("cancel  " + cancel(2041));   // 404
        System.out.println("rebook  " + book(sat));      // 201
        System.out.println(bookings);
    }
}

Try it yourself

Limit bookings per phone

Following the review, each phone number may hold at most two active bookings. Complete book so that a third booking for the same phone returns 429 too many bookings for this phone and is not stored.

Bookings that succeed return 201 #id, starting at 2041; a taken slot still returns 409 slot taken.

import java.time.*;
import java.util.*;

public class Main {
    record Booking(long id, String phone, LocalDateTime start) {}
    static final List<Booking> bookings = new ArrayList<>();

    static String book(String phone, LocalDateTime start) {
        if (bookings.stream().anyMatch(b -> b.start().equals(start))) return "409 slot taken";
        Booking b = new Booking(2041 + bookings.size(), phone, start);
        bookings.add(b);
        return "201 #" + b.id();
    }

    public static void main(String[] args) {
        LocalDate sat = LocalDate.of(2028, 5, 6);
        System.out.println(book("555-555-0142", sat.atTime(9, 0)));
        System.out.println(book("555-555-0142", sat.atTime(9, 30)));
        System.out.println(book("555-555-0142", sat.atTime(10, 0)));
        System.out.println(book("555-555-0199", sat.atTime(9, 30)));
        System.out.println(book("555-555-0199", sat.atTime(10, 0)));
    }
}

Looking back

In January, the booking service had been four questions on a whiteboard. Each lesson had added one layer: the container and its beans, controllers, validation and Problem Details, persistence over StockStore, configuration and secrets, security, calls to suppliers, tests at three sizes, an OpenAPI contract, and the signals that let Leif run it. None of the layers was magic once Hamza had built a small version of it by hand, which was Ingrid's reason for all the JDK examples. In May, the counter app started sending its phone bookings through the API, and the booking website followed later in 2028.

Common mistakes

  • MistakeRelying on a check in code alone to stop double bookings.

    InsteadBack the rule with a unique index, because two requests can pass the check at the same moment.

  • MistakeShowing exact stock counts on a public endpoint.

    InsteadPublish a small classification such as IN_STOCK, LOW and OUT.

  • MistakeGoing live without testing the failure paths.

    InsteadStop the database on purpose and watch the probes, alerts and recovery.

  • MistakeTreating the review as a demonstration.

    InsteadWalk through each requirement with the test that proves it, and record the findings with decisions.

  • MistakeLetting the website and the counter app each implement booking rules.

    InsteadKeep one set of rules behind the ports and let both drive it.

Summary and key terms

  • The capstone booking service meets eight numbered requirements: free slots (R1), booking with 201 and a reference (R2), no double bookings (R3), public part availability (R4), staff functions (R5), object-level privacy and clean logs (R6), Problem Details errors (R7) and observability (R8).
  • It keeps the hexagonal design of CounterApp, with REST controllers as driving adapters and JPA over StockStore's PostgreSQL schema, supplier clients and an SMS notifier as driven adapters.
  • Slot calculation and availability are pure domain logic with fast tests.
  • R3 is enforced twice, in the service and with a partial unique index.
  • Deployment uses the prod profile, environment secrets and a management port.
  • The review checked each requirement against its tests, tried the failure paths and recorded findings: holidays, a per-phone limit, customer cancellation, a runbook and publishing the OpenAPI document.
Requirement
A numbered statement of what the system must do, traceable to tests.
Driving adapter
An adapter that calls into the application, such as a REST controller.
Driven adapter
An adapter the application calls out to, such as a repository or notifier.
Partial unique index
A unique index that applies only to rows matching a condition.
Booking reference
A random code given to the customer and required to read their booking.
Availability classification
Reporting stock as IN_STOCK, LOW or OUT instead of a count.
Runbook
A short page that says what to check and do when an alert fires.
Go-live
The moment a service starts handling real users.
Failure-path test
A test that breaks a dependency on purpose to check the service's reaction.
Review finding
A problem or gap raised in a review, recorded with a decision.

Practice problems

Work each problem on paper first, then reveal the answer to check.

  1. Why does R3 need a unique index as well as a check in the service?

    Show answer

    Two requests can both pass the check before either saves; the index stops the second insert.

  2. How does the public availability endpoint avoid revealing stock counts?

    Show answer

    It returns IN_STOCK, LOW or OUT based on the reorder level.

  3. Which ports does the booking service share with the counter app?

    Show answer

    BookRepair, PartCatalog, Notifier and Clock.

  4. What happened to the probes when Leif stopped PostgreSQL?

    Show answer

    Readiness went DOWN, liveness stayed UP, and the service recovered when the database returned.

  5. Which OWASP API risk did the per-phone booking limit address?

    Show answer

    API6, unrestricted access to sensitive business flows.

Lesson quiz · 5 questions

Score 60% or more to complete this lesson.

Take the quiz