AWS Tutorials

AWS Lambda With Spring Boot: A Step-by-Step Tutorial

Build and deploy a Spring Boot function on AWS Lambda with Java 21 and AWS SAM, then test it, read its logs, and learn when SnapStart helps cold starts.

On this page
  1. What this tutorial builds
  2. Two ways to run Spring Boot on Lambda
  3. Before you start
  4. Step 1: Create the project
  5. Step 2: Write the function
  6. Step 3: Package it for Lambda
  7. Step 4: Describe the function in a SAM template
  8. Step 5: Build and test locally
  9. Step 6: Deploy
  10. Step 7: Invoke the function
  11. Cold starts and SnapStart
  12. Memory, timeout and cost
  13. Troubleshooting
  14. Clean up
  15. Next steps

What this tutorial builds

You will create a Spring Boot function that takes a name and returns a greeting. You will package it so Lambda can run it, describe it in an AWS SAM template, test it locally and deploy it.

Lambda runs your code only when it is invoked, so you pay for requests and the time your code runs rather than for a server that sits idle. Light testing usually costs little, and Lambda’s free tier includes a monthly allowance. Check your account’s plan before you start.

Two ways to run Spring Boot on Lambda

There are two common approaches:

  • Spring Cloud Function adapter. You write one or more java.util.function.Function beans. The adapter’s FunctionInvoker class receives Lambda events and passes them to your function. This tutorial uses this approach because it is the smallest setup.
  • AWS Serverless Java Container. This runs a full Spring MVC application behind an API Gateway proxy. It suits an existing web application that already has controllers and routes.

Pick the adapter for new, event-driven functions. Pick the container approach if you are moving an existing Spring MVC app with many routes.

Before you start

  • An AWS account and an IAM user with permission to deploy CloudFormation, Lambda and IAM roles.
  • JDK 21 and Maven on your computer.
  • The AWS CLI (version 2) and the AWS SAM CLI.
  • Docker, if you want to run sam local invoke on your machine.

Step 1: Create the project

Create a Maven project at start.spring.io with Java 21 and a Spring Boot 3.x version. You do not need extra starter dependencies. Then add the Spring Cloud Function AWS adapter to pom.xml and import the Spring Cloud BOM, so the adapter version matches the rest of the stack:

<dependencyManagement>
  <dependencies>
    <dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-dependencies</artifactId>
      <version>${spring-cloud.version}</version>
      <type>pom</type>
      <scope>import</scope>
    </dependency>
  </dependencies>
</dependencyManagement>

<dependencies>
  <dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-function-adapter-aws</artifactId>
  </dependency>
</dependencies>

Set spring-cloud.version in <properties> to the release train that matches your Spring Boot version. The Spring Cloud project publishes a compatibility table for this.

Step 2: Write the function

Create one function bean. Spring Cloud Function calls it with the input from the event. The class needs the usual Spring and java.util.function imports: SpringApplication, SpringBootApplication, Bean and Function.

@SpringBootApplication
public class GreetingApplication {

    public static void main(String[] args) {
        SpringApplication.run(GreetingApplication.class, args);
    }

    @Bean
    public Function<String, String> greet() {
        return name -> "Hello, " + name + "!";
    }
}

In src/main/resources/application.properties, name the function and turn off the embedded web server, because Lambda sends events rather than HTTP connections to a port:

spring.cloud.function.definition=greet
spring.main.web-application-type=none

Step 3: Package it for Lambda

Lambda cannot load a standard Spring Boot “fat” jar. That jar keeps its dependencies in a BOOT-INF/ folder and loads them with Spring Boot’s own launcher. Lambda starts your handler directly and does not use that launcher, so the classes under BOOT-INF/ are not found. You need a jar with all dependencies at the top level.

Add the Maven Shade plugin with a separate classifier, so Maven produces a second jar for Lambda:

