Skip to content
Visual explainer 15h to learn 6 steps

Build a secure REST backend (e.g. booking or expense API)

Auth, JPA, tests, Redis cache, Docker and a CI pipeline in one repo.

By Invicly Tech, , in Backend Java Development. About 12 minutes to read.

Topic 29 of 29

In short

The capstone combines everything into one deployable backend, such as a booking or expense API. A finished repo with auth, tests, caching, Docker and CI is strong evidence in interviews.

Explained simply

The capstone is one real backend that uses everything from this path. A good choice is a room booking API: people sign up, see which rooms are free, and book them; admins add rooms. It is small enough to finish, but it has real problems to solve, like two people trying to book the same room at the same time.

Plan before you code. Write down the things in your app (users, rooms, bookings), the rules (no double bookings, only admins create rooms), and the URLs your API offers. An hour of planning saves days of rework.

Then build in thin slices. First a database table, an entity and one endpoint, with a test. Then security. Then caching. Then Docker and CI. After each slice the app should run and the tests should pass. A small app that works beats a big one that half works.

The finished repo is your proof of skill. A reviewer should be able to clone it, run one command, and see it work. A clear README, passing CI and clean commits tell them you can be trusted with a real codebase.

Press Play on a diagram to walk through it one step at a time.

LayersCapstone architecture
  1. 1
    Security filter chain

    JWT authentication and role checks

  2. 2
    REST controllers

    DTOs, validation, error handling, OpenAPI

  3. 3
    Services

    Business rules inside @Transactional methods

  4. 4
    Redis cache

    Hot reads like listing available rooms

  5. 5
    JPA repositories

    Entities, relations, fetch joins

  6. 6
    PostgreSQL

    Schema versioned by Flyway migrations

FlowSuggested build order
  1. 1
    Design domain

    Entities, endpoints and rules on paper

  2. 2
    Entities and migrations

    JPA mappings plus Flyway V1 schema

  3. 3
    CRUD endpoints and tests

    Unit tests and Testcontainers integration tests

  4. 4
    Add security

    Login, JWT, roles on endpoints

  5. 5
    Add caching

    Redis for the most read endpoint

  6. 6
    Docker and CI

    Compose file and a pipeline running tests

MapA reviewer-friendly repo layout
booking-api
  • src/main/java
    • room, booking, user packages
    • security config
    • error handling advice
  • src/main/resources
    • application.yml
    • db/migration/V1__init.sql
  • src/test/java
    • unit tests
    • WebMvcTest slices
    • Testcontainers ITs
  • Root files
    • Dockerfile
    • compose.yaml
    • .env.example
    • README.md
  • .github/workflows
    • ci.yml
CompareWhere to enforce "no double booking"
Java check then insert
  • Easy to write
  • Race: two requests both pass
  • Breaks under load
  • Needs locking to be safe
Database constraint
  • Exclusion constraint on date ranges
  • Correct under any concurrency
  • Second insert fails, return 409
  • Rule lives next to the data

In depth

Design the domain and the REST endpoints

Start with nouns and rules. For a booking API the entities are User, Room and Booking. A Booking belongs to one user and one room and has a check-in date, a check-out date and a status (CONFIRMED or CANCELLED). The core rule: two confirmed bookings for the same room must not overlap.

Map resources to URLs and HTTP methods. GET /rooms?from=2026-12-01&to=2026-12-03 lists free rooms. POST /bookings creates one and returns 201 Created with a Location header. DELETE /bookings/{id} cancels (or POST /bookings/{id}/cancel if you prefer keeping history). POST /rooms is admin only.

Decide error responses up front: 400 for invalid input, 401 when not logged in, 403 when logged in but not allowed, 404 for unknown ids, 409 Conflict when a room is already taken. Spring's ProblemDetail gives these a standard JSON shape (RFC 9457).

  • Use DTOs for requests and responses, never entities
  • Validate input with @Valid and Bean Validation annotations
  • Paginate lists with Pageable from the start
MapBooking API resources
/api
  • /auth
    • POST /register
    • POST /login returns a JWT
  • /rooms
    • GET with date range (public)
    • POST (ADMIN only)
    • GET /{id}
  • /bookings
    • POST creates, 409 if taken
    • GET mine (USER)
    • DELETE /{id} cancels
  • /actuator
    • health, info, prometheus

Entities, Flyway and stopping double bookings

