GraalVM Native Image with AWS Fargate and Graviton2 to cut cost and startup of Java microservices - Meu Universo Nerd

There is a way to make your Java microservice boot in 50 milliseconds instead of 8 seconds, without rewriting a single line of business logic. Most developers still package the entire JVM inside the container and pay for that on the AWS bill every month.

With GraalVM Native Image and the AWS SDK for Java 2.x, you compile the application into a native binary and the startup time drops immediately. In this article you will build it from scratch, with Maven, a Dockerfile and a Fargate deploy, and you will understand why this decision became a senior interview question in fintech.

There is a way to make your Java microservice boot in 50 milliseconds instead of 8 seconds, without rewriting a single line of business logic. Most developers still package the entire JVM inside the container and pay for that on the AWS bill every month.

With GraalVM Native Image and the AWS SDK for Java 2.x, you compile the application into a native binary and the startup time drops immediately. In this article you will build it from scratch, with Maven, a Dockerfile and a Fargate deploy, and you will understand why this decision became a senior interview question in fintech.

Let's solve this for good.

Why the traditional JVM is heavy on Fargate

The classic model works like this: you package a JAR, ship an image with the full JVM, and every time the container starts, the virtual machine has to load classes, warm up the JIT and only then is your application ready. Think of a giant lunchbox that carries the stove along with the food. It works, but you are moving weight you will never use on the plate.

In practice, an average Spring Boot microservice takes 4 to 8 seconds to answer the first request. In a serverless environment that is money leaving your pocket. On Fargate you pay for vCPU and memory during the entire lifetime of the task, including the cold start. On Java Lambda functions, that delay becomes direct latency for the end user.

# Traditional Dockerfile: the whole JVM travels along
FROM eclipse-temurin:21-jre
COPY target/pedidos-service.jar app.jar
ENTRYPOINT ["java", "-jar", "app.jar"]
# Final image: ~280MB. Startup: ~6s. Idle memory: ~350MB

The problem is not your code. It is the runtime architecture. The JVM was designed for long running processes on servers that turn on and stay up for weeks. An ephemeral container that spins up, handles a spike and dies is the opposite scenario. As a Tech Leader, I learned that picking the wrong runtime for the workload lifecycle is the kind of decision nobody notices until the AWS invoice shows up.

The official GraalVM Native Image documentation explains in depth the ahead-of-time compilation mechanism that solves this.

GraalVM Native Image: what actually changes

Native Image does ahead-of-time (AOT) compilation. Instead of carrying the JVM and interpreting bytecode at runtime, GraalVM analyzes the whole application at build time, finds out which classes and methods are actually reachable and generates a native operating system executable. No JIT, no warmup, no class loading at runtime.

The result is a binary that boots almost instantly and uses a fraction of the memory. The thing that used to block adoption was reflection configuration: GraalVM needs to know at build time everything that will be accessed dynamically. The good news is that this changed.

<!-- pom.xml: the GraalVM native plugin -->
<plugin>
    <groupId>org.graalvm.buildtools</groupId>
    <artifactId>native-maven-plugin</artifactId>
    <configuration>
        <imageName>pedidos-service</imageName>
        <buildArgs>
            <buildArg>--no-fallback</buildArg>
        </buildArgs>
    </configuration>
</plugin>

If you use AWS services inside the app, the AWS SDK for Java 2.x started embedding the GraalVM reachability metadata from version 2.28.7 onward. Translation: that hell of writing dozens of reflect-config.json files by hand to make the SDK work in native image is over. It comes ready.

import software.amazon.awssdk.services.dynamodb.DynamoDbClient;

@Service
public class PedidoRepository {

    private final DynamoDbClient dynamo;

    public PedidoRepository(DynamoDbClient dynamo) {
        this.dynamo = dynamo; // SDK 2.28.7+ already ships reachability metadata
    }

    public Pedido find(String id) {
        // Same code as the JVM version. Nothing changes here.
        return mapper.fromItem(dynamo.getItem(req -> req.key(keyOf(id))));
    }
}

Notice the detail that changes everything: the business code is identical. You do not rewrite repository, controller or service. The change is in the build and the packaging, not in the logic.

Build in practice: Maven plus a multi-stage Dockerfile

Here is the way I use it in production. A multi-stage Dockerfile that compiles the native binary inside a GraalVM image and copies only the binary into a tiny final image. That way the deploy image carries neither compiler nor JDK.

# Stage 1: compile the native binary
FROM ghcr.io/graalvm/native-image-community:21 AS build
WORKDIR /app
COPY . .
RUN ./mvnw -Pnative native:compile -DskipTests

# Stage 2: final image with only the executable
FROM debian:stable-slim
COPY --from=build /app/target/pedidos-service /pedidos-service
EXPOSE 8080
ENTRYPOINT ["/pedidos-service"]
# Final image: ~90MB. Startup: ~0.05s. Memory: ~64MB

The local build command is straightforward. It compiles, generates the binary and you test it before pushing to the registry:

# compile the native binary (needs GraalVM installed)
./mvnw -Pnative native:compile -DskipTests

# run the binary directly, no java -jar
./target/pedidos-service

# build the image and push to ECR
docker build -t pedidos-service:native .
docker tag pedidos-service:native <account>.dkr.ecr.sa-east-1.amazonaws.com/pedidos-service:native
docker push <account>.dkr.ecr.sa-east-1.amazonaws.com/pedidos-service:native

