Skip to content

Spring Boot on AWS Lambda: From Traditional to Serverless

sankeerthbakki edited this page Mar 22, 2025 · 4 revisions

Architecture Comparison

Traditional Spring Boot Deployment

graph LR
    Client -->|HTTP Request| Tomcat
    Tomcat -->|Route Request| DispatcherServlet
    DispatcherServlet -->|Map to Controller| RestController
    RestController -->|Call Business Logic| Service
    Service -->|Read/Write Data| Database
Loading

Step-by-Step Flow:

  1. Client sends HTTP request: The client (e.g., browser, mobile app) sends a request to the Spring Boot application.
  2. Tomcat receives request: The embedded Tomcat server listens for incoming requests.
  3. DispatcherServlet routes request: Spring’s DispatcherServlet maps the request to the appropriate @RestController based on the URL.
  4. Controller processes request: The @RestController handles the request, extracts data, and calls the @Service layer.
  5. Service executes business logic: The @Service layer contains the core logic (e.g., database operations, validations).
  6. Response flows back: The response is returned to the client through the same chain.

Key Characteristics:

  • Runs 24/7 on Tomcat.
  • Uses @RestController for endpoint mapping.
  • Scales manually (e.g., Kubernetes clusters).

AWS Lambda Deployment

graph LR
    Client -->|HTTP Request| APIGateway
    APIGateway -->|Trigger| Lambda
    Lambda -->|Parse Event| Handler
    Handler -->|Call Business Logic| Service
    Service -->|Read/Write Data| Database
Loading

Step-by-Step Flow:

  1. Client sends HTTP request: The client sends a request to the API Gateway.
  2. API Gateway triggers Lambda: API Gateway validates the request and invokes the Lambda function.
  3. Lambda Handler processes event: The CreateRequestHandler class (Entry point: Implements RequestHandler<Input, Output>) parses the APIGatewayProxyRequestEvent (contains headers, body, path parameters).
  4. Handler calls business logic: The handler invokes the appropriate @Service method.
  5. Service executes business logic: The @Service layer performs the required operations (e.g., database queries).
  6. Handler formats response: The handler creates an APIGatewayProxyResponseEvent and returns it to API Gateway.
  7. API Gateway sends response: The response is sent back to the client.

Key Characteristics:

  • No persistent server – Lambda runs on-demand.
  • Handler class replaces @RestController for request processing.
  • Auto-scales with zero configuration.

Core Components in AWS Lambda

1. Lambda Handler (CreateRequestHandler)

The entry point for AWS Lambda.

public class CreateRequestHandler implements 
    RequestHandler<APIGatewayProxyRequestEvent, APIGatewayProxyResponseEvent> {
    
    // Spring context initialized once per Lambda instance
    private static final ApplicationContext context = SpringContext.getContext();
    private static final RequestService service = context.getBean(RequestService.class);
    
    @Override
    public APIGatewayProxyResponseEvent handleRequest(
        APIGatewayProxyRequestEvent event,  // Contains request data
        Context context                      // Lambda execution context
    ) {
        // Step 1: Parse event
        String requesterId = event.getPathParameters().get("requesterId");
        RequestDTO dto = parseBody(event.getBody());
        
        // Step 2: Call Spring-managed service
        SaayamResponse<Request> response = service.createRequest(requesterId, dto);
        
        // Step 3: Format response for API Gateway
        return new APIGatewayProxyResponseEvent()
            .withStatusCode(201)
            .withBody(toJson(response));
    }
}

2. Event Objects

  • APIGatewayProxyRequestEvent: Contains HTTP request details:
    event.getBody();          // Request payload (JSON/XML)
    event.getHeaders();       // Headers (e.g., Authorization)
    event.getPathParameters();// URL path parameters
    event.getHttpMethod();    // GET, POST, etc.
  • APIGatewayProxyResponseEvent: Structures the HTTP response.

Setup Steps

Step 1: Package the Application

mvn clean package

Step 2: Create Lambda Function

  1. Go to AWS Lambda Console:
    • Click "Create Function".
    • Choose "Author from scratch".
    • Set runtime to Java 17 (or your preferred version).
  2. Upload JAR/ZIP:
    • Upload the packaged JAR/ZIP file.
    • Set the handler class: com.example.CreateRequestHandler::handleRequest (or your custom handler class).
  3. Set Environment Variables:
    • Add database details or other configurations.
  4. Configure API Gateway:
    • Link API Gateway routes (e.g., POST /requests) to Lambda.

Differences: Lambda vs Traditional Spring Boot

Aspect AWS Lambda Traditional Spring Boot
Server Management No server (serverless) Requires Tomcat server
Scaling Automatic Manual (e.g., Kubernetes)
Cost Model Pay per request Pay for server uptime
Execution Time Limit 15 minutes max Unlimited
Cold Starts Yes (100ms–several seconds latency) No

Clone this wiki locally