Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .dockerignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,5 @@
*
!pom.xml
!src/
!mvnw
!.mvn/
59 changes: 59 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -26,3 +26,62 @@ jobs:
# locally, so the tests need nothing provisioned by the workflow.
- name: Build and test
run: ./mvnw -B verify

# Slower and independent of the test job: it compiles the application to a GraalVM native
# executable, checks that Dockerfile.native builds, and measures JVM mode against native mode.
native-build:
runs-on: ubuntu-latest

# The packaged application (not the tests) needs a real database, so this job does declare a
# PostgreSQL service. Dev Services only exists in dev and test mode.
services:
postgres:
image: postgres:16
env:
POSTGRES_DB: quarkus_tutorial
POSTGRES_USER: quarkus
POSTGRES_PASSWORD: ci-only-password
ports:
- 5432:5432
options: >-
--health-cmd "pg_isready -U quarkus -d quarkus_tutorial"
--health-interval 5s --health-timeout 3s --health-retries 10

env:
DB_URL: jdbc:postgresql://localhost:5432/quarkus_tutorial
DB_USER: quarkus
DB_PASSWORD: ci-only-password
# The repository's development key pair, fine for a throwaway CI database.
JWT_PUBLIC_KEY_LOCATION: ${{ github.workspace }}/dev-keys/publicKey.pem
JWT_PRIVATE_KEY_LOCATION: ${{ github.workspace }}/dev-keys/privateKey.pem

steps:
- name: Checkout
uses: actions/checkout@v4

- name: Set up Java 21
uses: actions/setup-java@v4
with:
distribution: temurin
java-version: "21"
cache: maven

- name: Package the JVM application
run: ./mvnw -B package -DskipTests

# container-build compiles inside a Mandrel builder container, so no local GraalVM is needed.
- name: Build the native executable
run: ./mvnw -B package -Dnative -Dquarkus.native.container-build=true -DskipTests

