Skip to content
javahacks.dev
Micronaut

Micronaut AWS Lambda Deployment With Native and SnapStart

Deploy Micronaut to AWS Lambda as a function or an API: choose a handler, build a JVM or GraalVM native artifact, use SnapStart and cut cold starts.

7 min read
Summarize in AI
Flat illustration of shipping containers stacked on a ship, with the Docker, GitHub Actions and Jenkins logos.

Lambda bills by time and punishes slow startup, which is where classic reflection-heavy frameworks suffer. Micronaut was designed to start quickly. This covers Micronaut 4 on AWS Lambda.

Two shapes

A function handles one event, for example an S3 object or a queue message:

java
@Introspected
public class OrderEventHandler extends MicronautRequestHandler<SQSEvent, Void> {

    @Inject OrderProcessor processor;

    @Override
    public Void execute(SQSEvent event) {
        event.getRecords().forEach(r -> processor.process(r.getBody()));
        return null;
    }
}

An API is a normal Micronaut controller app deployed behind API Gateway or a function URL:

java
@Controller("/orders")
class OrderController {
    @Get("/{id}")
    OrderView get(long id) { ... }
}

The Lambda runtime adapter translates the proxy event into a Micronaut request, so the controllers run unchanged.

Dependencies

XML
<dependency>
  <groupId>io.micronaut.aws</groupId>
  <artifactId>micronaut-function-aws-api-proxy</artifactId>
</dependency>

Use micronaut-function-aws for a plain function. The Micronaut Launcher or mn create-app --features=aws-lambda sets up the build and the packaging.

Runtime options

OptionCold startNotes
Java 21 runtime, fat jarSlowest, still short for MicronautSimplest to build
Java runtime with SnapStartFast, restored from a snapshotNeeds checks for stale state
GraalVM native, provided.al2023FastestLonger build, native constraints
Container imageDepends on contentLarger image limit, custom base

SnapStart

SnapStart takes a snapshot of the initialized runtime after the init phase, and restores it for cold starts. State created during init, such as random seeds, connections and cached timestamps, is shared by every restored copy. Re-create such state in a restore hook, using a CRaC Resource as the Micronaut docs describe, and keep the function idempotent about unique IDs.

Native

Build a native executable with the Micronaut Gradle or Maven plugin, packaged as a zip with a bootstrap file, for the provided.al2023 runtime. Compile on an Amazon Linux environment or in a container, so the binary matches the target platform. The issues you will meet are reflection and resources, which Micronaut's introspection reduces, see the native image build and, for JSON, Micronaut Serialization.

Cold start habits

  • Keep the jar small: only the modules you use.
  • Initialize SDK clients outside the handler method so a warm instance reuses them.
  • Avoid @Context beans, which are created eagerly at startup, unless they are needed for every invocation.
  • Set memory higher: Lambda gives CPU in proportion to memory, so 512 MB to 1024 MB often starts faster and costs less in total.

Deploy

Define the function with the AWS SAM, CDK or Terraform and upload the artifact. A minimal SAM snippet for the API shape:

YAML
Resources:
  OrdersFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: io.micronaut.function.aws.proxy.payload2.APIGatewayV2HTTPEventFunction
      Runtime: java21
      CodeUri: build/libs/orders-all.jar
      MemorySize: 1024
      SnapStart: { ApplyOn: PublishedVersions }
      Events:
        Http: { Type: HttpApi }

Pin versions with aliases so SnapStart applies, and test cold starts from a deployed version, not from a local run. General deployment practice is in Java on AWS Lambda with SnapStart.

Test the handler before it reaches AWS

A Lambda that only fails in the console costs a deploy per experiment, so the handler gets a plain JUnit test first. MicronautRequestHandler has a constructor that takes an ApplicationContext, which lets the test start the same dependency injection graph the function uses, with a fake OrderProcessor in place of the real one.

src/test/java/dev/javahacks/OrderEventHandlerTest.javajava
class OrderEventHandlerTest {

    @Test
    void processesEveryRecordInTheBatch() {
        List<String> seen = new ArrayList<>();
        try (ApplicationContext ctx = ApplicationContext.run()) {
            ctx.registerSingleton(OrderProcessor.class, seen::add);
            var handler = new OrderEventHandler(ctx);

            var event = new SQSEvent();
            event.setRecords(List.of(message("order-1"), message("order-2")));
            handler.execute(event);
        }
        assertEquals(List.of("order-1", "order-2"), seen);
    }

    private static SQSEvent.SQSMessage message(String body) {
        var m = new SQSEvent.SQSMessage();
        m.setBody(body);
        return m;
    }
}

The test registers the fake as a singleton, so no queue, no AWS credentials and no network are involved. It runs in milliseconds, which means the handler logic is settled before packaging starts. The same trick works for the API shape: build an APIGatewayV2HTTPEvent by hand and call new APIGatewayV2HTTPEventFunction(ctx).handleRequest(event, context).