Let Flyway own the schema. Put SQL files in src/main/resources/db/migration named V1__init.sql, V2__add_room_capacity.sql and so on; Flyway runs new ones at startup in order and records them in its flyway_schema_history table. Set spring.jpa.hibernate.ddl-auto=validate so Hibernate checks that entities match the tables but never changes them.

Checking for overlap in Java ("is there a booking? if not, insert") has a race: two requests can both see no booking and both insert. Let the database enforce the rule instead. PostgreSQL can do it with an exclusion constraint over a date range, which needs the btree_gist extension. When the second insert fails, catch DataIntegrityViolationException and return 409.

Map relations as @ManyToOne(fetch = LAZY) on Booking, and use a fetch join or an entity graph when a list needs the room names, to avoid the N+1 query problem.

  • CREATE EXTENSION IF NOT EXISTS btree_gist;
  • EXCLUDE USING gist (room_id WITH =, daterange(check_in, check_out) WITH &&)
  • Never edit a migration that has already run; add a new one

JWT and roles with Spring Security

Spring Security's OAuth2 resource server support validates JWTs for you. For a self-contained capstone, sign tokens yourself with an HMAC key (at least 256 bits, loaded from an environment variable) and give a JwtDecoder bean built with NimbusJwtDecoder.withSecretKey. The login endpoint checks the BCrypt password hash and issues a short-lived token (for example 15 minutes) with the user id as subject and a roles claim.

By default the resource server maps the scope claim to SCOPE_ authorities. To use roles, configure a JwtGrantedAuthoritiesConverter that reads the roles claim with the ROLE_ prefix. Then protect URLs in the SecurityFilterChain and individual methods with @PreAuthorize("hasRole('ADMIN')") after adding @EnableMethodSecurity.

Also check ownership, not just roles: a USER may cancel only their own booking. Compare the booking's user id with the token subject in the service, and return 404 or 403 when they differ.

SequenceLogin, then book a room
Client
Auth endpoint
Security filter
Booking service
  1. 1POST /auth/login email + password
    Client to Auth endpoint: POST /auth/login email + password
  2. 2JWT: sub=7, roles=[USER], exp 15 min
    Auth endpoint to Client: JWT: sub=7, roles=[USER], exp 15 min
  3. 3POST /bookings, Bearer token
    Client to Security filter: POST /bookings, Bearer token
  4. 4Signature and expiry OK: user 7, ROLE_USER
    Security filter to Booking service: Signature and expiry OK: user 7, ROLE_USER
  5. 5201 Created or 409 room taken
    Booking service to Client: 201 Created or 409 room taken

Caching, tests, Docker and CI

Cache one hot read and measure it. The free-rooms search is a good candidate, but it changes on every booking, so either evict on each booking or use a short TTL such as 30 seconds and accept that the list can be slightly stale (the exclusion constraint still prevents real double bookings). Record response times before and after in the README.

Test in layers. Unit tests cover service rules with Mockito. @WebMvcTest checks controllers, validation and security (use the jwt() request post-processor from spring-security-test). Integration tests use @SpringBootTest with Testcontainers for Postgres and Redis; with @ServiceConnection, Spring Boot wires the container URLs automatically. Include one test where two bookings overlap and expect 409.

Finally, a multi-stage Dockerfile, a compose.yaml with app, Postgres and Redis, and a CI workflow that runs ./mvnw verify and builds the image on every push and pull request.

Learn it in 6 short steps

About 2h 30m each. Track them with a timer in your plan.

  1. 1
    Design the domain and REST endpoints~2h 30m
  2. 2
    Implement JPA entities and Flyway migrations~2h 30m
  3. 3
    Secure the API with JWT and roles~2h 30m
  4. 4
    Add Redis caching for hot reads~2h 30m
  5. 5
    Write unit and Testcontainers tests~2h 30m
  6. 6
    Dockerise it and add a CI pipeline~2h 30m

Key points

  • Keep scope small but finished: a few resources done well beat many half-built ones.
  • Write a README with setup steps, an architecture diagram and example requests.
  • CI should build, run all tests and build the Docker image on every push.
  • Be ready to explain each design choice and what you would change at scale.

Key terms

Tap a card to flip it. 0/4 known

Examples

yaml
# .github/workflows/ci.yml
name: ci
on: [push, pull_request]
jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-java@v4
        with:
          distribution: temurin
          java-version: 21
          cache: maven
      - run: ./mvnw -B verify
      - run: docker build -t booking-api .

Testcontainers runs on GitHub-hosted Ubuntu runners because Docker is available.

Migration with an overlap constraint