<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-shade-plugin</artifactId>
  <configuration>
    <createDependencyReducedPom>false</createDependencyReducedPom>
    <shadedArtifactAttached>true</shadedArtifactAttached>
    <shadedClassifierName>aws</shadedClassifierName>
    <transformers>
      <transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer"/>
    </transformers>
  </configuration>
  <executions>
    <execution>
      <phase>package</phase>
      <goals>
        <goal>shade</goal>
      </goals>
    </execution>
  </executions>
</plugin>

Build the project:

./mvnw clean package
ls target/*-aws.jar

The file ending in -aws.jar is the one you deploy.

Step 4: Describe the function in a SAM template

Create template.yaml in the project root:

AWSTemplateFormatVersion: "2010-09-09"
Transform: AWS::Serverless-2016-10-31
Description: Spring Boot greeting function

Resources:
  GreetFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: target/greeting-0.0.1-SNAPSHOT-aws.jar
      Handler: org.springframework.cloud.function.adapter.aws.FunctionInvoker::handleRequest
      Runtime: java21
      MemorySize: 1024
      Timeout: 30
      Environment:
        Variables:
          SPRING_CLOUD_FUNCTION_DEFINITION: greet

Replace the jar name with the file you found in step 3. The handler is the adapter’s FunctionInvoker::handleRequest. The memory setting matters for Java, as explained below.

Step 5: Build and test locally

Save a test event in a file named event.json. The function takes a String, so the event is a JSON string:

"World"

Run the function locally. This needs Docker:

sam local invoke GreetFunction -e event.json

You should see "Hello, World!" in the output.

Step 6: Deploy

Run the guided deployment, which asks for a stack name, a Region and whether to save your answers:

sam deploy --guided

SAM creates a CloudFormation stack with the function and its execution role. When the deployment finishes, the output shows the function name.

Step 7: Invoke the function

Call the deployed function with the AWS CLI. Replace the function name with the one from the deployment output:

aws lambda invoke \
  --function-name <function-name> \
  --payload '"World"' \
  --cli-binary-format raw-in-base64-out \
  response.json
cat response.json

The output should be "Hello, World!". To expose the function over HTTP, add an HTTP API event to the template, and then test it with curl.

Cold starts and SnapStart

A cold start happens when Lambda creates a new execution environment. For Java, this includes starting the JVM and the Spring context, which can take several seconds. Lambda gives on-demand functions 10 seconds for initialization, so keep the Spring context small and avoid heavy work at startup.

SnapStart reduces this cost. Lambda takes a snapshot of the initialized environment and restores it for new instances. To use it:

  • Turn on SnapStart for the function, and publish a version.
  • Invoke the function through an alias that points at a published version, not $LATEST.
  • Refresh state that should not be reused after a restore, such as connections or random number seeds.
  • Do not combine SnapStart with provisioned concurrency.

Memory, timeout and cost

  • Memory: Lambda allocates CPU in proportion to memory. A Spring Boot function usually needs at least 1,024 MB. Test with a few values and pick the one that gives acceptable startup and duration.
  • Timeout: the default is 3 seconds, which is too short for a Spring Boot cold start. This tutorial uses 30 seconds. The maximum is 15 minutes.
  • Cost: you pay per request and per GB-second of execution. AWS’s free tier includes a monthly allowance of both, but check the current amounts on the Lambda pricing page.

Troubleshooting

  • ClassNotFoundException or “handler not found.” Check that the handler string is exactly org.springframework.cloud.function.adapter.aws.FunctionInvoker::handleRequest and that CodeUri points at the -aws.jar, not the plain jar.
  • Function fails with a Jackson or JSON error. The event does not match the function’s input type. Check the test event format.
  • The function times out during startup. Increase memory, enable SnapStart, or reduce the number of Spring beans loaded at startup.
  • Logs are missing. Check the function’s CloudWatch log group, which is named /aws/lambda/<function-name>.

Clean up

Delete the stack to remove the function and its role:

sam delete --stack-name <stack-name>

Then check CloudWatch for the log group, which Lambda keeps until you delete it. Set a retention period or delete it so logs do not keep accumulating.

Next steps

The complete guide to aws tutorials

AWS Fundamentals: The Core Cloud Computing Services
Read the guide

Keep exploring

Guides from other topics

All topics →