
Aws Sdk Java V2 Lambda
- 1.6k installs
- 311 repo stars
- Updated June 22, 2026
- giuseppe-trisciuoglio/developer-kit
aws-sdk-java-v2-lambda is an agent skill that provides aws lambda patterns using aws sdk for java 2.x. use when invoking lambda functions, creating/updating functions, managing function configurations, working with lambd
About
aws-sdk-java-v2-lambda is an agent skill from giuseppe-trisciuoglio/developer-kit that 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 l. # AWS SDK for Java 2.x - AWS Lambda ## Overview 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 - Invoking Lambda functions from Java applications - Deploying and updating Lambda functions via SDK - Developers invoke aws-sdk-java-v2-lambda during operate/infra work for cloud & infrastructure tasks. The skill documents triggers, prerequisites, and step-by-step workflows grounded in SKILL.md. Compatible with Claude Code, Cursor, and Codex agent runtimes that load marketplace skills.
- AWS SDK for Java 2.x - AWS Lambda
- Invoking Lambda functions from Java applications
- Deploying and updating Lambda functions via SDK
- Managing function configurations and layers
- Integrating Lambda with Spring Boot applications
Aws Sdk Java V2 Lambda by the numbers
- 1,599 all-time installs (skills.sh)
- +55 installs in the week ending Jul 28, 2026 (Skillselion tracking)
- Ranked #252 of 1,041 Cloud & Infrastructure skills by installs in the Skillselion catalog
- Security screen: LOW risk (skills.sh audit)
- Data as of Jul 28, 2026 (Skillselion catalog sync)
aws-sdk-java-v2-lambda capabilities & compatibility
- Capabilities
- aws sdk for java 2.x aws lambda · invoking lambda functions from java applications · deploying and updating lambda functions via sdk · managing function configurations and layers · integrating lambda with spring boot applications
- Use cases
- orchestration
What aws-sdk-java-v2-lambda says it does
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.
- Invoking Lambda functions from Java applications
- Deploying and updating Lambda functions via SDK
npx skills add https://github.com/giuseppe-trisciuoglio/developer-kit --skill aws-sdk-java-v2-lambdaAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 1.6k |
|---|---|
| repo stars | ★ 311 |
| Security audit | 3 / 3 scanners passed |
| Last updated | June 22, 2026 |
| Repository | giuseppe-trisciuoglio/developer-kit ↗ |
What it does
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 L
Who is it for?
Developers working on cloud & infrastructure during operate tasks.
Skip if: Tasks outside Cloud & Infrastructure scope described in SKILL.md.
When should I use this skill?
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 L
What you get
Completed cloud & infrastructure workflow aligned with SKILL.md steps.
- LambdaClient builder configuration
- LambdaAsyncClient async setup code
Files
AWS SDK for Java 2.x - AWS Lambda
Overview
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
- Invoking Lambda functions from Java applications
- Deploying and updating Lambda functions via SDK
- Managing function configurations and layers
- Integrating Lambda with Spring Boot applications
Quick Reference
| 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 |
Instructions
1. Add Dependencies
Include Lambda SDK dependency in pom.xml:
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>lambda</artifactId>
</dependency>See client-setup.md for complete setup.
2. Create Client
Instantiate LambdaClient with proper configuration:
LambdaClient lambdaClient = LambdaClient.builder()
.region(Region.US_EAST_1)
.build();For async operations, use LambdaAsyncClient.
3. Invoke Lambda Function
Synchronous invocation:
InvokeRequest request = InvokeRequest.builder()
.functionName("my-function")
.payload(SdkBytes.fromUtf8String(payload))
.build();
InvokeResponse response = lambdaClient.invoke(request);
return response.payload().asUtf8String();See invocation-patterns.md for patterns.
4. Handle Responses
Parse response payloads and check for errors:
if (response.functionError() != null) {
throw new LambdaInvocationException("Lambda error: " + response.functionError());
}
String result = response.payload().asUtf8String();5. Manage Functions
Create, update, or delete Lambda functions:
// Create
CreateFunctionRequest createRequest = CreateFunctionRequest.builder()
.functionName("my-function")
.runtime(Runtime.JAVA17)
.role(roleArn)
.code(code)
.build();
lambdaClient.createFunction(createRequest);
// Verify function is active before proceeding
GetFunctionRequest getRequest = GetFunctionRequest.builder()
.functionName("my-function")
.build();
GetFunctionResponse getResponse = lambdaClient.getFunction(getRequest);
if (!"Active".equals(getResponse.configuration().state())) {
throw new IllegalStateException("Function not active: " + getResponse.configuration().stateReason());
}
// Update code
UpdateFunctionCodeRequest updateCodeRequest = UpdateFunctionCodeRequest.builder()
.functionName("my-function")
.zipFile(SdkBytes.fromByteArray(zipBytes))
.build();
lambdaClient.updateFunctionCode(updateCodeRequest);
// Wait for deployment to complete
Waiter<GetFunctionConfigurationRequest> waiter = lambdaClient.waiter();
waiter.waitUntilFunctionUpdatedActive(GetFunctionConfigurationRequest.builder()
.functionName("my-function")
.build());See function-management.md for complete patterns.
6. Configure Environment
Set environment variables and concurrency limits:
Environment env = Environment.builder()
.variables(Map.of(
"DB_URL", "jdbc:postgresql://db",
"LOG_LEVEL", "INFO"
))
.build();
UpdateFunctionConfigurationRequest configRequest = UpdateFunctionConfigurationRequest.builder()
.functionName("my-function")
.environment(env)
.timeout(60)
.memorySize(512)
.build();
lambdaClient.updateFunctionConfiguration(configRequest);7. Integrate with Spring Boot
Configure Lambda beans and services:
@Configuration
public class LambdaConfiguration {
@Bean
public LambdaClient lambdaClient() {
return LambdaClient.builder()
.region(Region.US_EAST_1)
.build();
}
}
@Service
public class LambdaInvokerService {
public <T, R> R invoke(String functionName, T request, Class<R> responseType) {
// Implementation
}
}See spring-boot-integration.md for complete integration.
8. Test Locally
Use mocks or LocalStack for development testing.
See testing.md for testing patterns.
Examples
Basic Invocation
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();
}Async Invocation
public void invokeAsync(LambdaClient client, String functionName, Map<String, Object> event) {
String jsonPayload = new ObjectMapper().writeValueAsString(event);
InvokeRequest request = InvokeRequest.builder()
.functionName(functionName)
.invocationType(InvocationType.EVENT)
.payload(SdkBytes.fromUtf8String(jsonPayload))
.build();
client.invoke(request);
}Spring Boot Service
@Service
public class LambdaService {
private final LambdaClient lambdaClient;
public UserResponse processUser(UserRequest request) {
String payload = objectMapper.writeValueAsString(request);
InvokeResponse response = lambdaClient.invoke(
InvokeRequest.builder()
.functionName("user-processor")
.payload(SdkBytes.fromUtf8String(payload))
.build()
);
return objectMapper.readValue(
response.payload().asUtf8String(),
UserResponse.class
);
}
}See examples.md for more examples.
Best Practices
- Reuse clients: Create
LambdaClient/LambdaAsyncClientonce; they are thread-safe - Use async client: For fire-and-forget invocations, use
LambdaAsyncClientwithCompletableFuture - Verify deployments: Always wait for function state to be
Activeafter create/update operations - Limit payload size: Keep request/response payloads under 256KB for async, 6MB for sync invocations
- Configure timeouts: Set client read timeout slightly higher than Lambda function timeout
- Use latest runtime: Specify
Runtime.JAVA17or newer for improved cold start performance
Constraints and Warnings
- Payload Limit: 6MB (sync), 256KB (async invocation)
- Timeout: Max 900 seconds (15 minutes) per invocation
- Cold Starts: JVM-based functions have longer cold starts; use GraalVM Native Image for improvement
- Deployment Size: Function code + layers must not exceed 50MB (zipped) or 250MB (unzipped)
- Concurrency: Default 1000 per region; use reserved concurrency to guarantee capacity
- Cost: Monitor with CloudWatch metrics; set billing alerts to prevent runaway costs
References
- [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 configurationspring-boot-dependency-injection— Spring dependency injection best practicesunit-test-service-layer— Service testing patterns with Mockitospring-boot-actuator— Production monitoring and health checks
External Resources
Lambda Client Setup
Maven Dependency
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>lambda</artifactId>
</dependency>Basic Client Configuration
Synchronous Client
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.lambda.LambdaClient;
LambdaClient lambdaClient = LambdaClient.builder()
.region(Region.US_EAST_1)
.build();Asynchronous Client
import software.amazon.awssdk.services.lambda.LambdaAsyncClient;
LambdaAsyncClient asyncLambdaClient = LambdaAsyncClient.builder()
.region(Region.US_EAST_1)
.build();Custom Configuration
import software.amazon.awssdk.http.apache.ApacheHttpClient;
import java.time.Duration;
LambdaClient lambdaClient = LambdaClient.builder()
.region(Region.US_EAST_1)
.httpClientBuilder(ApacheHttpClient.builder()
.connectionTimeout(Duration.ofSeconds(5))
.socketTimeout(Duration.ofSeconds(300)))
.build();With Credentials Provider
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
AwsBasicCredentials credentials = AwsBasicCredentials.create(
"access-key-id",
"secret-access-key"
);
LambdaClient lambdaClient = LambdaClient.builder()
.region(Region.US_EAST_1)
.credentialsProvider(StaticCredentialsProvider.create(credentials))
.build();Spring Boot Configuration
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();
}
@Bean
public LambdaAsyncClient lambdaAsyncClient() {
return LambdaAsyncClient.builder()
.region(Region.US_EAST_1)
.build();
}
}Environment-Specific Configuration
@Bean
public LambdaClient lambdaClient(
@Value("${aws.region}") String region,
@Value("${aws.endpoint}") Optional<String> endpoint
) {
LambdaClient.Builder builder = LambdaClient.builder()
.region(Region.of(region));
endpoint.ifPresent(e -> builder.endpointOverride(URI.create(e)));
return builder.build();
}AWS Lambda Java SDK Examples
Client Setup
Basic Client Configuration
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.lambda.LambdaClient;
// Create synchronous client
LambdaClient lambdaClient = LambdaClient.builder()
.region(Region.US_EAST_1)
.build();
// Create asynchronous client
LambdaAsyncClient asyncLambdaClient = LambdaAsyncClient.builder()
.region(Region.US_EAST_1)
.build();Client with Configuration
import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;
import software.amazon.awssdk.http.nio.netty.NettyNioHttpServer;
LambdaClient lambdaClient = LambdaClient.builder()
.region(Region.US_EAST_1)
.credentialsProvider(DefaultCredentialsProvider.create())
.httpClientBuilder(NettyNioHttpServer.builder())
.build();Function Invocation Examples
Synchronous Invocation with String Payload
import software.amazon.awssdk.services.lambda.model.*;
import software.amazon.awssdk.core.SdkBytes;
public String invokeLambdaSync(LambdaClient lambdaClient,
String functionName,
String payload) {
InvokeRequest request = InvokeRequest.builder()
.functionName(functionName)
.payload(SdkBytes.fromUtf8String(payload))
.build();
InvokeResponse response = lambdaClient.invoke(request);
// Check for function errors
if (response.functionError() != null) {
throw new RuntimeException("Lambda function error: " +
response.payload().asUtf8String());
}
return response.payload().asUtf8String();
}Asynchronous Invocation
import java.util.concurrent.CompletableFuture;
public CompletableFuture<String> invokeLambdaAsync(LambdaClient lambdaClient,
String functionName,
String payload) {
InvokeRequest request = InvokeRequest.builder()
.functionName(functionName)
.invocationType(InvocationType.EVENT) // Asynchronous
.payload(SdkBytes.fromUtf8String(payload))
.build();
return lambdaClient.invoke(request)
.thenApply(response -> response.payload().asUtf8String());
}Invocation with JSON Object
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();
}Parse Typed Response
import com.fasterxml.jackson.databind.ObjectMapper;
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);
String responseJson = response.payload().asUtf8String();
return mapper.readValue(responseJson, responseType);
}Function Management Examples
List Functions
public List<FunctionConfiguration> listLambdaFunctions(LambdaClient lambdaClient) {
ListFunctionsResponse response = lambdaClient.listFunctions();
return response.functions();
}
// List functions with pagination
public List<FunctionConfiguration> listAllFunctions(LambdaClient lambdaClient) {
ListFunctionsRequest request = ListFunctionsRequest.builder().build();
ListFunctionsResponse response = lambdaClient.listFunctions(request);
return response.functions();
}Get Function Configuration
public FunctionConfiguration getFunctionConfig(LambdaClient lambdaClient,
String functionName) {
GetFunctionRequest request = GetFunctionRequest.builder()
.functionName(functionName)
.build();
GetFunctionResponse response = lambdaClient.getFunction(request);
return response.configuration();
}Get Function Code
public byte[] getFunctionCode(LambdaClient lambdaClient,
String functionName) {
GetFunctionRequest request = GetFunctionRequest.builder()
.functionName(functionName)
.build();
GetFunctionResponse response = lambdaClient.getFunction(request);
return response.code().zipFile().asByteArray();
}Update Function Code
import java.nio.file.Files;
import java.nio.file.Paths;
public void updateLambdaFunction(LambdaClient lambdaClient,
String functionName,
String zipFilePath) throws IOException {
byte[] zipBytes = Files.readAllBytes(Paths.get(zipFilePath));
UpdateFunctionCodeRequest request = UpdateFunctionCodeRequest.builder()
.functionName(functionName)
.zipFile(SdkBytes.fromByteArray(zipBytes))
.publish(true) // Create new version
.build();
UpdateFunctionCodeResponse response = lambdaClient.updateFunctionCode(request);
System.out.println("Updated function version: " + response.version());
}Update Function Configuration
public void updateFunctionConfig(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);
}Create Function
import java.nio.file.Files;
import java.nio.file.Paths;
public void createLambdaFunction(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)
.environment(Environment.builder()
.variables(Map.of("ENV", "production"))
.build())
.build();
CreateFunctionResponse response = lambdaClient.createFunction(request);
System.out.println("Function ARN: " + response.functionArn());
}Delete Function
public void deleteLambdaFunction(LambdaClient lambdaClient, String functionName) {
DeleteFunctionRequest request = DeleteFunctionRequest.builder()
.functionName(functionName)
.build();
lambdaClient.deleteFunction(request);
}Spring Boot Integration Examples
Configuration Class
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();
}
@Bean
public LambdaAsyncClient asyncLambdaClient() {
return LambdaAsyncClient.builder()
.region(Region.US_EAST_1)
.build();
}
}Lambda Invoker Service
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 invokeFunction(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 invokeFunctionAsync(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 Interface
public interface OrderProcessor {
OrderResponse processOrder(OrderRequest request);
CompletableFuture<OrderResponse> processOrderAsync(OrderRequest request);
}
@Service
public class LambdaOrderProcessor implements OrderProcessor {
private final LambdaInvokerService lambdaInvoker;
private final LambdaAsyncClient asyncLambdaClient;
@Value("${lambda.order-processor.function-name}")
private String functionName;
public LambdaOrderProcessor(LambdaInvokerService lambdaInvoker,
LambdaAsyncClient asyncLambdaClient) {
this.lambdaInvoker = lambdaInvoker;
this.asyncLambdaClient = asyncLambdaClient;
}
@Override
public OrderResponse processOrder(OrderRequest request) {
return lambdaInvoker.invoke(functionName, request, OrderResponse.class);
}
@Override
public CompletableFuture<OrderResponse> processOrderAsync(OrderRequest request) {
// Implement async invocation using async client
try {
String jsonPayload = new ObjectMapper().writeValueAsString(request);
InvokeRequest invokeRequest = InvokeRequest.builder()
.functionName(functionName)
.payload(SdkBytes.fromUtf8String(jsonPayload))
.build();
return asyncLambdaClient.invoke(invokeRequest)
.thenApply(response -> {
try {
return new ObjectMapper().readValue(
response.payload().asUtf8String(),
OrderResponse.class);
} catch (Exception e) {
throw new RuntimeException("Failed to parse response", e);
}
});
} catch (Exception e) {
throw new RuntimeException("Failed to invoke Lambda function", e);
}
}
}Error Handling Examples
Comprehensive Error Handling
public String invokeLambdaWithFullErrorHandling(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 LambdaInvocationException(
"Lambda function error: " + errorMessage);
}
// Check status code
if (response.statusCode() != 200) {
throw new LambdaInvocationException(
"Lambda invocation failed with status: " + response.statusCode());
}
return response.payload().asUtf8String();
} catch (LambdaException e) {
System.err.println("AWS Lambda error: " + e.awsErrorDetails().errorMessage());
throw new LambdaInvocationException(
"AWS Lambda service error: " + e.awsErrorDetails().errorMessage(), e);
}
}
public class LambdaInvocationException extends RuntimeException {
public LambdaInvocationException(String message) {
super(message);
}
public LambdaInvocationException(String message, Throwable cause) {
super(message, cause);
}
}Testing Examples
Unit Test for Lambda Service
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;
import static org.mockito.Mockito.*;
import static org.assertj.core.api.Assertions.*;
@ExtendWith(MockitoExtension.class)
class LambdaInvokerServiceTest {
@Mock
private LambdaClient lambdaClient;
@Mock
private ObjectMapper objectMapper;
@InjectMocks
private LambdaInvokerService service;
@Test
void shouldInvokeLambdaSuccessfully() throws Exception {
// Given
OrderRequest request = new OrderRequest("ORDER-123");
OrderResponse expectedResponse = new OrderResponse("SUCCESS");
String jsonPayload = "{\"orderId\":\"ORDER-123\"};
String jsonResponse = "{\"status\":\"SUCCESS\"};
when(objectMapper.writeValueAsString(request))
.thenReturn(jsonPayload);
when(lambdaClient.invoke(any(InvokeRequest.class)))
.thenReturn(InvokeResponse.builder()
.statusCode(200)
.payload(SdkBytes.fromUtf8String(jsonResponse))
.build());
when(objectMapper.readValue(jsonResponse, OrderResponse.class))
.thenReturn(expectedResponse);
// When
OrderResponse result = service.invoke(
"order-processor", request, OrderResponse.class);
// Then
assertThat(result).isEqualTo(expectedResponse);
verify(lambdaClient).invoke(any(InvokeRequest.class));
}
@Test
void shouldHandleFunctionError() throws Exception {
// Given
OrderRequest request = new OrderRequest("ORDER-123");
String jsonPayload = "{\"orderId\":\"ORDER-123\"};
String errorResponse = "{\"errorMessage\":\"Invalid input\"};
when(objectMapper.writeValueAsString(request))
.thenReturn(jsonPayload);
when(lambdaClient.invoke(any(InvokeRequest.class)))
.thenReturn(InvokeResponse.builder()
.statusCode(200)
.functionError("Unhandled")
.payload(SdkBytes.fromUtf8String(errorResponse))
.build());
// When & Then
assertThatThrownBy(() ->
service.invoke("order-processor", request, OrderResponse.class))
.isInstanceOf(LambdaInvocationException.class)
.hasMessageContaining("Lambda function error");
}
}Maven Dependencies
<!-- AWS SDK for Java v2 Lambda -->
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>lambda</artifactId>
<version>2.36.3</version> // Use the latest version available
</dependency>
<!-- Jackson for JSON processing -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
<!-- Spring Boot support -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>Lambda Function Management
List Functions
import software.amazon.awssdk.services.lambda.model.ListFunctionsResponse;
import software.amazon.awssdk.services.lambda.model.FunctionConfiguration;
public List<FunctionConfiguration> listFunctions(LambdaClient lambdaClient) {
ListFunctionsResponse response = lambdaClient.listFunctions();
return response.functions();
}Get Function Configuration
public FunctionConfiguration getFunctionConfig(LambdaClient lambdaClient,
String functionName) {
GetFunctionRequest request = GetFunctionRequest.builder()
.functionName(functionName)
.build();
GetFunctionResponse response = lambdaClient.getFunction(request);
return response.configuration();
}Update Function Code
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));
UpdateFunctionCodeRequest request = UpdateFunctionCodeRequest.builder()
.functionName(functionName)
.zipFile(SdkBytes.fromByteArray(zipBytes))
.publish(true)
.build();
UpdateFunctionCodeResponse response = lambdaClient.updateFunctionCode(request);
System.out.println("Updated function version: " + response.version());
}Update Function Configuration
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);
}Create Function
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
public void deleteFunction(LambdaClient lambdaClient, String functionName) {
DeleteFunctionRequest request = DeleteFunctionRequest.builder()
.functionName(functionName)
.build();
lambdaClient.deleteFunction(request);
}Environment Variables
Set Environment Variables
public void setEnvironmentVariables(LambdaClient lambdaClient,
String functionName,
Map<String, String> variables) {
Environment environment = Environment.builder()
.variables(variables)
.build();
UpdateFunctionConfigurationRequest request = UpdateFunctionConfigurationRequest.builder()
.functionName(functionName)
.environment(environment)
.build();
lambdaClient.updateFunctionConfiguration(request);
}Get Environment Variables
public Map<String, String> getEnvironmentVariables(LambdaClient lambdaClient,
String functionName) {
GetFunctionConfigurationRequest request = GetFunctionConfigurationRequest.builder()
.functionName(functionName)
.build();
GetFunctionConfigurationResponse response = lambdaClient.getFunctionConfiguration(request);
return response.environment().variables();
}Concurrency Configuration
Set Reserved Concurrency
public void setReservedConcurrency(LambdaClient lambdaClient,
String functionName,
Integer concurrentExecutions) {
PutFunctionConcurrencyRequest request = PutFunctionConcurrencyRequest.builder()
.functionName(functionName)
.reservedConcurrentExecutions(concurrentExecutions)
.build();
lambdaClient.putFunctionConcurrency(request);
}Set Provisioned Concurrency
public void setProvisionedConcurrency(LambdaClient lambdaClient,
String functionName,
String aliasName,
Integer provisionedConcurrentExecutions) {
PutProvisionedConcurrencyConfigRequest request = PutProvisionedConcurrencyConfigRequest.builder()
.functionName(functionName)
.qualifier(aliasName)
.provisionedConcurrentExecutions(provisionedConcurrentExecutions)
.build();
lambdaClient.putProvisionedConcurrencyConfig(request);
}Layers Management
List Layers
public List<LayerConfiguration> listLayers(LambdaClient lambdaClient) {
ListLayersResponse response = lambdaClient.listLayers();
return response.layers();
}Add Layer to Function
public void addLayerToFunction(LambdaClient lambdaClient,
String functionName,
String layerArn) {
UpdateFunctionConfigurationRequest request = UpdateFunctionConfigurationRequest.builder()
.functionName(functionName)
.layers(layerArn)
.build();
lambdaClient.updateFunctionConfiguration(request);
}Aliases and Versions
Create Alias
public void createAlias(LambdaClient lambdaClient,
String functionName,
String aliasName,
String version) {
CreateAliasRequest request = CreateAliasRequest.builder()
.functionName(functionName)
.name(aliasName)
.functionVersion(version)
.build();
lambdaClient.createAlias(request);
}Update Alias
public void updateAlias(LambdaClient lambdaClient,
String functionName,
String aliasName,
String newVersion) {
UpdateAliasRequest request = UpdateAliasRequest.builder()
.functionName(functionName)
.name(aliasName)
.functionVersion(newVersion)
.build();
lambdaClient.updateAlias(request);
}Publish Version
public String publishVersion(LambdaClient lambdaClient,
String functionName) {
PublishVersionRequest request = PublishVersionRequest.builder()
.functionName(functionName)
.build();
PublishVersionResponse response = lambdaClient.publishVersion(request);
return response.version();
}Lambda Invocation Patterns
Synchronous Invocation
Basic Invocation
import software.amazon.awssdk.services.lambda.model.InvokeRequest;
import software.amazon.awssdk.services.lambda.model.InvokeResponse;
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();
}With JSON Objects
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();
}Parse Typed Responses
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);
String responseJson = response.payload().asUtf8String();
return mapper.readValue(responseJson, responseType);
}Asynchronous Invocation
Fire-and-Forget
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());
}Async with Event
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();
client.invoke(request);
} catch (Exception e) {
throw new RuntimeException("Async invocation failed", e);
}
}Error Handling
Comprehensive Error Handling
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();
} catch (LambdaException e) {
System.err.println("Lambda error: " + e.awsErrorDetails().errorMessage());
throw e;
}
}Custom Exception
public class LambdaInvocationException extends RuntimeException {
private final String functionName;
private final String statusCode;
public LambdaInvocationException(String message) {
super(message);
this.functionName = null;
this.statusCode = null;
}
public LambdaInvocationException(String message, Throwable cause) {
super(message, cause);
this.functionName = null;
this.statusCode = null;
}
public LambdaInvocationException(String functionName, String statusCode, String message) {
super(message);
this.functionName = functionName;
this.statusCode = statusCode;
}
public String getFunctionName() {
return functionName;
}
public String getStatusCode() {
return statusCode;
}
}Advanced Patterns
Retry Logic
public String invokeWithRetry(LambdaClient lambdaClient,
String functionName,
String payload,
int maxRetries) {
int attempts = 0;
while (attempts < maxRetries) {
try {
return invokeLambda(lambdaClient, functionName, payload);
} catch (LambdaException e) {
attempts++;
if (attempts >= maxRetries) {
throw e;
}
try {
Thread.sleep(1000L * attempts); // Exponential backoff
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
throw new RuntimeException("Interrupted during retry", ie);
}
}
}
throw new RuntimeException("Max retries exceeded");
}Batch Invocation
public List<String> invokeBatch(LambdaClient lambdaClient,
String functionName,
List<String> payloads) {
List<String> responses = new ArrayList<>();
for (String payload : payloads) {
try {
String response = invokeLambda(lambdaClient, functionName, payload);
responses.add(response);
} catch (Exception e) {
responses.add("ERROR: " + e.getMessage());
}
}
return responses;
}Parallel Invocation
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
public List<String> invokeParallel(LambdaAsyncClient asyncClient,
String functionName,
List<String> payloads) {
List<CompletableFuture<String>> futures = payloads.stream()
.map(payload -> CompletableFuture.supplyAsync(() -> {
try {
return invokeLambdaAsync(asyncClient, functionName, payload);
} catch (Exception e) {
return "ERROR: " + e.getMessage();
}
}))
.collect(Collectors.toList());
return futures.stream()
.map(CompletableFuture::join)
.collect(Collectors.toList());
}AWS Lambda Official Documentation Reference
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.
Common Use Cases
- Stream processing: Process real-time data streams for analytics
- Web applications: Build scalable web apps that automatically adjust
- Mobile backends: Create secure API backends
- IoT backends: Handle web, mobile, IoT, and third-party API requests
- File processing: Process files automatically when uploaded
- Database operations: Respond to database changes and automate data workflows
- Scheduled tasks: Run automated operations on a regular schedule
How Lambda Works
1. You write and organize your code in Lambda functions 2. You control security through Lambda permissions using execution roles 3. Event sources and AWS services trigger your Lambda functions 4. Lambda runs your code with language-specific runtimes
Key Features
Configuration & Security
- Environment variables modify behavior without deployments
- Versions safely test new features while maintaining stable production
- Lambda layers optimize code reuse across multiple functions
- Code signing ensures only approved code reaches production
Performance
- Concurrency controls manage responsiveness and resource utilization
- Lambda SnapStart reduces cold start times to sub-second performance
- Response streaming delivers large payloads incrementally
- Container images package functions with complex dependencies
Integration
- VPC networks secure sensitive resources and internal services
- File system integration shares persistent data across function invocations
- Function URLs create public APIs without additional services
- Lambda extensions augment functions with monitoring and operational tools
AWS Lambda Java SDK API
Key Classes
LambdaClient- Synchronous service clientLambdaAsyncClient- Asynchronous service clientLambdaClientBuilder- Builder for synchronous clientLambdaAsyncClientBuilder- Builder for asynchronous clientLambdaServiceClientConfiguration- Client settings configuration
Related Packages
software.amazon.awssdk.services.lambda.model- API modelssoftware.amazon.awssdk.services.lambda.transform- Request/response transformationssoftware.amazon.awssdk.services.lambda.paginators- Pagination utilitiessoftware.amazon.awssdk.services.lambda.waiters- Waiter utilities
Authentication
Lambda supports signature version 4 for API authentication.
CA Requirements
Clients need to support these CAs:
- Amazon Root CA 1
- Starfield Services Root Certificate Authority - G2
- Starfield Class 2 Certification Authority
Core API Operations
Function Management Operations
CreateFunction- Create new Lambda functionDeleteFunction- Delete existing functionGetFunction- Retrieve function configurationUpdateFunctionCode- Update function codeUpdateFunctionConfiguration- Update function settingsListFunctions- List functions for account
Invocation Operations
Invoke- Invoke Lambda function synchronouslyInvokewithInvocationType.EVENT- Asynchronous invocation
Environment & Configuration
- Environment variable management
- Function configuration updates
- Version and alias management
- Layer management
Examples Overview
The AWS documentation includes examples for:
- Basic Lambda function creation and invocation
- Function configuration and updates
- Environment variable management
- Function listing and cleanup
- Integration patterns
Best Practices from Official Docs
- Reuse Lambda clients across invocations
- Set appropriate timeouts matching function requirements
- Use async invocation for fire-and-forget scenarios
- Implement proper error handling for function errors and status codes
- Use environment variables for configuration management
- Version functions for production stability
- Monitor invocations using CloudWatch metrics
- Implement retry logic for transient failures
- Use VPC integration for private resources
- Optimize payload sizes for performance
Security Considerations
- Use IAM roles with least privilege
- Implement proper Lambda permissions
- Use environment variables for sensitive data
- Enable CloudTrail logging
- Monitor security events with CloudWatch
- Use code signing for production deployments
- Implement proper authentication and authorization
Spring Boot Integration
Configuration
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();
}
@Bean
public LambdaAsyncClient lambdaAsyncClient() {
return LambdaAsyncClient.builder()
.region(Region.US_EAST_1)
.build();
}
@Bean
public ObjectMapper lambdaObjectMapper() {
return new ObjectMapper();
.registerModules(new JavaTimeModule())
.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
}
}Lambda Invoker Service
import org.springframework.stereotype.Service;
import lombok.RequiredArgsConstructor;
@Service
@RequiredArgsConstructor
public class LambdaInvokerService {
private final LambdaClient lambdaClient;
private final 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());
}
if (response.statusCode() != 200) {
throw new LambdaInvocationException(
functionName,
String.valueOf(response.statusCode()),
"Lambda invocation failed"
);
}
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);
}
}
public String invokeRaw(String functionName, String payload) {
try {
InvokeRequest invokeRequest = InvokeRequest.builder()
.functionName(functionName)
.payload(SdkBytes.fromUtf8String(payload))
.build();
InvokeResponse response = lambdaClient.invoke(invokeRequest);
if (response.functionError() != null) {
throw new LambdaInvocationException(
"Lambda function error: " + response.functionError());
}
return response.payload().asUtf8String();
} catch (Exception e) {
throw new RuntimeException("Failed to invoke Lambda function", e);
}
}
}Typed Lambda Client
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);
}
}Configuration Properties
@Configuration
@ConfigurationProperties(prefix = "lambda")
@Data
public class LambdaProperties {
private Map<String, FunctionConfig> functions = new HashMap<>();
@Data
public static class FunctionConfig {
private String functionName;
private String region;
private Integer timeout;
private Integer memorySize;
private Map<String, String> environment = new HashMap<>();
}
}Application Properties
lambda:
functions:
order-processor:
function-name: ${ORDER_PROCESSOR_FUNCTION:order-processor-dev}
region: ${AWS_REGION:us-east-1}
timeout: 60
memory-size: 512
environment:
LOG_LEVEL: INFO
user-processor:
function-name: ${USER_PROCESSOR_FUNCTION:user-processor-dev}
region: ${AWS_REGION:us-east-1}
timeout: 30
memory-size: 256Dynamic Lambda Service
@Service
public class DynamicLambdaService {
private final LambdaClient lambdaClient;
private final LambdaProperties lambdaProperties;
public <T, R> R invoke(String functionKey, T request, Class<R> responseType) {
LambdaProperties.FunctionConfig config = lambdaProperties.getFunctions()
.get(functionKey);
if (config == null) {
throw new IllegalArgumentException("Unknown function key: " + functionKey);
}
return invokeLambda(config, request, responseType);
}
private <T, R> R invokeLambda(LambdaProperties.FunctionConfig config,
T request,
Class<R> responseType) {
try {
String jsonPayload = objectMapper.writeValueAsString(request);
InvokeRequest invokeRequest = InvokeRequest.builder()
.functionName(config.getFunctionName())
.payload(SdkBytes.fromUtf8String(jsonPayload))
.build();
InvokeResponse response = lambdaClient.invoke(invokeRequest);
String responseJson = response.payload().asUtf8String();
return objectMapper.readValue(responseJson, responseType);
} catch (Exception e) {
throw new RuntimeException("Failed to invoke Lambda", e);
}
}
}Async Lambda Service
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import java.util.concurrent.CompletableFuture;
@Service
public class AsyncLambdaService {
private final LambdaAsyncClient asyncClient;
@Async
public CompletableFuture<String> invokeAsync(String functionName,
String payload) {
return CompletableFuture.supplyAsync(() -> {
try {
String jsonPayload = objectMapper.writeValueAsString(payload);
InvokeRequest request = InvokeRequest.builder()
.functionName(functionName)
.payload(SdkBytes.fromUtf8String(jsonPayload))
.build();
InvokeResponse response = asyncClient.invoke(request).get();
return response.payload().asUtf8String();
} catch (Exception e) {
throw new RuntimeException("Async invocation failed", e);
}
});
}
}Health Check
import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.stereotype.Component;
@Component
@RequiredArgsConstructor
public class LambdaHealthIndicator implements HealthIndicator {
private final LambdaClient lambdaClient;
@Override
public Health health() {
try {
ListFunctionsResponse response = lambdaClient.listFunctions();
return Health.up()
.withDetail("functions", response.functions().size())
.build();
} catch (Exception e) {
return Health.down()
.withDetail("error", e.getMessage())
.build();
}
}
}Testing Lambda Services
Unit Testing with Mocks
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;
import software.amazon.awssdk.services.lambda.LambdaClient;
import software.amazon.awssdk.services.lambda.model.InvokeResponse;
import software.amazon.awssdk.core.SdkBytes;
import static org.mockito.Mockito.*;
import static org.assertj.core.api.Assertions.*;
@ExtendWith(MockitoExtension.class)
class LambdaInvokerServiceTest {
@Mock
private LambdaClient lambdaClient;
@Mock
private ObjectMapper objectMapper;
@InjectMocks
private LambdaInvokerService service;
@Test
void shouldInvokeLambdaSuccessfully() throws Exception {
// Arrange
String functionName = "test-function";
OrderRequest request = new OrderRequest("123", List.of());
String jsonPayload = "{\"orderId\":\"123\",\"items\":[]}";
String jsonResponse = "{\"status\":\"SUCCESS\"}";
when(objectMapper.writeValueAsString(request)).thenReturn(jsonPayload);
when(objectMapper.readValue(jsonResponse, OrderResponse.class))
.thenReturn(new OrderResponse("SUCCESS"));
InvokeResponse invokeResponse = InvokeResponse.builder()
.statusCode(200)
.payload(SdkBytes.fromUtf8String(jsonResponse))
.build();
when(lambdaClient.invoke(any(InvokeRequest.class))).thenReturn(invokeResponse);
// Act
OrderResponse response = service.invoke(functionName, request, OrderResponse.class);
// Assert
assertThat(response.getStatus()).isEqualTo("SUCCESS");
InvokeRequest expectedRequest = InvokeRequest.builder()
.functionName(functionName)
.payload(SdkBytes.fromUtf8String(jsonPayload))
.build();
verify(lambdaClient).invoke(expectedRequest);
}
@Test
void shouldHandleLambdaFunctionError() throws Exception {
// Arrange
String functionName = "test-function";
OrderRequest request = new OrderRequest("123", List.of());
String jsonPayload = "{\"orderId\":\"123\",\"items\":[]}";
String errorResponse = "{\"error\":\"Invalid input\"}";
when(objectMapper.writeValueAsString(request)).thenReturn(jsonPayload);
InvokeResponse invokeResponse = InvokeResponse.builder()
.statusCode(200)
.functionError("Unhandled")
.payload(SdkBytes.fromUtf8String(errorResponse))
.build();
when(lambdaClient.invoke(any(InvokeRequest.class))).thenReturn(invokeResponse);
// Act & Assert
assertThatThrownBy(() -> service.invoke(functionName, request, OrderResponse.class))
.isInstanceOf(LambdaInvocationException.class)
.hasMessageContaining("Lambda function error");
}
@Test
void shouldHandleServiceException() {
// Arrange
String functionName = "test-function";
OrderRequest request = new OrderRequest("123", List.of());
when(lambdaClient.invoke(any(InvokeRequest.class)))
.thenThrow(new LambdaException("Service unavailable"));
// Act & Assert
assertThatThrownBy(() -> service.invoke(functionName, request, OrderResponse.class))
.isInstanceOf(RuntimeException.class)
.hasMessageContaining("Failed to invoke Lambda function");
}
}Integration Testing
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import static org.assertj.core.api.Assertions.*;
@SpringBootTest
@ActiveProfiles("test")
class LambdaInvokerServiceIntegrationTest {
@Autowired
private LambdaInvokerService lambdaInvoker;
@Test
void shouldInvokeRealLambdaFunction() {
// Arrange
String functionName = "test-function";
TestRequest request = new TestRequest("test-data");
// Act
TestResponse response = lambdaInvoker.invoke(functionName, request, TestResponse.class);
// Assert
assertThat(response).isNotNull();
assertThat(response.getStatus()).isEqualTo("SUCCESS");
}
}Testing with LocalStack
import org.testcontainers.containers.localstack.LocalStackContainer;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
import org.testcontainers.utility.DockerImageName;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.lambda.LambdaClient;
@SpringBootTest
@Testcontainers
class LambdaLocalStackTest {
@Container
static LocalStackContainer localstack = new LocalStackContainer(
DockerImageName.parse("localstack/localstack:latest"))
.withServices(LocalStackContainer.Service.LAMBDA);
@DynamicPropertySource
static void configureProperties(DynamicPropertyRegistry registry) {
registry.add("aws.endpoint", localstack::getEndpoint);
registry.add("aws.region", () -> "us-east-1");
}
@Bean
public LambdaClient lambdaClient() {
return LambdaClient.builder()
.endpointOverride(URI.create(localstack.getEndpoint()))
.region(Region.US_EAST_1)
.credentialsProvider(StaticCredentialsProvider.create(
AwsBasicCredentials.create("test", "test")))
.build();
}
}Testing Async Invocations
@ExtendWith(MockitoExtension.class)
class AsyncLambdaServiceTest {
@Mock
private LambdaAsyncClient asyncClient;
@InjectMocks
private AsyncLambdaService asyncService;
@Test
void shouldInvokeLambdaAsync() throws Exception {
// Arrange
String functionName = "test-function";
String payload = "{\"test\":\"data\"}";
CompletableFuture<InvokeResponse> future = CompletableFuture.completedFuture(
InvokeResponse.builder()
.statusCode(202)
.payload(SdkBytes.fromUtf8String("{\"status\":\"accepted\"}"))
.build()
);
when(asyncClient.invoke(any(InvokeRequest.class))).thenReturn(future);
// Act
CompletableFuture<String> result = asyncService.invokeAsync(functionName, payload);
// Assert
assertThat(result.get()).contains("accepted");
}
}Testing Error Scenarios
@Test
void shouldHandleTimeout() {
// Arrange
when(lambdaClient.invoke(any(InvokeRequest.class)))
.thenAnswer(invocation -> {
Thread.sleep(5000); // Simulate timeout
return InvokeResponse.builder().build();
});
// Act & Assert
assertThatThrownBy(() -> service.invoke("function", request, Response.class))
.isInstanceOf(RuntimeException.class);
}
@Test
void shouldRetryOnTransientFailure() {
// Arrange
when(lambdaClient.invoke(any(InvokeRequest.class)))
.thenThrow(new LambdaException("Service unavailable"))
.thenReturn(InvokeResponse.builder()
.statusCode(200)
.payload(SdkBytes.fromUtf8String("{\"status\":\"ok\"}"))
.build());
// Act
Response response = service.invokeWithRetry("function", request, Response.class, 3);
// Assert
assertThat(response.getStatus()).isEqualTo("ok");
verify(lambdaClient, times(2)).invoke(any(InvokeRequest.class));
}Test Fixtures
class LambdaTestFixture {
public static InvokeResponse successResponse(String payload) {
return InvokeResponse.builder()
.statusCode(200)
.payload(SdkBytes.fromUtf8String(payload))
.build();
}
public static InvokeResponse errorResponse(String error) {
return InvokeResponse.builder()
.statusCode(200)
.functionError("Handled")
.payload(SdkBytes.fromUtf8String("{\"error\":\"" + error + "\"}"))
.build();
}
public static InvokeRequest invokeRequest(String functionName, String payload) {
return InvokeRequest.builder()
.functionName(functionName)
.payload(SdkBytes.fromUtf8String(payload))
.build();
}
}Related skills
How it compares
Use aws-sdk-java-v2-lambda for Java Invoke client setup; pick infrastructure skills when deploying Lambda functions rather than calling them.
FAQ
What does aws-sdk-java-v2-lambda do?
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 L
When should I use aws-sdk-java-v2-lambda?
During operate infra work for cloud & infrastructure.
Is aws-sdk-java-v2-lambda safe to install?
Review the Security Audits panel on this listing before production use.