An honest point few people mention: the native build is slower than the regular build. AOT compilation can take 2 to 5 minutes against the seconds of a JAR. You trade build time for startup time and runtime cost. For a service that scales a lot, the trade-off pays off. For a batch that runs once a day, maybe not. It is worth checking the Spring Boot Native Images guide if you use Spring, because the ecosystem ships ready-made hints for most starters.

When a library has no native support

This is the moment most people give up on native image and run back to the JVM. You do not have to. When a third party library uses reflection, serialization or dynamic proxies without providing hints, the native build fails or the app breaks at runtime with a weird ClassNotFoundException. The senior solution is to register the hints yourself, and Spring Boot 3 makes that elegant with the RuntimeHintsRegistrar interface.

import org.springframework.aot.hint.RuntimeHints;
import org.springframework.aot.hint.RuntimeHintsRegistrar;
import org.springframework.aot.hint.MemberCategory;

// Registers reflection for a legacy library class
public class LegacyHints implements RuntimeHintsRegistrar {

    @Override
    public void registerHints(RuntimeHints hints, ClassLoader cl) {
        hints.reflection().registerType(
            LegacyOrder.class,
            MemberCategory.INVOKE_PUBLIC_METHODS,
            MemberCategory.INVOKE_PUBLIC_CONSTRUCTORS
        );
    }
}

Then you plug the registrar into the application with one annotation, and the native build starts seeing the class that was invisible to the AOT analysis before:

@SpringBootApplication
@ImportRuntimeHints(LegacyHints.class)
public class OrdersApplication {
    public static void main(String[] args) {
        SpringApplication.run(OrdersApplication.class, args);
    }
}

At the company where I worked, that is exactly how we unblocked the migration of a service that depended on an internal mainframe integration library with no GraalVM support at all. Half an afternoon of hints and the service that took 7 seconds to boot started answering in under 100 milliseconds. The platform team thought we had switched languages. We only switched the packaging. If you want the test agent flow to validate the binary before shipping, the AWS SDK native image guide brings the smoke test checklist we use.

Deploy on Fargate and the Graviton2 jump

With the native image on ECR, the Fargate deploy is the usual one: a task definition pointing to the image. The difference shows up in your wallet. And there is an extra lever that separates the mid-level from the senior when optimizing cost: running on Graviton2, the AWS ARM processors.

{
  "family": "orders-service",
  "requiresCompatibilities": ["FARGATE"],
  "cpu": "256",
  "memory": "512",
  "runtimePlatform": {
    "cpuArchitecture": "ARM64",
    "operatingSystemFamily": "LINUX"
  }
}

The numbers I see in practice when moving from a traditional JVM to native image on Fargate ARM:

  • Startup: from around 6 seconds to roughly 50 milliseconds, close to a 96% reduction
  • Idle memory: from about 350MB to around 64MB, which lets you cut the memory reserved by the task
  • Image: from 280MB to about 90MB, with faster push and pull on the CI/CD
  • Cost: Graviton2 delivers up to about 40% better price-performance than the equivalent x86

Put it all together: you reserve less memory per task, scale faster because the container is ready almost instantly, and still pay less per vCPU on ARM. On a service with aggressive autoscaling, that is the difference between a healthy invoice and an awkward meeting with the finance team.

When to use it and when to hold the hype

Native Image is not a silver bullet. It is a tool with a right context of use.

It pays off when:

  • Microservices and Lambda functions that spin up and down often (cold start matters)
  • Services with aggressive autoscaling, where fast startup cuts real cost
  • Apps where the cloud bill is already a concrete pain at the end of the month

Think twice when:

  • The service stays up for weeks and startup is no bottleneck at all
  • You depend on old libraries that use heavy reflection without native image hints
  • Your team has no room in the CI for longer builds right now

If you want to review how the thread lifecycle affects this kind of decision, it is also worth reading our content about Virtual Threads in Spring Boot and the material on observability with OpenTelemetry in Java, because optimizing cost without seeing the metric is betting in the dark. If you want to go deeper into packaging, we have a guide on Docker for Java applications the right way.

Frequently asked questions

Does GraalVM Native Image work with any Spring Boot application?
It works with most of them from Spring Boot 3 on, which already ships first class AOT support. The care is with third party libraries that use reflection without providing hints. Spring Boot generates a good part of the hints automatically in the native build.

Do I need to rewrite my code to migrate?
No. Controller, service and repository stay the same. The change is in the build (native plugin, Maven profile) and in the Dockerfile. The gain comes from the packaging, not from touching the business logic.

Why does the native build take so long?
Because the ahead-of-time compilation analyzes the whole application to find what is reachable and generate the executable. You trade build time for instant startup and less runtime memory. On CI, it is worth parallelizing or caching stages.

Does Graviton2 require changing the Java code?
No. The JVM and GraalVM run on ARM64 normally. You only adjust the base image to ARM and the cpuArchitecture field in the Fargate task definition. The bytecode and the native binary handle the rest.

Takeaways and next step

  • Native Image cuts startup and memory without you rewriting the business logic, only touching build and packaging
  • AWS SDK 2.28.7+ already ships the reachability metadata, which kills the most annoying part of reflection configuration
  • Fargate on Graviton2 adds up to about 40% price-performance on top of the native gain, and that is exactly the kind of decision that comes up in a senior cloud cost optimization interview

Have you already run native Java on your stack, or do you still package the whole JVM in the container? Tell me in the comments how the AWS bill is going on your side, I want to trade real numbers with you.

Next week I will show how to measure this gain for real, with cold start and cost per request observability on CloudWatch, so you bring data and not guesswork to the architecture meeting.