Skip to content
Tutorials Center
My learning

Topics

Lesson 30 of 38 ยท Cloud and Serverless

AWS Lambda and Serverless Functions

Build serverless functions with Micronaut: MicronautRequestHandler, API Gateway proxy controllers, cold starts, GraalVM native Lambdas and a runnable handler stand-in.

Serverless platforms run your code only when a request arrives and charge per execution. You deploy a function, the platform starts it on demand and scales it from zero to thousands of copies. The catch is the cold start: the first request to a new copy pays for starting the runtime, loading classes and creating the application context.

Micronaut was designed with this in mind: no runtime reflection or classpath scanning, so startup is quick, and it supports GraalVM native images for near-instant starts. This lesson covers AWS Lambda; Google Cloud Functions and Azure Functions work in a similar way. The real AWS integration cannot run on this site, so its code is read-only. The runnable examples simulate the handler lifecycle and the cost of a cold start.

Two ways to write a Lambda

1. A function handler

A function takes an input and returns an output. The Micronaut handler class extends MicronautRequestHandler, and your logic lives in beans:

GROOVY
implementation("io.micronaut.aws:micronaut-function-aws")
Java
import io.micronaut.function.aws.MicronautRequestHandler;
import jakarta.inject.Inject;

public class GreetingHandler extends MicronautRequestHandler<GreetingRequest, GreetingResponse> {

    @Inject
    GreetingService service;          // an ordinary Micronaut bean

    @Override
    public GreetingResponse execute(GreetingRequest request) {
        return new GreetingResponse(service.greet(request.name()));
    }
}

In the AWS console you set the handler to com.example.GreetingHandler. Dependency injection works because the handler builds an ApplicationContext once, when the Lambda container starts, and reuses it for later invocations.

2. A whole web application behind API Gateway

Often you simply want to run your normal controllers on Lambda. With the API Gateway proxy support, the same controllers serve both a local server and Lambda:

GROOVY
implementation("io.micronaut.aws:micronaut-function-aws-api-proxy")
Java
@Controller("/notes")
class NoteController {
    @Get("/{id}")
    Note find(long id) { /* ... */ }
}

The handler class is io.micronaut.function.aws.proxy.payload2.APIGatewayV2HTTPEventFunction (for HTTP APIs), and API Gateway forwards every request to it, which translates the event into a Micronaut request. The advantage is you can develop and test locally with a normal HTTP server; the cost is that a whole app starts on a cold start, so keep the number of beans small.

Cold start vs warm

Cold start Start runtime, load classes, build context.
Warm invoke Context already built. Just run the handler.

Only the first request in a new container pays for startup.

1 / 2

Keeping cold starts short

  • Do work once, outside the handler. Anything created in a field or the context (database pools, HTTP clients, parsed configuration) is reused across warm invocations.
  • Keep the jar small. Remove unused dependencies; Micronaut's modular design makes this easy.
  • Use AWS SnapStart for Java runtimes, which restores a pre-initialized snapshot instead of starting from scratch. Micronaut includes Crac support for it.
  • Compile to a native image with GraalVM and deploy on the provided.al2023 custom runtime for the fastest starts; see GraalVM Native Image Basics.
  • Avoid reflection-heavy libraries, which add time and break native builds.

Try it: lifecycle of a Lambda container

This stand-in models the two phases: init runs once per container, handle runs per request. The sleeps are replaced by counters so the output is deterministic.

Java Cold start vs warm invoke

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Try it: an API Gateway style event handler

The API Gateway proxy turns a JSON event into a routed controller call. This stand-in does the routing step so that you can see how one function can serve several endpoints.

Java Routing a gateway event

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Practical considerations

  • Statelessness: a container may be reused or thrown away at any time. Keep state in a database, DynamoDB, S3 or a cache, never in fields you rely on across requests.
  • Timeouts and memory: Lambda has a maximum run time, and its CPU share grows with the memory you choose. More memory often lowers total cost because the function finishes sooner.
  • Connections: many concurrent containers can overwhelm a relational database. Use a connection proxy or a data store designed for it.
  • Observability: structured logs to CloudWatch, plus metrics and traces as in Metrics, Health and Tracing.
  • Secrets: pull from AWS Secrets Manager or Parameter Store using distributed configuration (see Service Discovery and Distributed Configuration).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is a cold start?

    Only the first invocation in a fresh container pays for initialization; later warm invocations reuse it.
  2. 2. Where should expensive objects such as HTTP clients be created?

    Creating them once per container saves time on every warm call.
  3. 3. Which is a benefit of Micronaut for serverless?

    Compile-time processing gives quick starts and small memory use.
  4. 4. What does the API Gateway proxy module let you do?

    It translates gateway events into Micronaut requests so controllers work unchanged.

Summary

  • Micronaut supports function handlers (MicronautRequestHandler) and whole controllers behind API Gateway.
  • The application context is built once per container; keep initialization small and reuse resources.
  • SnapStart and GraalVM native images reduce cold-start time.
  • Serverless code must be stateless and respect timeouts and connection limits.

Next: Metrics, Health and Tracing