Lambda examples using SDK for Java 2.x - AWS SDK for Java 2.x

Lambda examples using SDK for Java 2.x

The following code examples show you how to perform actions and implement common scenarios by using the AWS SDK for Java 2.x with Lambda.

Actions are code excerpts from larger programs and must be run in context. While actions show you how to call individual service functions, you can see actions in context in their related scenarios and cross-service examples.

Scenarios are code examples that show you how to accomplish a specific task by calling multiple functions within the same service.

Each example includes a link to GitHub, where you can find instructions on how to set up and run the code in context.

Get started

The following code examples show how to get started using Lambda.

SDK for Java 2.x
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository.

package com.example.lambda; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.lambda.LambdaClient; import software.amazon.awssdk.services.lambda.model.LambdaException; import software.amazon.awssdk.services.lambda.model.ListFunctionsResponse; import software.amazon.awssdk.services.lambda.model.FunctionConfiguration; import java.util.List; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html */ public class ListLambdaFunctions { public static void main(String[] args) { Region region = Region.US_WEST_2; LambdaClient awsLambda = LambdaClient.builder() .region(region) .build(); listFunctions(awsLambda); awsLambda.close(); } public static void listFunctions(LambdaClient awsLambda) { try { ListFunctionsResponse functionResult = awsLambda.listFunctions(); List<FunctionConfiguration> list = functionResult.functions(); for (FunctionConfiguration config : list) { System.out.println("The function name is " + config.functionName()); } } catch (LambdaException e) { System.err.println(e.getMessage()); System.exit(1); } } }
  • For API details, see ListFunctions in AWS SDK for Java 2.x API Reference.

Actions

The following code example shows how to use CreateFunction.

SDK for Java 2.x
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository.