Report partial failures from a queue batch

An SQS trigger hands the function up to ten messages at once. If the handler throws on the ninth, Lambda retries the whole batch, and the first eight are processed twice. Return the identifiers of the messages that failed and Lambda retries only those. Enable ReportBatchItemFailures on the event source mapping, then change the handler's return type.

src/main/java/dev/javahacks/OrderEventHandler.javajava
@Introspected
public class OrderEventHandler extends MicronautRequestHandler<SQSEvent, SQSBatchResponse> {

    @Inject OrderProcessor processor;

    @Override
    public SQSBatchResponse execute(SQSEvent event) {
        var failures = new ArrayList<SQSBatchResponse.BatchItemFailure>();
        for (SQSEvent.SQSMessage record : event.getRecords()) {
            try {
                processor.process(record.getBody());
            } catch (RuntimeException e) {
                failures.add(new SQSBatchResponse.BatchItemFailure(record.getMessageId()));
            }
        }
        return new SQSBatchResponse(failures);
    }
}
YAML
Events:
  Orders:
    Type: SQS
    Properties:
      Queue: !GetAtt OrdersQueue.Arn
      BatchSize: 10
      FunctionResponseTypes: [ReportBatchItemFailures]

An empty failure list tells Lambda the whole batch succeeded. Because a retried message can arrive twice, OrderProcessor.process must be idempotent, for instance by recording the message id in a table with a unique constraint before doing the work.

Configure it from the environment, not the jar

Rebuilding to change a database URL defeats the point of an artifact that is promoted from staging to production. Micronaut reads environment variables and maps them onto properties, so DATASOURCES_DEFAULT_URL overrides datasources.default.url. Set MICRONAUT_ENVIRONMENTS=prod to select application-prod.yml, and keep secrets in AWS Secrets Manager or Parameter Store with the Micronaut AWS distributed configuration module, so a credential never sits in the function's console view.

YAML
Environment:
  Variables:
    MICRONAUT_ENVIRONMENTS: prod
    DATASOURCES_DEFAULT_URL: jdbc:postgresql://orders-db.internal:5432/orders

Measure the cold start you actually have

Cold start numbers quoted for a framework tell you little, because yours depends on your dependencies, your memory setting and your init work. Lambda writes the measurement into every REPORT log line: Init Duration is the cold start, Duration is the handler, and a SnapStart function shows Restore Duration instead. CloudWatch Logs Insights aggregates them across invocations.

Text
filter @type = "REPORT"
| stats count() as invocations,
        avg(@initDuration) as avgInit,
        pct(@initDuration, 95) as p95Init,
        max(@initDuration) as maxInit
  by bin(1h)

Run the query once for the plain Java 21 build, once for SnapStart and once for native, at the same memory size, and choose with your own p95. The difference between runtimes is real, but a function that opens three SDK clients in its constructor can spend more time there than in the framework. Move expensive clients behind a lazy Provider if the common path does not need them.

Two other checks pay for themselves. Look at the package size: a jar over about 50 MB usually carries dependencies the function never calls. And look at Max Memory Used in the same report. If it sits at a fifth of the allocation, test a lower setting; if the cold start improves when memory rises, you were CPU bound during init, which is common for a JVM.

Pick the front door: function URL, HTTP API or REST API

An API-shaped Micronaut function can sit behind three different entry points, and the choice changes the event class your handler receives. A function URL is the cheapest: one HTTPS endpoint attached to the function, no gateway, and no per-request gateway charge. An API Gateway HTTP API adds routing, JWT authorizers, throttling and custom domains. The older REST API adds API keys, usage plans and request validation. Pick the smallest one that covers your requirements, because every extra layer adds a few milliseconds and a bill line.

The handler class in the template depends on the payload format. APIGatewayV2HTTPEventFunction handles HTTP API and function URL events, which use payload format 2.0. MicronautLambdaHandler handles the REST API shape, payload format 1.0. Deploying the wrong class returns a 502 with a Malformed Lambda proxy response message, and the logs show a deserialization error rather than your controller.

YAML
OrdersFunction:
  Type: AWS::Serverless::Function
  Properties:
    FunctionUrlConfig:
      AuthType: AWS_IAM

Use AWS_IAM for service-to-service calls and put a JWT authorizer on the HTTP API for browser clients. Do not ship AuthType: NONE to production unless the controller authenticates every route itself, since the URL is public the moment it exists.

Where this does not apply

A steady, high-traffic service is cheaper on containers than on Lambda. For long jobs over 15 minutes, use a container or batch. The reference is Micronaut AWS, and the Lambda developer guide covers the platform.

Also inDevOps
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.