fix(lambda): back off DynamoDB Streams retries and expire aged records (#3613)

* fix(lambda): back off DynamoDB Streams ESM retries and enforce MaximumRecordAgeInSeconds

* fix(lambda): treat unset MaximumRecordAgeInSeconds as no age cutoff

Keep expired records retrying when no finite Lambda age limit is configured.
This commit is contained in:
Chris Jovanovski authored and GitHub committed 2026-09-15 21:46:27 -04:00
1 parent 265344e304
commit 86072aaa84
7 files changed
+291 -30

No files matched your search

@@ -39,6 +39,7 @@ import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.function.LongSupplier;
@ApplicationScoped
public class DynamoDbStreamsEventSourcePoller implements Resettable {
@@ -51,6 +52,7 @@ public class DynamoDbStreamsEventSourcePoller implements Resettable {
/** Raised by the stream when a stored checkpoint has aged out of the retained window. */
private static final String TRIMMED_DATA_ACCESS_EXCEPTION = "TrimmedDataAccessException";
static final long MAX_RETRY_BACKOFF_MS = 60_000;
private final Vertx vertx;
private final DynamoDbStreamService streamService;
@@ -64,9 +66,11 @@ public class DynamoDbStreamsEventSourcePoller implements Resettable {
private final S3Service s3Service;
private final String baseUrl;
private final long pollIntervalMs;
private final LongSupplier clock;
private final ConcurrentHashMap<String, Long> timerIds = new ConcurrentHashMap<>();
final ConcurrentHashMap<String, Boolean> activePolls = new ConcurrentHashMap<>();
private final ConcurrentHashMap<String, Integer> retryCounts = new ConcurrentHashMap<>();
private final ConcurrentHashMap<String, Long> retryNotBefore = new ConcurrentHashMap<>();
private final ExecutorService pollExecutor = Executors.newCachedThreadPool(r -> {
Thread t = new Thread(r, "dynamodb-streams-esm-poller");
t.setDaemon(true);
@@ -84,6 +88,21 @@ public class DynamoDbStreamsEventSourcePoller implements Resettable {
SqsService sqsService,
SnsService snsService,
S3Service s3Service) {
this(vertx, streamService, executorService, functionStore, esmStore, objectMapper, config,
filterMatcher, sqsService, snsService, s3Service, System::currentTimeMillis);
}
DynamoDbStreamsEventSourcePoller(Vertx vertx, DynamoDbStreamService streamService,
LambdaExecutorService executorService,
LambdaFunctionStore functionStore,
EsmStore esmStore,
ObjectMapper objectMapper,
EmulatorConfig config,
PipesFilterMatcher filterMatcher,
SqsService sqsService,
SnsService snsService,
S3Service s3Service,
LongSupplier clock) {
this.vertx = vertx;
this.streamService = streamService;
this.executorService = executorService;
@@ -96,6 +115,7 @@ public class DynamoDbStreamsEventSourcePoller implements Resettable {
this.sqsService = sqsService;
this.snsService = snsService;
this.s3Service = s3Service;
this.clock = clock;
}
public void startPersistedPollers() {
@@ -145,6 +165,7 @@ public class DynamoDbStreamsEventSourcePoller implements Resettable {
timerIds.clear();
activePolls.clear();
retryCounts.clear();
retryNotBefore.clear();
}
public void startPolling(EventSourceMapping esm) {
@@ -170,6 +191,7 @@ public class DynamoDbStreamsEventSourcePoller implements Resettable {
LOG.debugv("Stopped DynamoDB Streams polling for ESM {0}", uuid);
}
retryCounts.keySet().removeIf(k -> k.startsWith(uuid + ":"));
retryNotBefore.keySet().removeIf(k -> k.startsWith(uuid + ":"));
}
@@ -241,6 +263,13 @@ public class DynamoDbStreamsEventSourcePoller implements Resettable {
return;
}
String checkpointSeq = (lastSeq == null || checkpointTrimmed) ? "TRIM_HORIZON" : lastSeq;
String batchKey = esm.getUuid() + ":" + shardId + ":" + checkpointSeq;
long now = clock.getAsLong();
if (now < retryNotBefore.getOrDefault(batchKey, 0L)) {
return;
}
LOG.infov("DynamoDB Streams ESM {0}: delivering {1} of {2} record(s) to {3}",
esm.getUuid(), matched.size(), records.size(), esm.getFunctionName());
@@ -257,14 +286,13 @@ public class DynamoDbStreamsEventSourcePoller implements Resettable {
throw e;
}
String checkpointSeq = (lastSeq == null || checkpointTrimmed) ? "TRIM_HORIZON" : lastSeq;
String batchKey = esm.getUuid() + ":" + shardId + ":" + checkpointSeq;
CheckpointOutcome outcome = invokeResult.getFunctionError() == null
? successfulInvocationCheckpoint(esm, invokeResult, lastSeq, records, matched)
: new CheckpointOutcome(null, 0);
if (outcome.lowestFailedIndex() == records.size()) {
retryCounts.remove(batchKey);
retryNotBefore.remove(batchKey);
advanceCheckpoint(esm, shardId, outcome.checkpoint());
} else if (outcome.lowestFailedIndex() > 0) {
retryCounts.remove(batchKey);
@@ -273,28 +301,39 @@ public class DynamoDbStreamsEventSourcePoller implements Resettable {
String nextBatchKey = esm.getUuid() + ":" + shardId + ":" + nextCheckpoint;
Integer maxRetries = esm.getMaximumRetryAttempts();
int currentRetries = retryCounts.merge(nextBatchKey, 1, Integer::sum);
Set<String> deliveredSeqs = new HashSet<>();
for (DynamoDbStreamRecord rec : matched) {
deliveredSeqs.add(rec.getSequenceNumber());
}
List<DynamoDbStreamRecord> failedRecords = new ArrayList<>();
for (int i = outcome.lowestFailedIndex(); i < records.size(); i++) {
DynamoDbStreamRecord rec = records.get(i);
if (deliveredSeqs.contains(rec.getSequenceNumber())) {
failedRecords.add(rec);
}
}
if (failedRecords.isEmpty()) {
failedRecords = records.subList(outcome.lowestFailedIndex(), records.size());
}
if (maxRetries != null && maxRetries >= 0 && currentRetries > maxRetries) {
if (hasExceededMaximumRecordAge(esm, failedRecords, now)) {
LOG.warnv("DynamoDB Streams ESM {0}: maximum record age exceeded for batch ending at {1}",
esm.getUuid(), newestFetchedSeq);
sendToOnFailureDestination(esm, shardId, failedRecords, invokeResult, currentRetries,
"MaximumRecordAgeExceeded");
retryCounts.remove(nextBatchKey);
retryNotBefore.remove(nextBatchKey);
advanceCheckpoint(esm, shardId, newestFetchedSeq);
} else if (maxRetries != null && maxRetries >= 0 && currentRetries > maxRetries) {
LOG.warnv("DynamoDB Streams ESM {0}: maximum retry attempts ({1}) exhausted for batch ending at {2}",
esm.getUuid(), maxRetries, newestFetchedSeq);
Set<String> deliveredSeqs = new HashSet<>();
for (DynamoDbStreamRecord rec : matched) {
deliveredSeqs.add(rec.getSequenceNumber());
}
List<DynamoDbStreamRecord> failedRecords = new ArrayList<>();
for (int i = outcome.lowestFailedIndex(); i < records.size(); i++) {
DynamoDbStreamRecord rec = records.get(i);
if (deliveredSeqs.contains(rec.getSequenceNumber())) {
failedRecords.add(rec);
}
}
if (failedRecords.isEmpty()) {
failedRecords = records.subList(outcome.lowestFailedIndex(), records.size());
}
sendToOnFailureDestination(esm, shardId, failedRecords, invokeResult, currentRetries);
sendToOnFailureDestination(esm, shardId, failedRecords, invokeResult, currentRetries,
"RetryAttemptsExhausted");
retryCounts.remove(nextBatchKey);
retryNotBefore.remove(nextBatchKey);
advanceCheckpoint(esm, shardId, newestFetchedSeq);
} else {
retryNotBefore.put(nextBatchKey, now + retryBackoffMs(currentRetries));
LOG.warnv("DynamoDB Streams ESM {0}: Lambda returned error [batchItemFailures], retry {1}, records will be retried",
esm.getUuid(), currentRetries);
advanceCheckpoint(esm, shardId, nextCheckpoint);
@@ -302,13 +341,24 @@ public class DynamoDbStreamsEventSourcePoller implements Resettable {
} else {
Integer maxRetries = esm.getMaximumRetryAttempts();
int currentRetries = retryCounts.merge(batchKey, 1, Integer::sum);
if (maxRetries != null && maxRetries >= 0 && currentRetries > maxRetries) {
if (hasExceededMaximumRecordAge(esm, matched, now)) {
LOG.warnv("DynamoDB Streams ESM {0}: maximum record age exceeded for batch ending at {1}",
esm.getUuid(), newestFetchedSeq);
sendToOnFailureDestination(esm, shardId, matched, invokeResult, currentRetries,
"MaximumRecordAgeExceeded");
retryCounts.remove(batchKey);
retryNotBefore.remove(batchKey);
advanceCheckpoint(esm, shardId, newestFetchedSeq);
} else if (maxRetries != null && maxRetries >= 0 && currentRetries > maxRetries) {
LOG.warnv("DynamoDB Streams ESM {0}: maximum retry attempts ({1}) exhausted for batch ending at {2}",
esm.getUuid(), maxRetries, newestFetchedSeq);
sendToOnFailureDestination(esm, shardId, matched, invokeResult, currentRetries);
sendToOnFailureDestination(esm, shardId, matched, invokeResult, currentRetries,
"RetryAttemptsExhausted");
retryCounts.remove(batchKey);
retryNotBefore.remove(batchKey);
advanceCheckpoint(esm, shardId, newestFetchedSeq);
} else {
retryNotBefore.put(batchKey, now + retryBackoffMs(currentRetries));
String error = invokeResult.getFunctionError() != null
? invokeResult.getFunctionError()
: "batchItemFailures";
@@ -399,10 +449,34 @@ public class DynamoDbStreamsEventSourcePoller implements Resettable {
return previousCheckpoint;
}
private boolean hasExceededMaximumRecordAge(EventSourceMapping esm, List<DynamoDbStreamRecord> records,
long now) {
Integer configuredAge = esm.getMaximumRecordAgeInSeconds();
if (configuredAge == null || configuredAge <= 0) {
return false;
}
long oldestRecordSeconds = records.stream()
.mapToLong(DynamoDbStreamRecord::getApproximateCreationDateTime)
.filter(seconds -> seconds > 0)
.min()
.orElse(0);
if (oldestRecordSeconds == 0) {
return false;
}
return now - oldestRecordSeconds * 1_000 >= configuredAge * 1_000L;
}
long retryBackoffMs(int retries) {
int doublings = Math.min(retries, 16);
return Math.min(pollIntervalMs * (1L << doublings), MAX_RETRY_BACKOFF_MS);
}
private void sendToOnFailureDestination(EventSourceMapping esm, String shardId,
List<DynamoDbStreamRecord> records,
InvokeResult invokeResult,
int invokeCount) {
int invokeCount,
String condition) {
if (esm.getDestinationConfig() == null || esm.getDestinationConfig().getOnFailure() == null) {
return;
}
@@ -415,12 +489,12 @@ public class DynamoDbStreamsEventSourcePoller implements Resettable {
if (destinationArn.contains(":sqs:")) {
String region = AwsArnUtils.regionOrDefault(destinationArn, esm.getRegion());
String queueUrl = AwsArnUtils.arnToQueueUrl(destinationArn, baseUrl);
String payload = buildOnFailurePayload(esm, shardId, records, invokeResult, invokeCount);
String payload = buildOnFailurePayload(esm, shardId, records, invokeResult, invokeCount, condition);
sqsService.sendMessage(queueUrl, payload, 0, region);
LOG.infov("DynamoDB Streams ESM {0}: sent failed batch to SQS DLQ {1}", esm.getUuid(), destinationArn);
} else if (destinationArn.contains(":sns:")) {
String region = AwsArnUtils.regionOrDefault(destinationArn, esm.getRegion());
String payload = buildOnFailurePayload(esm, shardId, records, invokeResult, invokeCount);
String payload = buildOnFailurePayload(esm, shardId, records, invokeResult, invokeCount, condition);
snsService.publish(destinationArn, null, payload, "ESM OnFailure", region);
LOG.infov("DynamoDB Streams ESM {0}: sent failed batch to SNS DLQ {1}", esm.getUuid(), destinationArn);
} else if (destinationArn.contains(":s3:")) {
@@ -429,7 +503,7 @@ public class DynamoDbStreamsEventSourcePoller implements Resettable {
throw new IllegalArgumentException("Invalid S3 destination ARN: " + destinationArn);
}
String key = buildS3OnFailureKey(esm.getUuid(), shardId, Instant.now(), UUID.randomUUID());
String s3Payload = buildS3OnFailurePayload(esm, shardId, records, invokeResult, invokeCount);
String s3Payload = buildS3OnFailurePayload(esm, shardId, records, invokeResult, invokeCount, condition);
RequestScopes.runAs(esm.getAccountId(), () ->
s3Service.putObject(arn.resource(), key,
s3Payload.getBytes(StandardCharsets.UTF_8),
@@ -449,10 +523,11 @@ public class DynamoDbStreamsEventSourcePoller implements Resettable {
private String buildS3OnFailurePayload(EventSourceMapping esm, String shardId,
List<DynamoDbStreamRecord> records,
InvokeResult invokeResult,
int invokeCount) {
int invokeCount,
String condition) {
try {
ObjectNode root = (ObjectNode) objectMapper.readTree(
buildOnFailurePayload(esm, shardId, records, invokeResult, invokeCount));
buildOnFailurePayload(esm, shardId, records, invokeResult, invokeCount, condition));
root.put("payload", buildDynamoDbEvent(records, esm));
return objectMapper.writeValueAsString(root);
} catch (Exception e) {
@@ -469,7 +544,8 @@ public class DynamoDbStreamsEventSourcePoller implements Resettable {
private String buildOnFailurePayload(EventSourceMapping esm, String shardId,
List<DynamoDbStreamRecord> records,
InvokeResult invokeResult,
int invokeCount) {
int invokeCount,
String condition) {
try {
ObjectNode root = objectMapper.createObjectNode();
root.put("version", "1.0");
@@ -478,7 +554,7 @@ public class DynamoDbStreamsEventSourcePoller implements Resettable {
ObjectNode requestContext = root.putObject("requestContext");
requestContext.put("requestId", invokeResult.getRequestId() != null ? invokeResult.getRequestId() : "");
requestContext.put("functionArn", esm.getFunctionArn() != null ? esm.getFunctionArn() : "");
requestContext.put("condition", "RetryAttemptsExhausted");
requestContext.put("condition", condition);
requestContext.put("approximateInvokeCount", invokeCount);
ObjectNode responseContext = root.putObject("responseContext");
@@ -372,6 +372,9 @@ public class LambdaController {
if (esm.getMaximumRetryAttempts() != null) {
node.put("MaximumRetryAttempts", esm.getMaximumRetryAttempts());
}
if (esm.getMaximumRecordAgeInSeconds() != null) {
node.put("MaximumRecordAgeInSeconds", esm.getMaximumRecordAgeInSeconds());
}
if (esm.getDestinationConfig() != null && esm.getDestinationConfig().getOnFailure() != null) {
ObjectNode destinationConfig = node.putObject("DestinationConfig");
@@ -1320,6 +1320,7 @@ public class LambdaService implements ResourceProvider {
: null;
Integer maximumRetryAttempts = parseMaximumRetryAttempts(request);
Integer maximumRecordAgeInSeconds = parseMaximumRecordAgeInSeconds(request);
EventSourceMapping.DestinationConfig destinationConfig = parseDestinationConfig(request);
@@ -1347,6 +1348,7 @@ public class LambdaService implements ResourceProvider {
esm.setFunctionResponseTypes(functionResponseTypes);
esm.setBisectBatchOnFunctionError(bisectBatchOnFunctionError);
esm.setMaximumRetryAttempts(maximumRetryAttempts);
esm.setMaximumRecordAgeInSeconds(maximumRecordAgeInSeconds);
esm.setDestinationConfig(destinationConfig);
esm.setFilterCriteria(filterCriteria);
esm.setStartingPosition(startingPosition.position());
@@ -1752,6 +1754,28 @@ public class LambdaService implements ResourceProvider {
return (int) value;
}
private Integer parseMaximumRecordAgeInSeconds(Map<String, Object> request) {
Object raw = request.get("MaximumRecordAgeInSeconds");
if (raw == null) {
return null;
}
if (!(raw instanceof Number)) {
throw new AwsException("InvalidParameterValueException",
"MaximumRecordAgeInSeconds must be a numeric value", 400);
}
double d = ((Number) raw).doubleValue();
if (Double.isNaN(d) || Double.isInfinite(d) || d != Math.floor(d)) {
throw new AwsException("InvalidParameterValueException",
"MaximumRecordAgeInSeconds must be an integer", 400);
}
long value = ((Number) raw).longValue();
if (value != -1 && (value < 60 || value > 604800)) {
throw new AwsException("InvalidParameterValueException",
"MaximumRecordAgeInSeconds must be -1 or between 60 and 604800 (got " + value + ")", 400);
}
return (int) value;
}
private void startPollingHelper(EventSourceMapping esm) {
if (esm.getEventSourceArn() == null) {
return;
@@ -1826,6 +1850,9 @@ public class LambdaService implements ResourceProvider {
if (request.containsKey("MaximumRetryAttempts")) {
esm.setMaximumRetryAttempts(parseMaximumRetryAttempts(request));
}
if (request.containsKey("MaximumRecordAgeInSeconds")) {
esm.setMaximumRecordAgeInSeconds(parseMaximumRecordAgeInSeconds(request));
}
if (request.containsKey("DestinationConfig")) {
esm.setDestinationConfig(parseDestinationConfig(request));
@@ -32,6 +32,7 @@ public class EventSourceMapping {
private ScalingConfig scalingConfig;
private Boolean bisectBatchOnFunctionError;
private Integer maximumRetryAttempts;
private Integer maximumRecordAgeInSeconds;
private DestinationConfig destinationConfig;
private FilterCriteria filterCriteria;
private Map<String, Object> selfManagedEventSource;
@@ -127,6 +128,14 @@ public class EventSourceMapping {
this.maximumRetryAttempts = maximumRetryAttempts;
}
public Integer getMaximumRecordAgeInSeconds() {
return maximumRecordAgeInSeconds;
}
public void setMaximumRecordAgeInSeconds(Integer maximumRecordAgeInSeconds) {
this.maximumRecordAgeInSeconds = maximumRecordAgeInSeconds;
}
public DestinationConfig getDestinationConfig() {
return destinationConfig;
}