V1 creates the three tables. The exclusion constraint says: for confirmed bookings, no two rows may have the same room_id and overlapping date ranges. daterange uses a half-open range by default, so a booking that checks out on the 3rd does not clash with one checking in on the 3rd. In the service, catch DataIntegrityViolationException on save and turn it into a 409 response.

sql
CREATE EXTENSION IF NOT EXISTS btree_gist;
CREATE TABLE app_user (id bigserial PRIMARY KEY, email text UNIQUE NOT NULL,
  password_hash text NOT NULL, role text NOT NULL DEFAULT 'USER');
CREATE TABLE room (id bigserial PRIMARY KEY, name text NOT NULL, capacity int NOT NULL);
CREATE TABLE booking (
  id bigserial PRIMARY KEY,
  room_id bigint NOT NULL REFERENCES room(id),
  user_id bigint NOT NULL REFERENCES app_user(id),
  check_in date NOT NULL, check_out date NOT NULL CHECK (check_out > check_in),
  status text NOT NULL DEFAULT 'CONFIRMED',
  EXCLUDE USING gist (room_id WITH =, daterange(check_in, check_out) WITH &&)
    WHERE (status = 'CONFIRMED')
);

An integration test that proves the 409

The test starts a real Postgres in Docker through Testcontainers, and @ServiceConnection points the datasource at it. It books room 1 for two nights, then tries an overlapping booking and expects 409 Conflict. Because Flyway runs on startup, the test also proves the migrations work.

java
@SpringBootTest(webEnvironment = RANDOM_PORT)
@Testcontainers
class BookingConflictIT {
  @Container @ServiceConnection
  static PostgreSQLContainer<?> pg = new PostgreSQLContainer<>("postgres:17");
  @Autowired TestRestTemplate http;

  @Test void overlappingBookingIsRejected() {
    var first = new BookingRequest(1L, LocalDate.of(2026, 12, 1), LocalDate.of(2026, 12, 3));
    var clash = new BookingRequest(1L, LocalDate.of(2026, 12, 2), LocalDate.of(2026, 12, 4));
    assertEquals(201, post(first).getStatusCode().value());
    assertEquals(409, post(clash).getStatusCode().value());
  }
  // post(...) adds a test JWT header and calls /api/bookings
}

Quick reference

  • Return 201 + Location on create, 409 on conflicts, 403 for wrong role, 401 when not logged in
  • Flyway files: db/migration/V1__init.sql (two underscores); never edit one that already ran
  • spring.jpa.hibernate.ddl-auto=validate when Flyway owns the schema
  • Let the database enforce invariants such as no overlapping bookings
  • @EnableMethodSecurity + @PreAuthorize("hasRole('ADMIN')") for admin-only methods
  • @ServiceConnection on a Testcontainers field wires the URL into Spring Boot
  • Load the JWT secret and DB password from env vars; commit only .env.example
  • README: what it does, how to run it, example curl calls, test and CI badges

Common mistakes

  • Starting with microservices instead of one well-structured service.
  • No tests or a broken setup, so reviewers cannot run it.
  • Committing secrets such as the JWT key or database password.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1Two users book the same room for the same dates at the same moment. What is the most reliable way to stop a double booking?

Question 2

2A logged-in USER calls POST /api/rooms, which is admin only. Which status should they get?

Question 3

3Why set ddl-auto to validate when using Flyway?

Question 4

4With Spring's resource server defaults, a JWT with roles: ["ADMIN"] does not pass hasRole('ADMIN'). Why?

Question 5

5Which secret handling is right for a public capstone repo?

0/5 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Write the endpoint table for your capstone: method, path, role required, success status and main error statuses.

  2. Exercise 2medium

    Map the roles claim of your JWT to Spring authorities so hasRole('ADMIN') works.

  3. Exercise 3hard

    Cache the free-rooms search for 30 seconds and evict it whenever a booking is created or cancelled. Show the measured effect in the README.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

What should a Java backend portfolio project include?
Authentication, a real database with migrations, tests that run in CI, Docker for one-command setup, and a README explaining design choices. Depth and polish matter more than the number of features.
Should my capstone use microservices?
No. One well-structured service shows more judgment. You can describe in the README how you would split it if the system grew.
Do I need to deploy it?
It helps but is optional. A working docker compose up and a green CI run already let reviewers verify it; a small cloud deploy is a bonus.
How do I test secured endpoints without a real login?
In @WebMvcTest use the jwt() post-processor from spring-security-test, for example .with(jwt().authorities(new SimpleGrantedAuthority("ROLE_ADMIN"))).
ShareXLinkedInWhatsApp