import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.core.waiters.WaiterResponse; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.lambda.LambdaClient; import software.amazon.awssdk.services.lambda.model.CreateFunctionRequest; import software.amazon.awssdk.services.lambda.model.FunctionCode; import software.amazon.awssdk.services.lambda.model.CreateFunctionResponse; import software.amazon.awssdk.services.lambda.model.GetFunctionRequest; import software.amazon.awssdk.services.lambda.model.GetFunctionResponse; import software.amazon.awssdk.services.lambda.model.LambdaException; import software.amazon.awssdk.services.lambda.model.Runtime; import software.amazon.awssdk.services.lambda.waiters.LambdaWaiter; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; /** * This code example requires a ZIP or JAR that represents the code of the * Lambda function. * If you do not have a ZIP or JAR, please refer to the following document: * * https://github.com/aws-doc-sdk-examples/tree/master/javav2/usecases/creating_workflows_stepfunctions * * Also, set up your development environment, including your credentials. * * For information, see this documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html */ public class CreateFunction { public static void main(String[] args) { final String usage = """ Usage: <functionName> <filePath> <role> <handler>\s Where: functionName - The name of the Lambda function.\s filePath - The path to the ZIP or JAR where the code is located.\s role - The role ARN that has Lambda permissions.\s handler - The fully qualified method name (for example, example.Handler::handleRequest). \s """; if (args.length != 4) { System.out.println(usage); System.exit(1); } String functionName = args[0]; String filePath = args[1]; String role = args[2]; String handler = args[3]; Region region = Region.US_WEST_2; LambdaClient awsLambda = LambdaClient.builder() .region(region) .build(); createLambdaFunction(awsLambda, functionName, filePath, role, handler); awsLambda.close(); } public static void createLambdaFunction(LambdaClient awsLambda, String functionName, String filePath, String role, String handler) { try { LambdaWaiter waiter = awsLambda.waiter(); InputStream is = new FileInputStream(filePath); SdkBytes fileToUpload = SdkBytes.fromInputStream(is); FunctionCode code = FunctionCode.builder() .zipFile(fileToUpload) .build(); CreateFunctionRequest functionRequest = CreateFunctionRequest.builder() .functionName(functionName) .description("Created by the Lambda Java API") .code(code) .handler(handler) .runtime(Runtime.JAVA8) .role(role) .build(); // Create a Lambda function using a waiter. CreateFunctionResponse functionResponse = awsLambda.createFunction(functionRequest); GetFunctionRequest getFunctionRequest = GetFunctionRequest.builder() .functionName(functionName) .build(); WaiterResponse<GetFunctionResponse> waiterResponse = waiter.waitUntilFunctionExists(getFunctionRequest); waiterResponse.matched().response().ifPresent(System.out::println); System.out.println("The function ARN is " + functionResponse.functionArn()); } catch (LambdaException | FileNotFoundException e) { System.err.println(e.getMessage()); System.exit(1); } } }
  • For API details, see CreateFunction in AWS SDK for Java 2.x API Reference.

The following code example shows how to use DeleteFunction.

SDK for Java 2.x
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository.

import software.amazon.awssdk.services.lambda.LambdaClient; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.lambda.model.DeleteFunctionRequest; import software.amazon.awssdk.services.lambda.model.LambdaException; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html */ public class DeleteFunction { public static void main(String[] args) { final String usage = """ Usage: <functionName>\s Where: functionName - The name of the Lambda function.\s """; if (args.length != 1) { System.out.println(usage); System.exit(1); } String functionName = args[0]; Region region = Region.US_EAST_1; LambdaClient awsLambda = LambdaClient.builder() .region(region) .build(); deleteLambdaFunction(awsLambda, functionName); awsLambda.close(); } public static void deleteLambdaFunction(LambdaClient awsLambda, String functionName) { try { DeleteFunctionRequest request = DeleteFunctionRequest.builder() .functionName(functionName) .build(); awsLambda.deleteFunction(request); System.out.println("The " + functionName + " function was deleted"); } catch (LambdaException e) { System.err.println(e.getMessage()); System.exit(1); } } }
  • For API details, see DeleteFunction in AWS SDK for Java 2.x API Reference.

The following code example shows how to use Invoke.

SDK for Java 2.x
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository.

import org.json.JSONObject; import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider; import software.amazon.awssdk.services.lambda.LambdaClient; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.lambda.model.InvokeRequest; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.services.lambda.model.InvokeResponse; import software.amazon.awssdk.services.lambda.model.LambdaException; public class LambdaInvoke { /* * Function names appear as * arn:aws:lambda:us-west-2:335556666777:function:HelloFunction * you can retrieve the value by looking at the function in the AWS Console * * Also, set up your development environment, including your credentials. * * For information, see this documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started. * html */ public static void main(String[] args) { final String usage = """ Usage: <functionName>\s Where: functionName - The name of the Lambda function\s """; if (args.length != 1) { System.out.println(usage); System.exit(1); } String functionName = args[0]; Region region = Region.US_WEST_2; LambdaClient awsLambda = LambdaClient.builder() .region(region) .build(); invokeFunction(awsLambda, functionName); awsLambda.close(); } public static void invokeFunction(LambdaClient awsLambda, String functionName) { InvokeResponse res = null; try { // Need a SdkBytes instance for the payload. JSONObject jsonObj = new JSONObject(); jsonObj.put("inputValue", "2000"); String json = jsonObj.toString(); SdkBytes payload = SdkBytes.fromUtf8String(json); // Setup an InvokeRequest. InvokeRequest request = InvokeRequest.builder() .functionName(functionName) .payload(payload) .build(); res = awsLambda.invoke(request); String value = res.payload().asUtf8String(); System.out.println(value); } catch (LambdaException e) { System.err.println(e.getMessage()); System.exit(1); } } }
  • For API details, see Invoke in AWS SDK for Java 2.x API Reference.

Scenarios

The following code example shows how to:

  • Create an IAM role and Lambda function, then upload handler code.

  • Invoke the function with a single parameter and get results.

  • Update the function code and configure with an environment variable.

  • Invoke the function with new parameters and get results. Display the returned execution log.

  • List the functions for your account, then clean up resources.

For more information, see Create a Lambda function with the console.

SDK for Java 2.x
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository.

/* * Lambda function names appear as: * * arn:aws:lambda:us-west-2:335556666777:function:HelloFunction * * To find this value, look at the function in the AWS Management Console. * * Before running this Java code example, set up your development environment, including your credentials. * * For more information, see this documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html * * This example performs the following tasks: * * 1. Creates an AWS Lambda function. * 2. Gets a specific AWS Lambda function. * 3. Lists all Lambda functions. * 4. Invokes a Lambda function. * 5. Updates the Lambda function code and invokes it again. * 6. Updates a Lambda function's configuration value. * 7. Deletes a Lambda function. */ public class LambdaScenario { public static final String DASHES = new String(new char[80]).replace("\0", "-"); public static void main(String[] args) throws InterruptedException { final String usage = """ Usage: <functionName> <filePath> <role> <handler> <bucketName> <key>\s Where: functionName - The name of the Lambda function.\s filePath - The path to the .zip or .jar where the code is located.\s role - The AWS Identity and Access Management (IAM) service role that has Lambda permissions.\s handler - The fully qualified method name (for example, example.Handler::handleRequest).\s bucketName - The Amazon Simple Storage Service (Amazon S3) bucket name that contains the .zip or .jar used to update the Lambda function's code.\s key - The Amazon S3 key name that represents the .zip or .jar (for example, LambdaHello-1.0-SNAPSHOT.jar). """; if (args.length != 6) { System.out.println(usage); System.exit(1); } String functionName = args[0]; String filePath = args[1]; String role = args[2]; String handler = args[3]; String bucketName = args[4]; String key = args[5]; Region region = Region.US_WEST_2; LambdaClient awsLambda = LambdaClient.builder() .region(region) .build(); System.out.println(DASHES); System.out.println("Welcome to the AWS Lambda example scenario."); System.out.println(DASHES); System.out.println(DASHES); System.out.println("1. Create an AWS Lambda function."); String funArn = createLambdaFunction(awsLambda, functionName, filePath, role, handler); System.out.println("The AWS Lambda ARN is " + funArn); System.out.println(DASHES); System.out.println(DASHES); System.out.println("2. Get the " + functionName + " AWS Lambda function."); getFunction(awsLambda, functionName); System.out.println(DASHES); System.out.println(DASHES); System.out.println("3. List all AWS Lambda functions."); listFunctions(awsLambda); System.out.println(DASHES); System.out.println(DASHES); System.out.println("4. Invoke the Lambda function."); System.out.println("*** Sleep for 1 min to get Lambda function ready."); Thread.sleep(60000); invokeFunction(awsLambda, functionName); System.out.println(DASHES); System.out.println(DASHES); System.out.println("5. Update the Lambda function code and invoke it again."); updateFunctionCode(awsLambda, functionName, bucketName, key); System.out.println("*** Sleep for 1 min to get Lambda function ready."); Thread.sleep(60000); invokeFunction(awsLambda, functionName); System.out.println(DASHES); System.out.println(DASHES); System.out.println("6. Update a Lambda function's configuration value."); updateFunctionConfiguration(awsLambda, functionName, handler); System.out.println(DASHES); System.out.println(DASHES); System.out.println("7. Delete the AWS Lambda function."); LambdaScenario.deleteLambdaFunction(awsLambda, functionName); System.out.println(DASHES); System.out.println(DASHES); System.out.println("The AWS Lambda scenario completed successfully"); System.out.println(DASHES); awsLambda.close(); } public static String createLambdaFunction(LambdaClient awsLambda, String functionName, String filePath, String role, String handler) { try { LambdaWaiter waiter = awsLambda.waiter(); InputStream is = new FileInputStream(filePath); SdkBytes fileToUpload = SdkBytes.fromInputStream(is); FunctionCode code = FunctionCode.builder() .zipFile(fileToUpload) .build(); CreateFunctionRequest functionRequest = CreateFunctionRequest.builder() .functionName(functionName) .description("Created by the Lambda Java API") .code(code) .handler(handler) .runtime(Runtime.JAVA8) .role(role) .build(); // Create a Lambda function using a waiter CreateFunctionResponse functionResponse = awsLambda.createFunction(functionRequest); GetFunctionRequest getFunctionRequest = GetFunctionRequest.builder() .functionName(functionName) .build(); WaiterResponse<GetFunctionResponse> waiterResponse = waiter.waitUntilFunctionExists(getFunctionRequest); waiterResponse.matched().response().ifPresent(System.out::println); return functionResponse.functionArn(); } catch (LambdaException | FileNotFoundException e) { System.err.println(e.getMessage()); System.exit(1); } return ""; } public static void getFunction(LambdaClient awsLambda, String functionName) { try { GetFunctionRequest functionRequest = GetFunctionRequest.builder() .functionName(functionName) .build(); GetFunctionResponse response = awsLambda.getFunction(functionRequest); System.out.println("The runtime of this Lambda function is " + response.configuration().runtime()); } catch (LambdaException e) { System.err.println(e.getMessage()); System.exit(1); } } public static void listFunctions(LambdaClient awsLambda) { try { ListFunctionsResponse functionResult = awsLambda.listFunctions(); List<FunctionConfiguration> list = functionResult.functions(); for (FunctionConfiguration config : list) { System.out.println("The function name is " + config.functionName()); } } catch (LambdaException e) { System.err.println(e.getMessage()); System.exit(1); } } public static void invokeFunction(LambdaClient awsLambda, String functionName) { InvokeResponse res; try { // Need a SdkBytes instance for the payload. JSONObject jsonObj = new JSONObject(); jsonObj.put("inputValue", "2000"); String json = jsonObj.toString(); SdkBytes payload = SdkBytes.fromUtf8String(json); InvokeRequest request = InvokeRequest.builder() .functionName(functionName) .payload(payload) .build(); res = awsLambda.invoke(request); String value = res.payload().asUtf8String(); System.out.println(value); } catch (LambdaException e) { System.err.println(e.getMessage()); System.exit(1); } } public static void updateFunctionCode(LambdaClient awsLambda, String functionName, String bucketName, String key) { try { LambdaWaiter waiter = awsLambda.waiter(); UpdateFunctionCodeRequest functionCodeRequest = UpdateFunctionCodeRequest.builder() .functionName(functionName) .publish(true) .s3Bucket(bucketName) .s3Key(key) .build(); UpdateFunctionCodeResponse response = awsLambda.updateFunctionCode(functionCodeRequest); GetFunctionConfigurationRequest getFunctionConfigRequest = GetFunctionConfigurationRequest.builder() .functionName(functionName) .build(); WaiterResponse<GetFunctionConfigurationResponse> waiterResponse = waiter .waitUntilFunctionUpdated(getFunctionConfigRequest); waiterResponse.matched().response().ifPresent(System.out::println); System.out.println("The last modified value is " + response.lastModified()); } catch (LambdaException e) { System.err.println(e.getMessage()); System.exit(1); } } public static void updateFunctionConfiguration(LambdaClient awsLambda, String functionName, String handler) { try { UpdateFunctionConfigurationRequest configurationRequest = UpdateFunctionConfigurationRequest.builder() .functionName(functionName) .handler(handler) .runtime(Runtime.JAVA11) .build(); awsLambda.updateFunctionConfiguration(configurationRequest); } catch (LambdaException e) { System.err.println(e.getMessage()); System.exit(1); } } public static void deleteLambdaFunction(LambdaClient awsLambda, String functionName) { try { DeleteFunctionRequest request = DeleteFunctionRequest.builder() .functionName(functionName) .build(); awsLambda.deleteFunction(request); System.out.println("The " + functionName + " function was deleted"); } catch (LambdaException e) { System.err.println(e.getMessage()); System.exit(1); } } }

Serverless examples

The following code example shows how to implement a Lambda function that receives an event triggered by receiving records from a Kinesis stream. The function retrieves the Kinesis payload, decodes from Base64, and logs the record contents.

SDK for Java 2.x
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Serverless examples repository.

Consuming a Kinesis event with Lambda using Java.

// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package example; import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.LambdaLogger; import com.amazonaws.services.lambda.runtime.RequestHandler; import com.amazonaws.services.lambda.runtime.events.KinesisEvent; public class Handler implements RequestHandler<KinesisEvent, Void> { @Override public Void handleRequest(final KinesisEvent event, final Context context) { LambdaLogger logger = context.getLogger(); if (event.getRecords().isEmpty()) { logger.log("Empty Kinesis Event received"); return null; } for (KinesisEvent.KinesisEventRecord record : event.getRecords()) { try { logger.log("Processed Event with EventId: "+record.getEventID()); String data = new String(record.getKinesis().getData().array()); logger.log("Data:"+ data); // TODO: Do interesting work based on the new data } catch (Exception ex) { logger.log("An error occurred:"+ex.getMessage()); throw ex; } } logger.log("Successfully processed:"+event.getRecords().size()+" records"); return null; } }

The following code example shows how to implement a Lambda function that receives an event triggered by uploading an object to an S3 bucket. The function retrieves the S3 bucket name and object key from the event parameter and calls the Amazon S3 API to retrieve and log the content type of the object.

SDK for Java 2.x
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Serverless examples repository.

Consuming an S3 event with Lambda using Java.

// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package example; import software.amazon.awssdk.services.s3.model.HeadObjectRequest; import software.amazon.awssdk.services.s3.model.HeadObjectResponse; import software.amazon.awssdk.services.s3.S3Client; import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.RequestHandler; import com.amazonaws.services.lambda.runtime.events.S3Event; import com.amazonaws.services.lambda.runtime.events.models.s3.S3EventNotification.S3EventNotificationRecord; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Handler implements RequestHandler<S3Event, String> { private static final Logger logger = LoggerFactory.getLogger(Handler.class); @Override public String handleRequest(S3Event s3event, Context context) { try { S3EventNotificationRecord record = s3event.getRecords().get(0); String srcBucket = record.getS3().getBucket().getName(); String srcKey = record.getS3().getObject().getUrlDecodedKey(); S3Client s3Client = S3Client.builder().build(); HeadObjectResponse headObject = getHeadObject(s3Client, srcBucket, srcKey); logger.info("Successfully retrieved " + srcBucket + "/" + srcKey + " of type " + headObject.contentType()); return "Ok"; } catch (Exception e) { throw new RuntimeException(e); } } private HeadObjectResponse getHeadObject(S3Client s3Client, String bucket, String key) { HeadObjectRequest headObjectRequest = HeadObjectRequest.builder() .bucket(bucket) .key(key) .build(); return s3Client.headObject(headObjectRequest); } }

The following code example shows how to implement a Lambda function that receives an event triggered by receiving messages from an SNS topic. The function retrieves the messages from the event parameter and logs the content of each message.

SDK for Java 2.x
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Serverless examples repository.

Consuming an SNS event with Lambda using Java.

// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package example; import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.LambdaLogger; import com.amazonaws.services.lambda.runtime.RequestHandler; import com.amazonaws.services.lambda.runtime.events.SNSEvent; import com.amazonaws.services.lambda.runtime.events.SNSEvent.SNSRecord; import java.util.Iterator; import java.util.List; public class SNSEventHandler implements RequestHandler<SNSEvent, Boolean> { LambdaLogger logger; @Override public Boolean handleRequest(SNSEvent event, Context context) { logger = context.getLogger(); List<SNSRecord> records = event.getRecords(); if (!records.isEmpty()) { Iterator<SNSRecord> recordsIter = records.iterator(); while (recordsIter.hasNext()) { processRecord(recordsIter.next()); } } return Boolean.TRUE; } public void processRecord(SNSRecord record) { try { String message = record.getSNS().getMessage(); logger.log("message: " + message); } catch (Exception e) { throw new RuntimeException(e); } } }

The following code example shows how to implement a Lambda function that receives an event triggered by receiving messages from an SQS queue. The function retrieves the messages from the event parameter and logs the content of each message.

SDK for Java 2.x
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Serverless examples repository.

Consuming an SQS event with Lambda using Java.

// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.RequestHandler; import com.amazonaws.services.lambda.runtime.events.SQSEvent; import com.amazonaws.services.lambda.runtime.events.SQSEvent.SQSMessage; public class Function implements RequestHandler<SQSEvent, Void> { @Override public Void handleRequest(SQSEvent sqsEvent, Context context) { for (SQSMessage msg : sqsEvent.getRecords()) { processMessage(msg, context); } context.getLogger().log("done"); return null; } private void processMessage(SQSMessage msg, Context context) { try { context.getLogger().log("Processed message " + msg.getBody()); // TODO: Do interesting work based on the new message } catch (Exception e) { context.getLogger().log("An error occurred"); throw e; } } }

The following code example shows how to implement partial batch response for Lambda functions that receive events from a Kinesis stream. The function reports the batch item failures in the response, signaling to Lambda to retry those messages later.

SDK for Java 2.x
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Serverless examples repository.

Reporting Kinesis batch item failures with Lambda using Java.

// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.RequestHandler; import com.amazonaws.services.lambda.runtime.events.KinesisEvent; import com.amazonaws.services.lambda.runtime.events.StreamsEventResponse; import java.io.Serializable; import java.util.ArrayList; import java.util.List; public class ProcessKinesisRecords implements RequestHandler<KinesisEvent, StreamsEventResponse> { @Override public StreamsEventResponse handleRequest(KinesisEvent input, Context context) { List<StreamsEventResponse.BatchItemFailure> batchItemFailures = new ArrayList<>(); String curRecordSequenceNumber = ""; for (KinesisEvent.KinesisEventRecord kinesisEventRecord : input.getRecords()) { try { //Process your record KinesisEvent.Record kinesisRecord = kinesisEventRecord.getKinesis(); curRecordSequenceNumber = kinesisRecord.getSequenceNumber(); } catch (Exception e) { /* Since we are working with streams, we can return the failed item immediately. Lambda will immediately begin to retry processing from this failed item onwards. */ batchItemFailures.add(new StreamsEventResponse.BatchItemFailure(curRecordSequenceNumber)); return new StreamsEventResponse(batchItemFailures); } } return new StreamsEventResponse(batchItemFailures); } }

The following code example shows how to implement partial batch response for Lambda functions that receive events from a DynamoDB stream. The function reports the batch item failures in the response, signaling to Lambda to retry those messages later.

SDK for Java 2.x
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Serverless examples repository.

Reporting DynamoDB batch item failures with Lambda using Java.

// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.RequestHandler; import com.amazonaws.services.lambda.runtime.events.DynamodbEvent; import com.amazonaws.services.lambda.runtime.events.StreamsEventResponse; import com.amazonaws.services.lambda.runtime.events.models.dynamodb.StreamRecord; import java.io.Serializable; import java.util.ArrayList; import java.util.List; public class ProcessDynamodbRecords implements RequestHandler<DynamodbEvent, Serializable> { @Override public StreamsEventResponse handleRequest(DynamodbEvent input, Context context) { List<StreamsEventResponse.BatchItemFailure> batchItemFailures = new ArrayList<>(); String curRecordSequenceNumber = ""; for (DynamodbEvent.DynamodbStreamRecord dynamodbStreamRecord : input.getRecords()) { try { //Process your record StreamRecord dynamodbRecord = dynamodbStreamRecord.getDynamodb(); curRecordSequenceNumber = dynamodbRecord.getSequenceNumber(); } catch (Exception e) { /* Since we are working with streams, we can return the failed item immediately. Lambda will immediately begin to retry processing from this failed item onwards. */ batchItemFailures.add(new StreamsEventResponse.BatchItemFailure(curRecordSequenceNumber)); return new StreamsEventResponse(batchItemFailures); } } return new StreamsEventResponse(); } }

The following code example shows how to implement partial batch response for Lambda functions that receive events from an SQS queue. The function reports the batch item failures in the response, signaling to Lambda to retry those messages later.

SDK for Java 2.x
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the Serverless examples repository.

Reporting SQS batch item failures with Lambda using Java.

// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.RequestHandler; import com.amazonaws.services.lambda.runtime.events.SQSEvent; import com.amazonaws.services.lambda.runtime.events.SQSBatchResponse; import java.util.ArrayList; import java.util.List; public class ProcessSQSMessageBatch implements RequestHandler<SQSEvent, SQSBatchResponse> { @Override public SQSBatchResponse handleRequest(SQSEvent sqsEvent, Context context) { List<SQSBatchResponse.BatchItemFailure> batchItemFailures = new ArrayList<SQSBatchResponse.BatchItemFailure>(); String messageId = ""; for (SQSEvent.SQSMessage message : sqsEvent.getRecords()) { try { //process your message messageId = message.getMessageId(); } catch (Exception e) { //Add failed message identifier to the batchItemFailures list batchItemFailures.add(new SQSBatchResponse.BatchItemFailure(messageId)); } } return new SQSBatchResponse(batchItemFailures); } }