- name: Measure JVM mode against native mode
run: |
{
echo "| Mode | Ready after (ms) | Reported startup (s) | RSS after load (MB) |"
echo "|---|---|---|---|"
scripts/measure-startup.sh jvm java -jar target/quarkus-app/quarkus-run.jar
scripts/measure-startup.sh native target/*-runner
} | tee -a "$GITHUB_STEP_SUMMARY"
ls -l target/*-runner

- name: Check that Dockerfile.native builds
run: docker build -f Dockerfile.native -t quarkus-tutorial:native .
30 changes: 30 additions & 0 deletions Dockerfile.native
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# Multi-stage image for the GraalVM native executable.
# Stage 1 compiles the application to a native binary with Mandrel (Red Hat's GraalVM distribution),
# stage 2 keeps only that binary on a minimal runtime image: no JVM, no Maven, no sources.

FROM quay.io/quarkus/ubi9-quarkus-mandrel-builder-image:jdk-21 AS build
USER root
WORKDIR /build

# The builder image ships Mandrel but not Maven, so the Maven wrapper is used. Copying the wrapper and
# the pom alone first lets Docker cache the dependency download until the pom changes.
COPY mvnw .
COPY .mvn .mvn
COPY pom.xml .
RUN ./mvnw -B -q dependency:go-offline

COPY src ./src
# -Dnative switches on the pom's native profile. Tests are skipped here: they rely on Dev Services,
# which needs a Docker daemon a build stage does not have, and they run in CI with mvn verify.
RUN ./mvnw -B -q package -Dnative -DskipTests

# The runtime image only needs the C libraries the native binary links against.
FROM quay.io/quarkus/ubi9-quarkus-micro-image:2.0
WORKDIR /work

# Same idea as Dockerfile.jvm: never run as root.
COPY --from=build --chown=1001:root --chmod=0755 /build/target/*-runner /work/application

EXPOSE 8080
USER 1001
ENTRYPOINT ["./application", "-Dquarkus.http.host=0.0.0.0"]
8 changes: 4 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -404,10 +404,10 @@ Depends on `feature/categories` existing, since every product references one.

### Tasks

- [ ] `Dockerfile.native` (multi-stage: GraalVM builder image, minimal runtime image)
- [ ] Build a native executable locally (`mvn package -Dnative -Dquarkus.native.container-build=true`, container build so a local GraalVM install isn't required)
- [ ] Measure and document, in this branch's own notes: startup time and resident memory of the JVM-mode application versus the native executable, under the same request load
- [ ] `.github/workflows/ci.yml` extended with a native build verification job (can be slower/separate from the main test job)
- [x] `Dockerfile.native` (multi-stage: GraalVM builder image, minimal runtime image)
- [x] Build a native executable locally (`mvn package -Dnative -Dquarkus.native.container-build=true`, container build so a local GraalVM install isn't required). Built and run by the CI job, since the local Docker VM (1.4 GiB) is too small for it, see `docs/native-build.md`
- [x] Measure and document, in this branch's own notes (`docs/native-build.md`): startup time and resident memory of the JVM-mode application versus the native executable, under the same request load
- [x] `.github/workflows/ci.yml` extended with a native build verification job (can be slower/separate from the main test job)

## feature/reactive-endpoints (bonus)

Expand Down
55 changes: 55 additions & 0 deletions docs/native-build.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
# Native build notes

Notes for `feature/native-build`: how the native executable is built, and what it changes compared
with the JVM application.

## How it is built

- `Dockerfile.native` is a two stage build. Stage one compiles the application with Mandrel (Red Hat's
GraalVM distribution) through the pom's `native` profile. Stage two copies only the resulting binary
onto a micro runtime image, so no JVM, Maven or sources ship.
- Without Docker, the same executable comes from
`./mvnw package -Dnative -Dquarkus.native.container-build=true -DskipTests`. The build runs inside a
Mandrel builder container, so no local GraalVM install is needed.
- The CI job `native-build` in `.github/workflows/ci.yml` does both, builds the executable and checks that
`Dockerfile.native` builds, on every push and pull request. It is separate from the test job because it
takes around ten minutes.

## Measurements

Produced by `scripts/measure-startup.sh`, run by the CI job on the same runner, against the same
PostgreSQL 16 service, with the same load for both modes: 300 sequential requests cycling over
`/q/health/ready`, `/q/openapi` and a secured endpoint (401).

| Mode | Ready after (ms) | Startup reported by Quarkus (s) | RSS after the load (MB) |
|---|---|---|---|
| JVM (`java -jar quarkus-run.jar`) | 4021 | 3.832 | 249 |
| Native executable | 156 | 0.126 | 127 |

The native executable is about 103 MB on disk.

Reading the figures:

- Startup is roughly 25 times faster in native mode. The JVM has to load and link classes and JIT compile
at start, while the native binary already has its heap initialised and its code compiled.
- Memory after the load is about half. It is a single run on a shared CI runner, so treat the ratios as an
order of magnitude and not as a benchmark. The JVM figure would keep changing with more traffic, since
the JIT and the heap grow with it.
- The JVM run is the first to start against the empty database and so applies the Flyway migrations, while
the native run only validates them. That favours native by a few tens of milliseconds at most.
- What is given up: native builds take minutes and several GB of memory, the binary is tied to one
platform, and peak throughput after a long warm up is usually better on the JVM.

## Issues found while getting it to compile

- A `static final SecureRandom` in `AuthServiceImpl` failed the native build, because it was created while
the image was built and its seed would have been frozen into the image. It is now a field of the bean, created
when the application starts. This is a good example of the closed world model: code that runs at class
initialisation time is executed at build time in native mode.

## Building locally

Compiling a native image needs several GB of memory in the builder container (the CI build peaks at about
3.4 GB). On the development machine used for this tutorial, Docker Desktop was limited to 1.4 GiB, and the
build was killed by the out of memory killer, so the executable was built and measured in CI instead. Raise
the memory of the Docker VM to at least 6 GB to build locally.
60 changes: 60 additions & 0 deletions scripts/measure-startup.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
#!/usr/bin/env bash
# Starts the application, waits until it is ready, sends a fixed request load, then prints one
# markdown table row: time until /q/health/ready answers, the startup time Quarkus itself reports,
# and the resident memory of the process after the load.
#
# Usage: scripts/measure-startup.sh <label> <command> [args...]
# Expects the database and JWT settings (DB_URL, DB_USER, DB_PASSWORD, JWT_*_LOCATION) in the
# environment, and honours PORT (default 8090) and REQUESTS (default 300).
set -euo pipefail

label=$1
shift
port=${PORT:-8090}
requests=${REQUESTS:-300}
log="target/measure-${label}.log"

# An environment variable works for a jar and for a native binary alike; a -D option placed after
# "-jar" would be handed to the program instead of the JVM and silently ignored.
QUARKUS_HTTP_PORT="$port" "$@" >"$log" 2>&1 &
pid=$!
# Wait for the process to be gone, so the next measurement never finds the port still taken.
trap 'kill "$pid" 2>/dev/null || true; wait "$pid" 2>/dev/null || true' EXIT

start=$(date +%s%N)
until curl -sf "http://localhost:${port}/q/health/ready" >/dev/null; do
if [ $(( ($(date +%s%N) - start) / 1000000000 )) -gt 120 ]; then
echo "The application was not ready after 120 s:" >&2
tail -n 40 "$log" >&2
exit 1
fi
if ! kill -0 "$pid" 2>/dev/null; then
echo "The application exited before becoming ready:" >&2
tail -n 40 "$log" >&2
exit 1
fi
sleep 0.02
done
ready_ms=$(( ($(date +%s%N) - start) / 1000000 ))

# The same load for every mode: a health probe, the OpenAPI document and a secured endpoint
# (answers 401), which together exercise routing, serialization and the security stack.
for i in $(seq 1 "$requests"); do
case $((i % 3)) in
0) path=/q/health/ready ;;
1) path=/q/openapi ;;
2) path=/api/v1/products ;;
esac
# 401 is the expected answer of the secured endpoint; a refused connection (000) or a 5xx means the
# load did not exercise the application and the figures would be meaningless.
code=$(curl -s -o /dev/null -w '%{http_code}' "http://localhost:${port}${path}")
if [ "$code" = "000" ] || [ "$code" -ge 500 ]; then
echo "Request ${i} to ${path} answered ${code}" >&2
exit 1
fi
done

reported=$(grep -o 'started in [0-9.]*s' "$log" | head -n 1 | grep -o '[0-9.]*' || echo "n/a")
rss_mb=$(awk '/VmRSS/ {printf "%d", $2 / 1024}' "/proc/${pid}/status")

echo "| ${label} | ${ready_ms} | ${reported} | ${rss_mb} |"
Original file line number Diff line number Diff line change
Expand Up @@ -48,11 +48,16 @@ public class AuthServiceImpl implements AuthService {
private static final Duration RESET_TTL = Duration.ofMinutes(30);
private static final String INVALID_CREDENTIALS = "Invalid email or password";
private static final String INVALID_TOKEN = "The token is invalid, expired or already used";
private static final SecureRandom RANDOM = new SecureRandom();
// Computed once: verifying against it burns the same bcrypt time as a real check when the email is
// unknown, so response timing does not reveal whether an account exists.
private static final String DUMMY_HASH = BcryptUtil.bcryptHash("timing-equalizer");

// An instance field, not a static one, on purpose: a static SecureRandom is created while the GraalVM
// native image is built, which freezes its seed into the image (and the build refuses it). A field
// of an @ApplicationScoped bean is created when the running application starts, so it is seeded
// for real at run time, in JVM and native mode alike.
private final SecureRandom random = new SecureRandom();

@Inject
UserRepository userRepository;

Expand Down Expand Up @@ -201,9 +206,9 @@ private static UserResponse toResponse(User user) {
}

/** 256 bits from SecureRandom, URL-safe Base64 without padding. */
private static String newRawToken() {
private String newRawToken() {
byte[] bytes = new byte[32];
RANDOM.nextBytes(bytes);
random.nextBytes(bytes);
return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes);
}

Expand Down
Loading