Sub topic 14
Choosing native images: costs and benefits
This chapter helps you decide whether a native executable suits a given Spring Boot service. It assumes you can build a Spring Boot 3 project with Maven or Gradle, that you know what a container image is, and that you have read the earlier chapters on the closed-world assumption, Spring AOT processing, runtime hints and native builds. No new commands are introduced here. The goal is a decision method, not a recommendation for or against native images.
What you gain
A native executable is compiled ahead of time. It starts from a prepared heap image instead of loading classes, interpreting bytecode and warming up a JIT compiler. This gives three typical gains.
- Startup time. A service that takes seconds to start on the JVM often starts in tens of milliseconds as a native executable. Exact numbers depend on the application, so measure your own.
- Memory footprint. There is no JIT compiler, no class metadata for unused code and no profiling data in memory. Resident memory at idle is usually much lower than on the JVM.
- Packaging. The result is a single executable. A container image can be small because it needs no JDK.
These gains matter most when processes are started often, run briefly, or are packed densely onto shared hardware.
What you pay
Each gain has a cost, and most of the costs come from the closed-world assumption.
- Build time and build resources. Static analysis of the whole application, including the libraries and the Spring framework, takes minutes and several gigabytes of memory. A JVM build takes seconds. This lengthens every CI run and every local feedback loop.
- Peak throughput. The JVM's JIT compiler uses runtime profiling to optimize hot code. A native executable is optimized once, at build time, without that profile. For long-running, CPU-heavy services, the JVM can reach higher steady-state throughput and lower tail latency.
- Build-time fixing of the application. Spring evaluates conditions, profiles and bean definitions during AOT processing. Changing
app.feature.enabledat runtime does not add a bean that was excluded at build time. Configuration that the JVM lets you change per environment may need a separate build in native mode. - Metadata burden. Reflection, resources, proxies and serialization need reachability metadata. Spring and many libraries supply it. Your own code and less common libraries may not, and failures appear only at runtime.
- Operational differences. Dynamic class loading, runtime agents (including many APM agents), and JVM tools such as JMX-based monitoring, heap dumps and
jcmdare limited or unavailable. Debugging uses different tools. - Portability. The executable targets one operating system and CPU architecture. A build on an ARM laptop does not run on an x86 server. Cross-platform delivery needs a build per target.
The table summarizes the comparison.
| Concern | JVM | Native executable |
|---|---|---|
| Startup | Seconds | Milliseconds to tens of milliseconds |
| Idle memory | Higher | Lower |
| Peak throughput | Often higher after warm-up | Often lower, no runtime profiling |
| Build time | Seconds | Minutes |
| Dynamic features | Full support | Restricted, needs metadata |
| Runtime configuration of beans | Flexible | Fixed at build time for conditions and profiles |
| Tooling and diagnostics | Full JVM tooling | Reduced |
| Portability | One artifact per Java version | One artifact per OS and CPU |
A decision workflow
Work through these questions in order. Stop at the first one that settles the decision.
- Is there a hard blocker? A required library that does not work in native mode, a dependency on a runtime agent, or a need to change bean wiring at runtime without rebuilding all rule out native images for now.
- Does startup or memory drive cost or behavior? If startup time decides whether the service meets its requirements, native is a strong candidate. Examples are scale-to-zero platforms, serverless functions, command-line tools and autoscaling that reacts to traffic spikes. Memory matters when you run many small instances and pay per gigabyte.
- Is the service long-running and CPU-bound? If it runs for days, is warm most of the time and is limited by throughput, the JVM's JIT likely wins. Startup savings are paid once and become negligible.
- Can your pipeline absorb the build cost? Check CI time, CI memory and developer feedback. A common arrangement is to develop and run most tests on the JVM, then build and test the native executable in CI.
- Can you test it as native? Native-only failures are real. If you cannot run the native test suite (
./mvnw -PnativeTest test) or a smoke test against the built executable, you carry risk into production.
Workload examples
The same decision method gives different answers for different services.
| Workload | Likely choice | Reason |
|---|---|---|
| Serverless function invoked rarely | Native | Cold start dominates the cost and latency |
| Command-line tool built with Spring Boot | Native | Process lifetime is short, so JVM startup is most of the run |
| Many small microservices on a shared cluster | Native, if tests pass | Lower memory per instance allows denser packing |
| Large monolith with heavy reflection and plugins | JVM | Metadata effort is high and startup is rarely critical |
| Batch or streaming service, always warm, CPU-bound | JVM | JIT optimization improves throughput over time |
| Service relying on a runtime APM agent | JVM | Agents that rewrite bytecode at runtime do not work |
A service may also use both modes. Run the JVM in development and in a long-lived production environment, and ship a native build for edge or scale-to-zero deployments, as long as you test both.
Reducing the costs
Several practices keep the cost of native images manageable.
- Keep the JVM as the default for development. Run the application and most tests on the JVM for fast feedback. Build native in CI on a branch or before release.
- Run native tests regularly. Failures that appear only in native mode, such as a missing reflection hint, are cheapest to fix when they come from a recent change.
- Move configuration decisions to build time deliberately. If a property controls a conditional bean, treat it as part of the build, and document which values each build uses.
- Prefer libraries that publish reachability metadata. Check that a dependency supports native images before you adopt it. For your own code, register hints with
RuntimeHintsRegistrar, or use the tracing agent to collect them. - Size build agents for the job. Native builds are memory-hungry. Give CI runners enough RAM, and cache dependencies.
- Use buildpacks for consistent builds.
./mvnw -Pnative spring-boot:build-imageor./gradlew bootBuildImagebuilds a native container without a local GraalVM installation. This also solves the portability issue when the build runs on the same architecture as the deployment target.
Measure before you commit
Do not decide from published figures alone. Build a native version of your actual service and compare it with the JVM version under your expected load.
- Record time to first successful request, not just the time the log prints "Started".
- Record resident memory at idle and under typical load.
- Run a load test long enough to include JVM warm-up, and compare throughput and p99 latency.
- Record native build duration and peak build memory.
- Run the full test suite in native mode and note any failures and the effort to fix them.
If the native version meets a requirement the JVM version cannot, such as a cold-start limit, and the costs are acceptable, adopt it. If the gains are small, the JVM is simpler to build, debug and operate.
Common mistakes in the decision
- Choosing native for a long-running service only because of startup numbers. Startup is a one-time saving. Check whether it matters in your deployment.
- Ignoring build cost. A ten-minute build on every commit slows the team more than a few seconds of JVM startup.
- Assuming that passing JVM tests means the native build works. Reflection, resource and proxy problems appear only in the native executable.
- Treating runtime configuration as free. In native mode, some configuration is fixed when the application is built.
- Not planning for diagnostics. Decide in advance how you will profile, trace and debug a native service in production.
Exercise
A team runs a Spring Boot service that processes a steady stream of messages 24 hours a day on four CPU-heavy instances. Startup takes eight seconds and is never a problem, because deployments are rare. They consider switching to a native executable to "improve performance". Using the criteria in this chapter, what would you advise, and what would you measure if they still wanted to try?
Show answer
Advise staying on the JVM. Startup is not a constraint, the service is long-running and CPU-bound, and the JIT compiler is likely to give equal or better steady-state throughput. A native build would add build time and metadata risk with little benefit. If they still want to try, build a native version and compare it with the JVM version under production-like load over a long enough period to include warm-up. Measure throughput, p99 latency, resident memory, build duration and peak build memory, and run the native test suite to see how many native-only failures appear.
Exercise
A property app.feature.enabled controls a @ConditionalOnProperty bean. The JVM deployment sets it differently in staging and production through environment variables. What problem does this cause for a native deployment, and how can you handle it?
Show answer
Spring evaluates the condition during AOT processing, so the value present at build time decides whether the bean exists in the executable. Setting the variable at runtime does not add a bean that was excluded at build time. Either build a separate native executable for each value, or change the design so the bean is always present and the feature is switched at runtime, for example with a normal property check inside the bean.