What is a Spring Boot GraalVM native image and how does native compilation work?
A native image is a standalone, platform-specific executable produced by compiling your application ahead of time (AOT) rather than running bytecode on a JVM. GraalVM's native-image tool works under a closed-world assumption: every class, method and resource the program can use must be known at build time.
Starting from the application's entry points, static reachability analysis follows calls, field accesses and type usage, and compiles only what it can prove is reachable. Classes that are safe to initialize early run their static initializers during the build. The resulting objects are stored in a pre-initialized image heap embedded in the binary, so they don't have to be rebuilt at startup. The output has no JIT compiler, no bytecode interpreter and no runtime class loading. Code that the analysis did not see does not exist in the binary.
That constraint conflicts with how Spring normally works, because Spring discovers beans and evaluates conditions at runtime, often through reflection. Spring Boot's AOT processing closes that gap. Before GraalVM runs, it starts the application context at build time, evaluates bean definitions and @Conditional logic, and generates Java source for the bean wiring along with reachability hints. As a result, active profiles and conditional configuration are fixed in the binary. Changing them means rebuilding.
The pipeline:
sources -> Spring AOT processing -> generated code + hints -> GraalVM static analysis -> native executable
With the standard build plugins, you invoke it through ./mvnw -Pnative native:compile (Maven) or ./gradlew nativeCompile (Gradle).
# Maven: the 'native' profile from spring-boot-starter-parent runs Spring AOT
# processing first, then hands generated code + hints to GraalVM native-image.
./mvnw -Pnative native:compile
# Inspect what Spring AOT generated at build time (Maven layout):
# Java source for bean wiring, e.g. classes ending in __BeanDefinitions
find target/spring-aot/main/sources -name '*__BeanDefinitions.java' | head
# Reachability metadata (reflection, resources, proxies) passed to GraalVM
find target/spring-aot/main/resources/META-INF/native-image -name '*.json'
# The result is a standalone, platform-specific executable named after the
# artifactId (placeholder: demo-service). No JVM is needed to run it.
./target/demo-service
# Gradle equivalent (requires the org.graalvm.buildtools.native plugin):
./gradlew nativeCompile
# Spring AOT output (Gradle layout)
ls build/generated/aotSources build/generated/aotResources
# Executable location for Gradle builds
./build/native/nativeCompile/demo-service
# Profiles and @Conditional outcomes were evaluated during the build.
# Changing which beans exist means rebuilding the binary,
# not just passing a different profile at startup.
Building a Spring Boot native executable with the standard Maven and Gradle goals, then inspecting the Spring AOT-generated bean definition sources and reachability hints that GraalVM consumes before producing the binary.
Why does a native image use less memory than the JVM?
A HotSpot process spends a large share of its footprint on machinery that sits outside the Java heap. A native executable leaves most of that machinery out.
| Memory contributor | HotSpot JVM | Native image |
|---|---|---|
| JIT compiler threads and their working memory | Present, active during warm-up and recompilation | Absent; code is compiled ahead of time |
| Profiling data and JIT code cache | Grows as hot methods are compiled | Absent; machine code lives in the binary's text section |
| Class metadata (Metaspace) | Built at runtime as classes load, link and verify | Precomputed at build time, no runtime class loading |
| Framework objects created at startup | Allocated on the heap during startup | Partly pre-initialized in the image heap, mapped from the binary |
| Java heap for application data | Sized by -Xmx and GC ergonomics |
Still present and still grows with load |
The last row is why comparing -Xmx values misleads. -Xmx caps only the Java heap and says nothing about Metaspace, code cache, thread stacks or GC bookkeeping. On the JVM those regions often explain much of the gap between configured heap and actual process size. The number that matters is resident set size (RSS) under realistic traffic, measured on both runtimes with the same container limits.
Garbage collection also changes. Native Image supports fewer collectors than HotSpot. The default is a simple serial, stop-the-world collector, which suits small heaps but can produce pause spikes for latency-sensitive services with high allocation rates. Some distributions offer other collectors, but don't assume your HotSpot tuning carries over. Re-run load tests and check both RSS and tail latency before you trust the savings.
Is a native image faster than the JVM at steady state?
Startup and steady-state throughput are separate questions, and a native image wins clearly only on the first. A native binary starts fast because the work of class loading, initialization, and compilation already happened at build time. Once a long-running service is warm, the comparison often reverses.
Why a warmed-up JIT can win
HotSpot's JIT compiles hot methods using profiles collected from the live process: which branches are taken, which concrete types appear at a virtual call site, how often loops iterate. With that data it inlines aggressively and speculates. For example, it can assume a call site only ever sees one implementation. If the assumption breaks, it deoptimizes back to the interpreter and recompiles. The AOT compiler in native-image has no such feedback. It compiles once, before the application has seen real traffic, so it must produce code that is correct for every type and path it could reach. That code is usually more conservative.
Some GraalVM distributions offer profile-guided optimization to narrow this gap. You build an instrumented binary, run it against a representative workload to collect a profile, then rebuild using that profile. This adds a second build and a training run that has to stay representative as the code and traffic change.
The capacity effect
Lower per-instance memory does not guarantee a lower bill. Suppose a CPU-bound, long-running service gets less throughput per core as a native image. You may need more instances to handle the same load, and that can cancel out the memory and startup savings. Size the fleet from steady-state load tests, not from startup benchmarks.
How do you handle reflection config and other reachability metadata?
Native compilation works under a closed-world assumption. The build analyzes which code is reachable from main and discards everything else. Anything resolved by name at runtime is invisible to that analysis. This includes reflective calls like Class.forName, JDK dynamic proxies, classpath resources loaded by path, Java serialization and JNI lookups. To keep those elements in the image, you supply reachability metadata.
Spring's AOT processing generates most of this metadata for your beans, configuration classes and common framework patterns. For anything it can't infer, you implement RuntimeHintsRegistrar. Its registerHints method receives a RuntimeHints object with separate registries for reflection(), resources(), proxies(), serialization() and jni(). To activate the registrar, put @ImportRuntimeHints on a configuration class.
To find out what's missing, run the application on the JVM with GraalVM's tracing agent (-agentlib:native-image-agent). The agent records every dynamic access it observes and writes JSON config files. It only captures code paths that actually executed, though. An error handler or rarely used feature that your test run never triggered will still be missing. Drive the agent with a broad integration suite, not just a smoke test.
Third-party library support varies. Some libraries ship their own metadata. Others are covered by the community-maintained GraalVM reachability metadata repository, which Spring Boot's native build plugins can consume. Some have no coverage at all. Hand-written hints break silently when a library renames an internal class on upgrade.
That silence is the core risk. Missing metadata doesn't cause a build error. It shows up at runtime as a ClassNotFoundException, a missing resource or a failed proxy, often only on the specific path that needed it.
package com.example.app;
import org.springframework.aot.hint.MemberCategory;
import org.springframework.aot.hint.RuntimeHints;
import org.springframework.aot.hint.RuntimeHintsRegistrar;
import org.springframework.aot.hint.TypeReference;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportRuntimeHints;
// Activates the registrar during Spring AOT processing.
@Configuration(proxyBeanMethods = false)
@ImportRuntimeHints(NativeHintsConfig.AppHints.class)
public class NativeHintsConfig {
static class AppHints implements RuntimeHintsRegistrar {
@Override
public void registerHints(RuntimeHints hints, ClassLoader classLoader) {
// Plugin class loaded with Class.forName(), so static analysis never sees it.
hints.reflection().registerType(PricingPlugin.class,
MemberCategory.INVOKE_DECLARED_CONSTRUCTORS,
MemberCategory.INVOKE_PUBLIC_METHODS);
// Third-party internal class referenced by name. This hint breaks silently
// if the library renames the class in a later release.
hints.reflection().registerType(
TypeReference.of("com.vendor.sdk.internal.ResponseMapper"),
MemberCategory.INVOKE_DECLARED_CONSTRUCTORS);
// Template files read from the classpath by path at runtime.
hints.resources().registerPattern("templates/*.mustache");
// Interface implemented by a JDK dynamic proxy created at runtime.
hints.proxies().registerJdkProxy(AuditClient.class);
// Type written and read with Java serialization (e.g. a session cache).
hints.serialization().registerType(CartSnapshot.class);
}
}
}
A RuntimeHintsRegistrar, activated with @ImportRuntimeHints, that registers reflection, resource, proxy and serialization hints for dynamic accesses that Spring AOT and the closed-world analysis cannot infer on their own.
How much does native compilation cost in build time and CI?
Native compilation is slow because native-image performs whole-program, closed-world analysis: it traces every reachable class, method and field from the entry points, runs Spring's ahead-of-time processing, initializes selected classes at build time, and then compiles the result into one binary. A jar build compiles each class to bytecode independently and leaves the rest of the work to the JVM at runtime. The analysis holds the entire application graph in memory, so native builds typically need several gigabytes of heap. Default CI runners can run out of memory or start swapping, which makes the build even slower.
This changes the local loop. A full native build takes minutes, not seconds. For that reason most teams develop and run unit tests on the JVM and produce native images only in CI. The drift risk follows from that split: code that runs on the JVM can still fail natively because of missing reachability metadata. Without a native test stage, the first time a developer sees that failure may be after deployment.
The binary is also platform-specific. One jar runs on any JVM on any architecture. A native image targets one OS and CPU architecture, so mixed amd64/arm64 fleets need a build per architecture, either on native runners or through cross-build infrastructure.
Illustrative estimate (assumed numbers, not a benchmark)
Formula: monthly minutes = builds/day × working days × minutes/build × architectures
| Build type | Builds/day | Working days | Min/build | Architectures | Monthly minutes |
|---|---|---|---|---|---|
| JVM jar | 20 | 22 | 4 | 1 | 1,760 |
| Native image | 20 | 22 | 15 | 2 | 13,200 |
How should you test and operate a native Spring Boot application?
JVM tests prove your logic; they do not prove the binary. Ahead-of-time processing changes what exists at runtime. A missing reflection hint, a resource the static analysis never saw, or a condition fixed during the build will pass every JVM test and fail only when the native executable runs. The usual symptom is an exception on the first request that reaches the affected path, not a startup failure.
The Spring Boot build tooling can compile your tests into a native executable and run them. With Maven, activate the nativeTest profile (mvn -PnativeTest test). With Gradle, run the nativeTest task. These runs are slow because they pay the full native compilation cost. Run them on merges to the main branch or nightly, not on every pull request. Always run them before a release candidate is promoted. Your fast JVM suite still gates each commit.
Operational differences
- Agents and instrumentation. Java agents that rewrite bytecode at runtime have no bytecode to rewrite, so they don't work in a native image. This affects APM agents and some mocking or weaving libraries. Use library-based instrumentation such as Micrometer and OpenTelemetry SDK integration instead, or confirm that the vendor supports native images.
- Diagnostics. Heap dump and monitoring support must be enabled when you build the image. The memory layout also differs from HotSpot, so update your runbooks and tooling.
- Profiles and conditions.
@Profileand@ConditionalOnPropertyare evaluated at build time, so the bean graph is frozen. Express environment differences as property values read at runtime, not as alternate beans.
#!/usr/bin/env bash
# CI test stage for a Spring Boot app that ships as a native executable.
# Assumes the Maven wrapper and the native-maven-plugin from spring-boot-starter-parent.
set -euo pipefail
# Set by your CI system; placeholder values shown.
BRANCH="${BRANCH:-feature/example}"
PIPELINE_KIND="${PIPELINE_KIND:-pull_request}" # pull_request | merge | nightly | release
# 1. Fast JVM suite gates every commit and pull request.
# It proves application logic but not that the native binary works.
./mvnw -B test
# 2. Native test suite: compiles the tests into a native executable and runs them.
# This catches missing reflection/resource hints and build-time-fixed
# @Profile / @ConditionalOnProperty decisions that JVM tests cannot see.
# It is slow because it pays the full native compilation cost, so run it only
# on main-branch merges, nightly builds, and before promoting a release candidate.
if [[ "$BRANCH" == "main" || "$PIPELINE_KIND" =~ ^(merge|nightly|release)$ ]]; then
./mvnw -B -PnativeTest test
# Gradle equivalent: ./gradlew nativeTest
fi
# 3. Release candidates also build the production executable.
# Profiles and conditions are evaluated during this build, so build with the
# same active profile you deploy; vary environments through runtime properties.
if [[ "$PIPELINE_KIND" == "release" ]]; then
./mvnw -B -Pnative -DskipTests native:compile
# Gradle equivalent: ./gradlew nativeCompile
fi
A CI script that gates every commit on the fast JVM test suite and runs the slower native test suite (-PnativeTest / nativeTest) only on main-branch merges, nightly builds and release candidates.
When should you use a native image, when should you avoid it, and what are the alternatives?
The deciding question is whether startup time and baseline memory dominate your cost. If they do, native compilation pays for its build and metadata overhead. If they don't, you take on that overhead and get little back.
| Workload shape | Recommended runtime | Main reason |
|---|---|---|
| Scale-to-zero services, serverless functions | Native image | Cold start sits on the request path |
| Short-lived batch jobs, CLIs | Native image | The process exits before JIT warm-up would pay off |
| Dense multi-tenant deployments with many small instances | Native image | Lower baseline memory per instance fits more instances per node |
| Long-running, high-throughput APIs | Tuned JVM | Profile-guided JIT and mature GCs win at steady state |
| Apps relying on runtime classpath scanning or dynamic class generation | JVM | These patterns conflict with the closed-world assumption |
| Dependencies without reachability metadata | JVM, or JVM with AOT | You would have to write and maintain the missing config yourself |
If you stay on the JVM, there are still ways to improve startup:
- A tuned JVM deployment. Set heap limits explicitly, choose a GC that suits your latency goals, and set container-aware sizing.
- Spring Boot AOT processing on the JVM. This moves bean-definition work to build time without the closed-world constraints of a native image.
- Class data sharing. It reuses parsed class metadata across runs, which shortens startup.
- Checkpoint/restore. You snapshot a warmed-up JVM and resume from that snapshot instead of booting from scratch.
The engineering-time argument is the one teams tend to underweight. Every library upgrade can break reflection config, and every native-only bug needs a long rebuild before you can reproduce it. That maintenance only makes sense where startup or memory savings show up in your bill or your latency SLOs. For a service that runs for weeks, those savings are close to zero, and the maintenance cost remains.
How OneEnv can help
Disclosure: OneEnv is the product behind this blog.
OneEnv (oneenv.io) is a workspace-based governance platform for the things services share — environment variables, database structure, API routes and validation rules. A change to a shared value is staged on a branch, reviewed once, and then every affected service explicitly approves or rejects it before it goes live, so you can see who a change touches before it ships instead of finding out in production.
Applied to spring boot graalvm native image, this is where it helps:
Saves time
- Every service that inherits a shared value is listed in one place, so nobody searches repos and chats to find out who is affected.
- One review per branch replaces coordinating each team separately; each service still keeps its own approve/reject.
- Reviewers see the exact diff and the list of affected services up front, so approval is a decision rather than an investigation.
Saves cost
- Fewer production incidents and rollbacks caused by a shared value, route or column changing under a consumer unannounced.
- Less duplicated configuration to maintain: one shared definition inherited by many services.
- Per-service approve/reject means a bad shared value can be refused where it would break something, before it is live.
- OneEnv has a free plan (1 workspace, unlimited services and members, full governance), so trying it costs nothing.
These are qualitative benefits, not measured results — how much you save depends on how many services share the value.
Want to try it? Start at oneenv.io.