Sub topic 14
Native Images with GraalVM: Trade-offs
This chapter covers what a GraalVM native image is, how to build one from a Spring Boot application, and how to decide whether it fits your deployment. It assumes you can build a Spring Boot JAR with Maven or Gradle, run it with java -jar, and build a container image as covered in earlier chapters.
What a native image is
A normal Spring Boot application runs on the JVM. At startup the JVM loads classes, interprets bytecode, and compiles hot methods to machine code with the JIT (just-in-time) compiler.
A GraalVM native image moves most of that work to build time. The native-image tool performs ahead-of-time (AOT) compilation. It analyzes your application and its libraries, and it produces one platform-specific executable. That executable contains your compiled code, the parts of the JDK it needs, and a small runtime called Substrate VM. It does not need a JVM installed to run.
The tool uses a closed-world assumption. It starts from the entry point and finds every class, method, and field that can be reached. Anything it cannot prove is reachable is left out of the executable. This is where most of the trade-offs come from.
What you gain
- Fast startup. A typical Spring Boot service that needs a few seconds on the JVM can start in well under a second as a native executable. The exact figures depend on the application.
- Lower memory at idle. There is no JIT compiler, no loaded class metadata for unused code, and no bytecode interpreter. Resident memory is often much smaller than for the same application on the JVM.
- A smaller runtime image. The container does not need a JRE. The executable can run on a minimal base image.
- Immediate full speed. There is no warm-up period. The first requests are not slower than later ones.
These benefits matter most when instances start and stop often, or when many small instances run at once. Examples are serverless functions, scale-to-zero services, command-line tools, and short-lived batch jobs.
What you give up
- Long build times. The AOT analysis is expensive. A native build commonly takes minutes and uses several gigabytes of memory, where a JAR build takes seconds.
- Lower peak throughput in many cases. The JIT compiler uses runtime profiling to optimize hot paths. A native image has no such profile. For a long-running, CPU-heavy service, the JVM may be faster after warm-up. Profile-guided optimization (PGO) can narrow the gap, but it needs extra build steps and may need a GraalVM edition with that feature.
- Platform-specific output. An executable built on Linux x86-64 will not run on macOS or on Linux ARM. Build on the target platform or use a build container.
- Dynamic features need metadata. Reflection, resource loading, JDK proxies, and serialization depend on information the build cannot always see. You must supply it as configuration.
- Harder debugging and monitoring. The usual JVM tools, such as JMX-based tooling, Java agents, and
jcmd, do not work the same way. Native images have their own diagnostics, which are more limited. - Fixed build-time decisions. Some choices are frozen when you build. Examples are the set of Spring beans, and the values of conditions evaluated at build time.
How Spring Boot supports native images
Spring Framework and Spring Boot include AOT processing. When you run the AOT phase, Spring evaluates your configuration at build time. It generates source code that creates the bean definitions directly, and it generates the reachability metadata that GraalVM needs for reflection, resources, and proxies. This replaces most of the dynamic classpath scanning and condition evaluation that normally happens at startup.
Because of this, a native Spring Boot application has some rules:
- The set of beans is fixed at build time. A
@Profileor@ConditionalOnPropertycondition is evaluated during the build. Changing the active profile at run time will not add or remove beans that were decided at build time. - The classpath is fixed at build time. You cannot add a JAR later.
- Spring Boot's
@ConfigurationPropertiesbinding still works with values from the environment, so ordinary externalized configuration (ports, URLs, passwords) remains a run-time matter.
The practical rule: run-time values such as server.port or spring.datasource.url can still be supplied from outside. Values that choose which beans exist should be treated as build-time decisions.
Building a native image
There are two common routes. Both need a GraalVM-capable build environment, or a container that provides one.
Route 1: Buildpacks, with no local GraalVM
The buildpack route from the earlier chapter works for native images too. The plugin runs the compilation inside a builder container, so you do not install GraalVM yourself. You need a running Docker daemon.
# Maven
./mvnw -Pnative spring-boot:build-image -Dspring-boot.build-image.imageName=myorg/myapp-native:1.0.0
# Gradle
./gradlew bootBuildImage --imageName=myorg/myapp-native:1.0.0With Maven, the native profile is defined in the spring-boot-starter-parent and activates the GraalVM native build plugin. With Gradle, applying the org.graalvm.buildtools.native plugin makes bootBuildImage produce a native image.
Run the resulting image like any other container:
docker run --rm -p 8080:8080 \
-e DB_URL=jdbc:postgresql://db:5432/app \
-e DB_PASSWORD=change-me \
myorg/myapp-native:1.0.0Route 2: A native executable on your machine
If GraalVM is installed and JAVA_HOME points to it, you can produce a plain executable.
# Maven
./mvnw -Pnative native:compile
# Gradle
./gradlew nativeCompileThe output is in target/ for Maven, or build/native/nativeCompile/ for Gradle. Run it directly:
./target/myapp --server.port=9090Command-line arguments and environment variables still work. There is no java -jar step.
Running tests against the native build
Passing tests on the JVM does not prove the native executable works. Reflection and resource problems appear only after native compilation. The native build tools can run your JUnit tests as a native executable:
# Maven
./mvnw -PnativeTest test
# Gradle
./gradlew nativeTestRun these in CI. They are slow, so many teams run them on the main branch or before release, instead of on every commit.
Common problems
| Symptom | Likely cause | Typical fix |
|---|---|---|
| `ClassNotFoundException` or `NoSuchMethodException` at run time, but not on the JVM | Reflection use that the build did not detect | Register the type with `@RegisterReflectionForBinding` or a `RuntimeHintsRegistrar` |
| A resource file such as a template or a JSON file is missing | Resource was not included in the executable | Register a resource hint |
| Build runs out of memory | Analysis needs several gigabytes | Increase memory for the build machine or container |
| A bean that exists on the JVM is missing | Condition was evaluated at build time with different properties | Set the property during the AOT build, or change the design |
| The executable fails on another machine | Built for a different OS or CPU architecture | Build on, or for, the target platform |
| A library fails in native mode | Library has no native support or metadata | Check the library's documentation, or look for newer versions |
Providing hints
When your own code uses reflection, you tell the AOT engine about it. The simplest option is an annotation on a configuration class.
import org.springframework.aot.hint.annotation.RegisterReflectionForBinding;
import org.springframework.context.annotation.Configuration;
@Configuration
@RegisterReflectionForBinding(ExternalPayload.class)
public class NativeHintsConfig {
}public record ExternalPayload(String id, String name) {
}@RegisterReflectionForBinding registers the class for reflection so that serialization libraries, such as Jackson, can read and write it. For resources or more complex cases, implement RuntimeHintsRegistrar and import it with @ImportRuntimeHints.
Deciding when to use a native image
Use these criteria:
- Instance lifecycle. If instances start and stop often, or scale to zero, startup time directly affects cost and latency. A native image helps. If instances run for weeks, startup is a one-time cost and matters little.
- Resource limits. If you pay per megabyte or run many small replicas, lower memory helps. If a few large instances serve steady traffic, the JVM's memory use is usually acceptable.
- Peak throughput. Measure it. If the service is CPU-bound and long-running, test the JVM against the native image under realistic load before committing.
- Dependencies. Check that every library you rely on works in native mode. Older or less common libraries are the main source of surprises.
- Dynamic behavior. If your design relies on loading plugins, changing beans through profiles at run time, or heavy reflection, the closed-world model will fight you.
- Team and pipeline cost. Longer builds, native tests, and platform-specific artifacts add work. A small team may prefer to keep the simpler JVM pipeline.
There are middle options. You can reduce JVM startup with class data sharing (CDS) or AOT cache features in recent JDKs, and with the layered JAR and container tuning from earlier chapters. Try these first if startup is the only concern.
Summary of the trade-off
| Aspect | JVM (executable JAR) | GraalVM native image |
|---|---|---|
| Startup time | Seconds | Typically well under a second |
| Memory at idle | Higher | Lower |
| Peak throughput | Often higher after warm-up | Often lower without PGO |
| Build time | Seconds | Minutes |
| Portability | Same JAR on any OS with a JVM | One executable per OS and CPU |
| Reflection and dynamic features | Work freely | Need hints and metadata |
| Profile-driven bean changes at run time | Supported | Fixed at build time |
| Diagnostics | Full JVM tooling | More limited |
Exercise
A team runs a Spring Boot service on Kubernetes. It has one steady replica that serves constant traffic for months. The service is CPU-heavy, and the build pipeline takes about two minutes today. A developer proposes moving to a native image to "make it faster." Give two reasons this may not help, and name one measurement the team should take before deciding.
Show answer
First, the main native benefits are fast startup and low idle memory. A single long-lived replica starts rarely, so faster startup saves little. Second, the JIT compiler can optimize hot paths after warm-up, so a CPU-heavy, long-running service may have equal or better peak throughput on the JVM. Native builds would also lengthen the pipeline well beyond two minutes. Before deciding, the team should run a load test that compares throughput and latency (for example p99 latency at the expected request rate) for the JVM build and the native build. Memory use under the same load is also worth recording.
Exercise
Your application runs correctly on the JVM. In the native build, a request fails with an error saying Jackson cannot access the constructor of a class named ExternalPayload. What is the likely cause, and how do you fix it?
Show answer
The class is used through reflection by Jackson, but the AOT build did not detect it, so the native executable has no reflection metadata for it. Register it with @RegisterReflectionForBinding(ExternalPayload.class) on a configuration class, or provide a RuntimeHintsRegistrar. Then rebuild the native image and run the native tests to confirm the fix.