Spring on AWS Lambda
AWS Lambda runs a function when an event arrives and charges only for the time it runs, but every new execution environment starts a fresh JVM first. Spring Cloud Function lets ordinary Function beans become Lambda handlers, and the real engineering problem is the cold start. This page shows how the adapter finds and calls your function, measures what Spring adds to start-up, and covers packaging, events and SnapStart.
Contents
How Lambda runs Java code
AWS Lambda runs code in response to events: an HTTP request through API Gateway, a message from SQS, a file in S3, a change in a DynamoDB table. There is no server to manage. Lambda creates an execution environment, a small micro-VM with the Java runtime, loads the code, and calls a handler method with the event. When the handler returns, the environment is frozen and kept for a while, and the next event may be handled by the same environment, already warm.
That lifecycle has two phases, and their costs differ:
- Init: the first event in a new environment pays for starting the JVM, loading classes and running static initialisers and constructors. This is the cold start. For a Spring application, it includes building the whole application context.
- Invoke: every event, including the first, runs the handler. In a warm environment only this phase runs, and it is as fast as the code itself.
Lambda scales by creating more environments, one per concurrent event, so a burst of traffic causes a burst of cold starts. Each environment handles one event at a time. Its memory setting, from 128 MB to 10,240 MB, also sets its CPU share, which is why a Java function often starts faster with more memory.
Spring code reaches Lambda in one of three ways:
| Approach | What the handler is | Best for |
|---|---|---|
| Spring Cloud Function with the AWS adapter | FunctionInvokerFunction | Event handlers: SQS, S3, scheduled jobs, single API operations |
| AWS Serverless Java Container | A proxy that turns API Gateway events into servlet requests | Moving an existing Spring MVC application to Lambda unchanged |
| Plain handler without Spring | A class implementing RequestHandler | Tiny functions where start-up time matters most |
This page uses Spring Cloud Function 5.0, the line for Spring Boot 4. Neither its AWS adapter nor Lambda itself is available where this page was built, so the adapter, packaging and event examples are marked as not run; they were checked against the Spring Cloud Function 5.0 reference documentation. The two programs shown running use Spring Framework and Spring Boot only, to show the function lookup and to measure start-up.
Business logic as function beans
Spring Cloud Function's idea is that business code is a plain java.util.function.FunctionConsumerSuppliervalidate|price
package demo.lambda.functions;
import java.math.BigDecimal;
import java.util.function.Function;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.ResolvableType;
public class FunctionLookup {
record OrderRequest(String sku, int quantity) {
}
record PricedOrder(String sku, int quantity, BigDecimal total) {
}
// the business code: plain java.util.function beans, no AWS types anywhere
@Configuration
static class Functions {
@Bean
Function<OrderRequest, OrderRequest> validate() {
return order -> {
if (order.quantity() <= 0) {
throw new IllegalArgumentException("quantity must be positive");
}
return order;
};
}
@Bean
Function<OrderRequest, PricedOrder> price() {
return order -> new PricedOrder(order.sku(), order.quantity(),
new BigDecimal("12.50").multiply(BigDecimal.valueOf(order.quantity())));
}
}
// roughly what Spring Cloud Function does for a definition such as "validate|price"
@SuppressWarnings("unchecked")
static Function<Object, Object> lookup(AnnotationConfigApplicationContext ctx, String def) {
Function<Object, Object> result = Function.identity();
for (String name : def.split("\\|")) {
result = result.andThen((Function<Object, Object>) ctx.getBean(name, Function.class));
}
return result;
}
public static void main(String[] args) {
try (var context = new AnnotationConfigApplicationContext(Functions.class)) {
for (String name : context.getBeanNamesForType(Function.class)) {
ResolvableType type = context.getBeanFactory().getMergedBeanDefinition(name)
.getResolvableType().as(Function.class);
System.out.println("function bean '" + name + "': "
+ type.getGeneric(0).toClass().getSimpleName() + " -> "
+ type.getGeneric(1).toClass().getSimpleName());
}
Function<Object, Object> handler = lookup(context, "validate|price");
System.out.println("validate|price(book x 3) = "
+ handler.apply(new OrderRequest("book", 3)));
try {
handler.apply(new OrderRequest("book", 0));
} catch (IllegalArgumentException e) {
System.out.println("validate|price(book x 0) failed: " + e.getMessage());
}
}
}
}
function bean 'validate': OrderRequest -> OrderRequest
function bean 'price': OrderRequest -> PricedOrder
validate|price(book x 3) = PricedOrder[sku=book, quantity=3, total=37.50]
validate|price(book x 0) failed: quantity must be positive
- The context held two function beans, and their generic types were readable from the bean definitions:
andOrderRequest -> OrderRequest . Spring Cloud Function uses those types to decide what to convert the incoming JSON into.OrderRequest -> PricedOrder - The definition
composed the two withvalidate|price , so one call validated the order and then priced it: 3 × 12.50 = 37.50.andThen - With a quantity of 0,
threw, andvalidate never ran. In Lambda, an exception from the handler fails the invocation, and the event source decides what happens next: API Gateway returns an error, and SQS makes the message visible again for a retry.price
Because the functions are ordinary beans, they are tested like any other bean, with no Lambda involved, and the same code can run behind an HTTP endpoint with spring-cloud-function-webFunctionCatalogMessage
The AWS adapter and the handler (not run)
The adapter dependency adds FunctionInvoker
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-function-adapter-aws</artifactId>
</dependency>
@SpringBootApplication
public class OrderFunctions {
public static void main(String[] args) {
SpringApplication.run(OrderFunctions.class, args);
}
@Bean
public Function<OrderRequest, PricedOrder> price(PriceList prices) {
return order -> prices.price(order);
}
}
- The Lambda handler is
. On its first call it starts the Spring application, looking up the main class from the jar'sorg.springframework.cloud.function.adapter.aws.FunctionInvoker::handleRequest manifest entry, or from theStart-Class environment variable.MAIN_CLASS - With one function bean, that bean is used. With several, set the
environment variable, for example tospring_cloud_function_definition orprice . Lambda does not allow dots or hyphens in environment variable names, hence the underscores.validate|price - Without a definition and with several beans, the framework searches for a
, then aFunction , then aConsumer , and otherwise falls back to its routing function.Supplier
Lambda needs a single jar with all dependencies. The Spring Cloud Function documentation uses the Maven Shade plugin with the classifier awsorder-functions-1.0.0-aws.jar
Resources:
PriceFunction:
Type: AWS::Serverless::Function
Properties:
Runtime: java21
Handler: org.springframework.cloud.function.adapter.aws.FunctionInvoker::handleRequest
CodeUri: target/order-functions-1.0.0-aws.jar
MemorySize: 1024
Timeout: 15
Environment:
Variables:
spring_cloud_function_definition: price
SnapStart:
ApplyOn: PublishedVersions
Event types (not run)
The input of the function decides what the adapter gives it. For a business type, the event's JSON body is converted to it. To see the whole event, use the AWS event classes from aws-lambda-java-eventsMessage
// API Gateway: full control over status code and headers
@Bean
public Function<APIGatewayProxyRequestEvent, APIGatewayProxyResponseEvent> getOrder(
OrderStore store) {
return request -> {
String id = request.getPathParameters().get("id");
return store.find(id)
.map(order -> new APIGatewayProxyResponseEvent()
.withStatusCode(200).withBody(order.toJson()))
.orElseGet(() -> new APIGatewayProxyResponseEvent().withStatusCode(404));
};
}
// SQS: one invocation receives a batch of up to 10 messages by default
@Bean
public Consumer<SQSEvent> fulfil(Fulfilment fulfilment) {
return event -> event.getRecords()
.forEach(record -> fulfilment.start(record.getMessageId(), record.getBody()));
}
- For an SQS trigger, Lambda polls the queue and calls the function with a batch. If the function throws, the whole batch returns to the queue and is retried, including the messages that succeeded, so the consumer must be idempotent, as the
SQS page shows. Returning an with the failed message IDs, withSQSBatchResponse enabled on the trigger, retries only those.ReportBatchItemFailures - For API Gateway, a function from a business type to a business type also works: the adapter takes the body as input and returns the result as a 200 response. Use the event classes when the status code or headers matter.
What Spring adds to a cold start
Every cold start runs the init phase, so the cost of building the Spring context is paid by every new environment. This program measures it the way Lambda experiences it: each variant runs in a fresh JVM that initialises, handles one event and exits, three times, keeping the best run:
package demo.lambda.coldstart;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
public class ColdStart {
@Configuration
static class Functions {
@Bean
Function<String, String> uppercase() {
return String::toUpperCase;
}
}
@SpringBootApplication
static class BootFunctions {
}
// one cold start: a fresh JVM that initialises, handles one event and exits
static void child(String variant) {
Function<String, String> handler = switch (variant) {
case "plain-java" -> String::toUpperCase;
case "spring-context" -> {
var context = new AnnotationConfigApplicationContext(Functions.class);
@SuppressWarnings("unchecked")
Function<String, String> f = context.getBean("uppercase", Function.class);
yield f;
}
default -> {
List<String> args = new ArrayList<>(List.of("--spring.main.banner-mode=off",
"--logging.level.root=WARN", "--spring.main.web-application-type=none"));
if (variant.equals("boot-lazy")) {
args.add("--spring.main.lazy-initialization=true");
}
var context = SpringApplication.run(BootFunctions.class,
args.toArray(String[]::new));
@SuppressWarnings("unchecked")
Function<String, String> f = context.getBean("uppercase", Function.class);
yield f;
}
};
handler.apply("event");
}
static long bestOfThree(String variant) throws Exception {
String java = Path.of(System.getProperty("java.home"), "bin", "java").toString();
long best = Long.MAX_VALUE;
for (int i = 0; i < 3; i++) {
long start = System.nanoTime();
Process p = new ProcessBuilder(java, "-Xshare:auto", "-cp",
System.getProperty("java.class.path"), ColdStart.class.getName(), variant)
.inheritIO().start();
if (p.waitFor() != 0) {
throw new IllegalStateException(variant + " failed");
}
best = Math.min(best, (System.nanoTime() - start) / 1000000);
}
return best;
}
public static void main(String[] args) throws Exception {
if (args.length == 1) {
child(args[0]);
return;
}
long base = bestOfThree("plain-java");
System.out.println("Rough comparison, best of 3 fresh JVMs each, "
+ Runtime.getRuntime().availableProcessors() + " CPUs:");
for (String variant : List.of("plain-java", "spring-context", "boot", "boot-lazy")) {
long ms = variant.equals("plain-java") ? base : bestOfThree(variant);
System.out.printf(" %-15s %5d ms (%.1fx plain Java)%n", variant, ms,
(double) ms / base);
}
}
}
Rough comparison, best of 3 fresh JVMs each, 2 CPUs:
plain-java 62 ms (1.0x plain Java)
spring-context 1239 ms (20.0x plain Java)
boot 1620 ms (26.1x plain Java)
boot-lazy 1481 ms (23.9x plain Java)
This is a rough comparison on a shared 2-CPU machine that was busy with other work while it ran, so the exact numbers vary from run to run; the order between them did not.
- Plain Java, a JVM that loads one class and calls one function, was by far the fastest. That is the floor for any Java function.
- A Spring Framework context with one function bean was many times slower than plain Java. Most of that is class loading: the context infrastructure loads thousands of classes before the first bean exists.
- Spring Boot was slower again, because it also reads configuration files, sets up logging and evaluates every auto-configuration on the classpath.
- Lazy initialisation, with
, made no consistent difference here: in repeated runs it came out sometimes ahead of the normal Boot start and sometimes behind. With one bean there is almost nothing to defer, so the run-to-run noise was larger than the gain. It pays off in applications with many beans that a given function does not use.spring.main.lazy-initialization=true
Measured in a real Lambda environment, the absolute numbers differ, and they depend strongly on the memory setting, since more memory brings more CPU. The proportions are what matter: the framework, not the business code, dominates a Java cold start.
Making cold starts acceptable
- SnapStart: with
enabled on published versions, Lambda runs the init phase once when the version is published, snapshots the memory of the initialised environment, and restores new environments from that snapshot. The Spring context is already built, so a cold start becomes a restore. Code that must run again after a restore, such as reopening connections or reseeding random state, uses the CRaC runtime hooks; Spring Framework's CRaC support, covered on theSnapStartSpring CRaC page, stops and restarts lifecycle beans around the checkpoint. - Fewer beans and auto-configurations: every starter on the classpath is evaluated at start-up. Keep the function's dependencies to what it uses, and exclude auto-configurations it does not need.
- Lazy initialisation: beans the function does not use on a given path are never created. As the measurement shows, it helps little in a tiny application, so measure it with your own beans.
- Memory: a function with 1,024 MB or more gets more CPU during init, which shortens class loading and JIT work. Measure the cost per invocation before choosing the smallest size.
- Native images: a GraalVM native image of the Spring Boot application starts in milliseconds, at the cost of a long build and a custom runtime. The
Spring native page explains the trade-offs. - Provisioned concurrency: Lambda keeps a set number of environments initialised at all times, for a fixed price. It removes cold starts for that much traffic, but it is paid for whether used or not.
Writing code for the Lambda lifecycle
- Create clients once: AWS SDK clients, HTTP clients and connection pools belong in beans, created during init and reused by every warm invocation. Creating them inside the function repeats the cost on every event.
- No background work: after the handler returns, the environment is frozen. Threads started by
or@Async do not run between events, and work left on them may never finish. Finish everything before returning.@Scheduled - Database connections: hundreds of environments, each with a connection pool, can exhaust a relational database. Use a pool size of 1 or 2 per environment, and RDS Proxy in front of the database.
- Timeouts: the function's timeout, at most 15 minutes, covers init on a cold start too. Keep it well above the cold start time, or the first request after a deployment fails.
- Logging: write logs to standard output, which Lambda sends to CloudWatch Logs; Spring Boot's console logging works as it is. Structured JSON logs make them searchable.
Choosing how to run Spring on Lambda
| Situation | Choice |
|---|---|
| Event processing from SQS, S3, EventBridge or schedules | Spring Cloud Function with FunctionInvoker |
| A few HTTP operations | Spring Cloud Function with API Gateway event types |
| An existing Spring MVC application | AWS Serverless Java Container, or a container service instead of Lambda |
| Cold starts must be short, Java runtime | SnapStart and fewer dependencies, then lazy initialisation if it measurably helps |
| Cold starts must be minimal | GraalVM native image on a custom runtime, or a plain handler |
| Steady traffic all day | A long-running service on ECS, EKS or EC2 is usually cheaper and simpler |
Lambda suits spiky, event-driven work, and Spring Cloud Function keeps that work as plain functions that can also run elsewhere. Measure the cold start of your own function with its real dependencies before committing to it, and enable SnapStart from the start. For queue processing on Lambda, combine this page with the