To prevent duplicate processing caused by Lambda retries or failed batches, use the Powertools Idempotency utility. The @Idempotent annotation ensures that a specific operation is only executed once for a given input by tracking the result in a persistence store (like DynamoDB).
- Configure the
Idempotency utility with a PersistenceStore (e.g., DynamoDBPersistenceStore) in your handler constructor. - Annotate the specific method performing the business logic with
@Idempotent.
The utility uses the JSON representation of the input object to identify unique messages.
public class IdempotentKafkaHandler implements RequestHandler<ConsumerRecords<String, Payment>, String> {
public IdempotentKafkaHandler() {
Idempotency.config()
.withPersistenceStore(
DynamoDBPersistenceStore.builder()
.withTableName("IdempotencyTable")
.build())
.configure();
}
@Override
@Logging
@Deserialization(type = DeserializationType.KAFKA_JSON)
public String handleRequest(ConsumerRecords<String, Payment> records, Context context) {
for (ConsumerRecord<String, Payment> record : records) {
Payment payment = record.value();
processPayment(payment);
}
return "OK";
}
@Idempotent
private void processPayment(Payment payment) {
// Business logic here
PaymentService.process(payment.getPaymentId(), payment.getCustomerId(), payment.getAmount());
}
}