aws-sdk-java-v2-lambda · diff
git:20260316.91dc3c4 to git:20260323.300f036
122 added, 446 removed. Audit A to A.
---
name: aws-sdk-java-v2-lambda
description: Provides AWS Lambda patterns using AWS SDK for Java 2.x. Use when invoking Lambda functions, creating/updating functions, managing function configurations, working with Lambda layers, or integrating Lambda with Spring Boot applications.
allowed-tools: Read, Write, Edit, Bash, Glob, Grep
---
# AWS SDK for Java 2.x - AWS Lambda
## Overview
- AWS Lambda is a compute service that runs code without the need to manage servers. Your code runs automatically, scaling up and down with pay-per-use pricing. Use this skill to implement AWS Lambda operations using AWS SDK for Java 2.x in applications and services.
+ AWS Lambda is a compute service that runs code without managing servers. Use this skill to implement AWS Lambda operations using AWS SDK for Java 2.x in applications and services.
## When to Use
- Use this skill when:
- Invoking Lambda functions programmatically
- Creating or updating Lambda functions
- Managing Lambda function configurations
- Working with Lambda environment variables
- Managing Lambda layers and aliases
- Implementing asynchronous Lambda invocations
- Integrating Lambda with Spring Boot
- ## Instructions
+ ## Quick Reference
- Follow these steps to work with AWS Lambda:
+ | Operation | SDK Method | Use Case |
+ |-----------|------------|----------|
+ | **Invoke** | `invoke()` | Synchronous/async function invocation |
+ | **List Functions** | `listFunctions()` | Get all Lambda functions |
+ | **Get Config** | `getFunction()` | Retrieve function configuration |
+ | **Create Function** | `createFunction()` | Create new Lambda function |
+ | **Update Code** | `updateFunctionCode()` | Deploy new function code |
+ | **Update Config** | `updateFunctionConfiguration()` | Modify settings (timeout, memory, env vars) |
+ | **Delete Function** | `deleteFunction()` | Remove Lambda function |
- 1. **Add Dependencies** - Include Lambda SDK dependency
- 2. **Create Client** - Instantiate LambdaClient with proper configuration
- 3. **Invoke Functions** - Use invoke() with appropriate invocation type
- 4. **Handle Responses** - Parse response payloads and handle function errors
- 5. **Manage Functions** - Create, update, or delete Lambda functions
- 6. **Configure Environment** - Set environment variables and concurrency limits
- 7. **Integrate with Spring** - Configure Lambda beans and services
- 8. **Test Locally** - Use mocks or LocalStack for development testing
+ ## Instructions
- ## Dependencies
+ ### 1. Add Dependencies
+ Include Lambda SDK dependency in `pom.xml`:
+
```xml
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>lambda</artifactId>
</dependency>
```
- ## Client Setup
-
- To use AWS Lambda, create a LambdaClient with the required region configuration:
-
- ```java
- import software.amazon.awssdk.regions.Region;
- import software.amazon.awssdk.services.lambda.LambdaClient;
+ See [client-setup.md](references/client-setup.md) for complete setup.
- LambdaClient lambdaClient = LambdaClient.builder()
- .region(Region.US_EAST_1)
- .build();
- ```
+ ### 2. Create Client
- For asynchronous operations, use LambdaAsyncClient:
+ Instantiate `LambdaClient` with proper configuration:
```java
- import software.amazon.awssdk.services.lambda.LambdaAsyncClient;
-
- LambdaAsyncClient asyncLambdaClient = LambdaAsyncClient.builder()
+ LambdaClient lambdaClient = LambdaClient.builder()
.region(Region.US_EAST_1)
.build();
```
- ## Invoke Lambda Function
-
- ### Synchronous Invocation
-
- Invoke Lambda functions synchronously to get immediate results:
-
- ```java
- import software.amazon.awssdk.services.lambda.model.*;
- import software.amazon.awssdk.core.SdkBytes;
-
- public String invokeLambda(LambdaClient lambdaClient,
- String functionName,
- String payload) {
- InvokeRequest request = InvokeRequest.builder()
- .functionName(functionName)
- .payload(SdkBytes.fromUtf8String(payload))
- .build();
-
- InvokeResponse response = lambdaClient.invoke(request);
-
- return response.payload().asUtf8String();
- }
- ```
-
- ### Asynchronous Invocation
-
- Use asynchronous invocation for fire-and-forget scenarios:
-
- ```java
- public void invokeLambdaAsync(LambdaClient lambdaClient,
- String functionName,
- String payload) {
- InvokeRequest request = InvokeRequest.builder()
- .functionName(functionName)
- .invocationType(InvocationType.EVENT) // Asynchronous
- .payload(SdkBytes.fromUtf8String(payload))
- .build();
-
- InvokeResponse response = lambdaClient.invoke(request);
-
- System.out.println("Status: " + response.statusCode());
- }
- ```
-
- ### Invoke with JSON Objects
-
- Work with JSON payloads for complex data structures:
-
- ```java
- import com.fasterxml.jackson.databind.ObjectMapper;
-
- public <T> String invokeLambdaWithObject(LambdaClient lambdaClient,
- String functionName,
- T requestObject) throws Exception {
- ObjectMapper mapper = new ObjectMapper();
- String jsonPayload = mapper.writeValueAsString(requestObject);
-
- InvokeRequest request = InvokeRequest.builder()
- .functionName(functionName)
- .payload(SdkBytes.fromUtf8String(jsonPayload))
- .build();
-
- InvokeResponse response = lambdaClient.invoke(request);
-
- return response.payload().asUtf8String();
- }
- ```
+ For async operations, use `LambdaAsyncClient`.
- ### Parse Typed Responses
+ ### 3. Invoke Lambda Function
- Parse JSON responses into typed objects:
+ Synchronous invocation:
```java
- public <T> T invokeLambdaAndParse(LambdaClient lambdaClient,
- String functionName,
- Object request,
- Class<T> responseType) throws Exception {
- ObjectMapper mapper = new ObjectMapper();
- String jsonPayload = mapper.writeValueAsString(request);
-
- InvokeRequest invokeRequest = InvokeRequest.builder()
- .functionName(functionName)
- .payload(SdkBytes.fromUtf8String(jsonPayload))
- .build();
-
- InvokeResponse response = lambdaClient.invoke(invokeRequest);
+ InvokeRequest request = InvokeRequest.builder()
+ .functionName("my-function")
+ .payload(SdkBytes.fromUtf8String(payload))
+ .build();
- String responseJson = response.payload().asUtf8String();
+ InvokeResponse response = lambdaClient.invoke(request);
- return mapper.readValue(responseJson, responseType);
- }
+ return response.payload().asUtf8String();
```
- ## Function Management
+ See [invocation-patterns.md](references/invocation-patterns.md) for patterns.
- ### List Functions
+ ### 4. Handle Responses
- List all Lambda functions for the current account:
+ Parse response payloads and check for errors:
```java
- public List<FunctionConfiguration> listFunctions(LambdaClient lambdaClient) {
- ListFunctionsResponse response = lambdaClient.listFunctions();
-
- return response.functions();
+ if (response.functionError() != null) {
+ throw new LambdaInvocationException("Lambda error: " + response.functionError());
}
- ```
- ### Get Function Configuration
-
- Retrieve function configuration and metadata:
-
- ```java
- public FunctionConfiguration getFunctionConfig(LambdaClient lambdaClient,
- String functionName) {
- GetFunctionRequest request = GetFunctionRequest.builder()
- .functionName(functionName)
- .build();
-
- GetFunctionResponse response = lambdaClient.getFunction(request);
-
- return response.configuration();
- }
+ String result = response.payload().asUtf8String();
```
- ### Update Function Code
+ ### 5. Manage Functions
- Update Lambda function code with new deployment package:
+ Create, update, or delete Lambda functions:
```java
- import java.nio.file.Files;
- import java.nio.file.Paths;
-
- public void updateFunctionCode(LambdaClient lambdaClient,
- String functionName,
- String zipFilePath) throws IOException {
- byte[] zipBytes = Files.readAllBytes(Paths.get(zipFilePath));
+ // Create
+ CreateFunctionRequest createRequest = CreateFunctionRequest.builder()
+ .functionName("my-function")
+ .runtime(Runtime.JAVA17)
+ .role(roleArn)
+ .code(code)
+ .build();
- UpdateFunctionCodeRequest request = UpdateFunctionCodeRequest.builder()
- .functionName(functionName)
- .zipFile(SdkBytes.fromByteArray(zipBytes))
- .publish(true)
- .build();
+ lambdaClient.createFunction(createRequest);
- UpdateFunctionCodeResponse response = lambdaClient.updateFunctionCode(request);
+ // Update code
+ UpdateFunctionCodeRequest updateCodeRequest = UpdateFunctionCodeRequest.builder()
+ .functionName("my-function")
+ .zipFile(SdkBytes.fromByteArray(zipBytes))
+ .build();
- System.out.println("Updated function version: " + response.version());
- }
+ lambdaClient.updateFunctionCode(updateCodeRequest);
```
- ### Update Function Configuration
-
- Modify function settings like timeout, memory, and environment variables:
-
- ```java
- public void updateFunctionConfiguration(LambdaClient lambdaClient,
- String functionName,
- Map<String, String> environment) {
- Environment env = Environment.builder()
- .variables(environment)
- .build();
-
- UpdateFunctionConfigurationRequest request = UpdateFunctionConfigurationRequest.builder()
- .functionName(functionName)
- .environment(env)
- .timeout(60)
- .memorySize(512)
- .build();
-
- lambdaClient.updateFunctionConfiguration(request);
- }
- ```
+ See [function-management.md](references/function-management.md) for complete patterns.
- ### Create Function
+ ### 6. Configure Environment
- Create new Lambda functions with code and configuration:
+ Set environment variables and concurrency limits:
```java
- public void createFunction(LambdaClient lambdaClient,
- String functionName,
- String roleArn,
- String handler,
- String zipFilePath) throws IOException {
- byte[] zipBytes = Files.readAllBytes(Paths.get(zipFilePath));
-
- FunctionCode code = FunctionCode.builder()
- .zipFile(SdkBytes.fromByteArray(zipBytes))
- .build();
-
- CreateFunctionRequest request = CreateFunctionRequest.builder()
- .functionName(functionName)
- .runtime(Runtime.JAVA17)
- .role(roleArn)
- .handler(handler)
- .code(code)
- .timeout(60)
- .memorySize(512)
- .build();
-
- CreateFunctionResponse response = lambdaClient.createFunction(request);
-
- System.out.println("Function ARN: " + response.functionArn());
- }
- ```
-
- ### Delete Function
-
- Remove Lambda functions when no longer needed:
+ Environment env = Environment.builder()
+ .variables(Map.of(
+ "DB_URL", "jdbc:postgresql://db",
+ "LOG_LEVEL", "INFO"
+ ))
+ .build();
- ```java
- public void deleteFunction(LambdaClient lambdaClient, String functionName) {
- DeleteFunctionRequest request = DeleteFunctionRequest.builder()
- .functionName(functionName)
- .build();
+ UpdateFunctionConfigurationRequest configRequest = UpdateFunctionConfigurationRequest.builder()
+ .functionName("my-function")
+ .environment(env)
+ .timeout(60)
+ .memorySize(512)
+ .build();
- lambdaClient.deleteFunction(request);
- }
+ lambdaClient.updateFunctionConfiguration(configRequest);
```
- ## Spring Boot Integration
-
- ### Configuration
+ ### 7. Integrate with Spring Boot
- Configure Lambda clients as Spring beans:
+ Configure Lambda beans and services:
```java
- import org.springframework.context.annotation.Bean;
- import org.springframework.context.annotation.Configuration;
-
@Configuration
public class LambdaConfiguration {
-
@Bean
public LambdaClient lambdaClient() {
return LambdaClient.builder()
.region(Region.US_EAST_1)
.build();
}
}
- ```
- ### Lambda Invoker Service
-
- Create a service for Lambda function invocation:
-
- ```java
- import org.springframework.stereotype.Service;
- import org.springframework.beans.factory.annotation.Autowired;
-
@Service
public class LambdaInvokerService {
-
- private final LambdaClient lambdaClient;
- private final ObjectMapper objectMapper;
-
- @Autowired
- public LambdaInvokerService(LambdaClient lambdaClient, ObjectMapper objectMapper) {
- this.lambdaClient = lambdaClient;
- this.objectMapper = objectMapper;
- }
-
public <T, R> R invoke(String functionName, T request, Class<R> responseType) {
- try {
- String jsonPayload = objectMapper.writeValueAsString(request);
-
- InvokeRequest invokeRequest = InvokeRequest.builder()
- .functionName(functionName)
- .payload(SdkBytes.fromUtf8String(jsonPayload))
- .build();
-
- InvokeResponse response = lambdaClient.invoke(invokeRequest);
-
- if (response.functionError() != null) {
- throw new LambdaInvocationException(
- "Lambda function error: " + response.functionError());
- }
-
- String responseJson = response.payload().asUtf8String();
-
- return objectMapper.readValue(responseJson, responseType);
-
- } catch (Exception e) {
- throw new RuntimeException("Failed to invoke Lambda function", e);
- }
- }
-
- public void invokeAsync(String functionName, Object request) {
- try {
- String jsonPayload = objectMapper.writeValueAsString(request);
-
- InvokeRequest invokeRequest = InvokeRequest.builder()
- .functionName(functionName)
- .invocationType(InvocationType.EVENT)
- .payload(SdkBytes.fromUtf8String(jsonPayload))
- .build();
-
- lambdaClient.invoke(invokeRequest);
-
- } catch (Exception e) {
- throw new RuntimeException("Failed to invoke Lambda function async", e);
- }
- }
- }
- ```
-
- ### Typed Lambda Client
-
- Create type-safe interfaces for Lambda services:
-
- ```java
- public interface OrderProcessor {
- OrderResponse processOrder(OrderRequest request);
- }
-
- @Service
- public class LambdaOrderProcessor implements OrderProcessor {
-
- private final LambdaInvokerService lambdaInvoker;
-
- @Value("${lambda.order-processor.function-name}")
- private String functionName;
-
- public LambdaOrderProcessor(LambdaInvokerService lambdaInvoker) {
- this.lambdaInvoker = lambdaInvoker;
- }
-
- @Override
- public OrderResponse processOrder(OrderRequest request) {
- return lambdaInvoker.invoke(functionName, request, OrderResponse.class);
+ // Implementation
}
}
```
- ## Error Handling
-
- Implement comprehensive error handling for Lambda operations:
-
- ```java
- public String invokeLambdaSafe(LambdaClient lambdaClient,
- String functionName,
- String payload) {
- try {
- InvokeRequest request = InvokeRequest.builder()
- .functionName(functionName)
- .payload(SdkBytes.fromUtf8String(payload))
- .build();
-
- InvokeResponse response = lambdaClient.invoke(request);
-
- // Check for function error
- if (response.functionError() != null) {
- String errorMessage = response.payload().asUtf8String();
- throw new RuntimeException("Lambda error: " + errorMessage);
- }
-
- // Check status code
- if (response.statusCode() != 200) {
- throw new RuntimeException("Lambda invocation failed with status: " +
- response.statusCode());
- }
-
- return response.payload().asUtf8String();
+ See [spring-boot-integration.md](references/spring-boot-integration.md) for complete integration.
- } catch (LambdaException e) {
- System.err.println("Lambda error: " + e.awsErrorDetails().errorMessage());
- throw e;
- }
- }
+ ### 8. Test Locally
- public class LambdaInvocationException extends RuntimeException {
- public LambdaInvocationException(String message) {
- super(message);
- }
+ Use mocks or LocalStack for development testing.
- public LambdaInvocationException(String message, Throwable cause) {
- super(message, cause);
- }
- }
- ```
+ See [testing.md](references/testing.md) for testing patterns.
## Examples
- ### Example 1: Basic Lambda Invocation
+ ### Basic Invocation
```java
public String invokeFunction(LambdaClient client, String functionName, String payload) {
InvokeRequest request = InvokeRequest.builder()
.functionName(functionName)
.payload(SdkBytes.fromUtf8String(payload))
.build();
InvokeResponse response = client.invoke(request);
if (response.functionError() != null) {
throw new RuntimeException("Lambda error: " + response.functionError());
}
return response.payload().asUtf8String();
}
```
- ### Example 2: Async Invocation
+ ### Async Invocation
```java
public void invokeAsync(LambdaClient client, String functionName, Map<String, Object> event) {
- try {
- String jsonPayload = new ObjectMapper().writeValueAsString(event);
-
- InvokeRequest request = InvokeRequest.builder()
- .functionName(functionName)
- .invocationType(InvocationType.EVENT)
- .payload(SdkBytes.fromUtf8String(jsonPayload))
- .build();
+ String jsonPayload = new ObjectMapper().writeValueAsString(event);
- client.invoke(request);
+ InvokeRequest request = InvokeRequest.builder()
+ .functionName(functionName)
+ .invocationType(InvocationType.EVENT)
+ .payload(SdkBytes.fromUtf8String(jsonPayload))
+ .build();
- } catch (Exception e) {
- throw new RuntimeException("Async invocation failed", e);
- }
+ client.invoke(request);
}
```
- ### Example 3: Spring Boot Service
+ ### Spring Boot Service
```java
@Service
public class LambdaService {
-
private final LambdaClient lambdaClient;
- private final ObjectMapper objectMapper;
- @Value("${lambda.user-processor-function}")
- private String userProcessorFunction;
-
public UserResponse processUser(UserRequest request) {
- try {
- String payload = objectMapper.writeValueAsString(request);
-
- InvokeResponse response = lambdaClient.invoke(
- InvokeRequest.builder()
- .functionName(userProcessorFunction)
- .payload(SdkBytes.fromUtf8String(payload))
- .build()
- );
+ String payload = objectMapper.writeValueAsString(request);
- return objectMapper.readValue(
- response.payload().asUtf8String(),
- UserResponse.class
- );
+ InvokeResponse response = lambdaClient.invoke(
+ InvokeRequest.builder()
+ .functionName("user-processor")
+ .payload(SdkBytes.fromUtf8String(payload))
+ .build()
+ );
- } catch (Exception e) {
- throw new RuntimeException("User processing failed", e);
- }
+ return objectMapper.readValue(
+ response.payload().asUtf8String(),
+ UserResponse.class
+ );
}
}
```
- For comprehensive code examples, see the references section:
+ See [examples.md](references/examples.md) for more examples.
- - **Basic examples** - Simple invocation patterns and function management
- - **Spring Boot integration** - Complete Spring Boot configuration and service patterns
- - **Testing examples** - Unit and integration test patterns
- - **Advanced patterns** - Complex scenarios and best practices
+ ## Best Practices
+ - **Reuse Lambda clients**: Create once and reuse across invocations
+ - **Set appropriate timeouts**: Match client timeout to Lambda function timeout
+ - **Use async invocation**: For fire-and-forget scenarios
+ - **Handle errors properly**: Check for function errors and status codes
+ - **Use environment variables**: For function configuration
+ - **Implement retry logic**: For transient failures with exponential backoff
+ - **Monitor invocations**: Use CloudWatch metrics and logs
+ - **Version functions**: Use aliases and versions for production
+ - **Use VPC**: For accessing resources in private subnets
+ - **Optimize payload size**: Keep payloads small for better performance
+
## Constraints and Warnings
- - **Payload Size**: Lambda payload limited to 6MB for sync invocation, 256KB for async
+ - **Payload Size**: Limited to 6MB for sync, 256KB for async invocation
- **Timeout**: Maximum function timeout is 15 minutes
- **Memory**: Memory configuration affects CPU and network performance
- **Concurrency**: Account-level concurrency limits can cause throttling
- **Cold Starts**: New invocations may have delays for initialization
- **VPC**: VPC functions need proper security group and subnet configuration
- **Layers**: Lambda layers count towards deployment package size limit
- **Reserved Concurrency**: Prevents throttling but limits maximum scaling
- **Event Source Mappings**: Some event sources require special configuration
- **Cost**: Unexpected usage can lead to high bills; set budgets and alerts
- ## Best Practices
-
- 1. **Reuse Lambda clients**: Create once and reuse across invocations
- 2. **Set appropriate timeouts**: Match client timeout to Lambda function timeout
- 3. **Use async invocation**: For fire-and-forget scenarios
- 4. **Handle errors properly**: Check for function errors and status codes
- 5. **Use environment variables**: For function configuration
- 6. **Implement retry logic**: For transient failures
- 7. **Monitor invocations**: Use CloudWatch metrics
- 8. **Version functions**: Use aliases and versions for production
- 9. **Use VPC**: For accessing resources in private subnets
- 10. **Optimize payload size**: Keep payloads small for better performance
-
- ## Testing
-
- Test Lambda services using mocks and test assertions:
-
- ```java
- import org.junit.jupiter.api.Test;
- import org.junit.jupiter.api.extension.ExtendWith;
- import org.mockito.InjectMocks;
- import org.mockito.Mock;
- import org.mockito.junit.jupiter.MockitoExtension;
-
- @ExtendWith(MockitoExtension.class)
- class LambdaInvokerServiceTest {
-
- @Mock
- private LambdaClient lambdaClient;
-
- @Mock
- private ObjectMapper objectMapper;
-
- @InjectMocks
- private LambdaInvokerService service;
+ ## References
- @Test
- void shouldInvokeLambdaSuccessfully() throws Exception {
- // Test implementation
- }
- }
- ```
+ - **[client-setup.md](references/client-setup.md)** — Client configuration and setup
+ - **[invocation-patterns.md](references/invocation-patterns.md)** — Synchronous and async invocation patterns
+ - **[function-management.md](references/function-management.md)** — Create, update, delete functions
+ - **[spring-boot-integration.md](references/spring-boot-integration.md)** — Spring Boot configuration and services
+ - **[testing.md](references/testing.md)** — Unit and integration testing patterns
+ - **[examples.md](references/examples.md)** — Complete code examples and integration patterns
+ - **[official-documentation.md](references/official-documentation.md)** — AWS Lambda concepts and API reference
## Related Skills
- - `@`aws-sdk-java-v2-core - Core AWS SDK patterns and client configuration
- - `@`spring-boot-dependency-injection - Spring dependency injection best practices
- - `@`unit-test-service-layer - Service testing patterns with Mockito
- - `@`spring-boot-actuator - Production monitoring and health checks
-
- ## References
-
- For detailed information and examples, see the following reference files:
-
- - **[Official Documentation](references/official-documentation.md)** - AWS Lambda concepts, API reference, and official guidance
- - **[Examples](references/examples.md)** - Complete code examples and integration patterns
+ - `aws-sdk-java-v2-core` — Core AWS SDK patterns and client configuration
+ - `spring-boot-dependency-injection` — Spring dependency injection best practices
+ - `unit-test-service-layer` — Service testing patterns with Mockito
+ - `spring-boot-actuator` — Production monitoring and health checks
- ## Additional Resources
+ ## External Resources
- [Lambda Examples on GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/lambda)
- [Lambda API Reference](https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/services/lambda/package-summary.html)
- [AWS Lambda Developer Guide](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html)
+