Created
May 2, 2024 00:52
-
-
Save zb-sj/b034bbc02390320b80cd559f78943675 to your computer and use it in GitHub Desktop.
ApproximateReceiveCount limit on SqsPartialBatch
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// implementation poc for https://github.com/middyjs/middy/issues/1206 | |
const approximateReceiveLimit = 3; | |
export const handler = middy<SQSEvent> | |
// ... | |
.use({ | |
/** | |
* Filter out messages that have been retried 3 times | |
* | |
* @remarks must be placed before the `@middy/sqs-partial-batch-failure` middleware | |
*/ | |
after(request: middy.Request<SQSEvent, SQSBatchResponse>) { | |
if (!request.response) { | |
throw new Error("response is not set. It's a bug in the middleware chain"); | |
} | |
const records = request.event.Records.reduce( | |
(m, r) => | |
Object.assign(m, { | |
[r.messageId]: r, | |
}), | |
{} as Record<string, SQSRecord> | |
); | |
request.response.batchItemFailures = request.response.batchItemFailures.filter(({ itemIdentifier }) => { | |
const record = records[itemIdentifier]!; | |
const shouldRetry = parseInt(record.attributes.ApproximateReceiveCount) < approximateReceiveLimit; | |
if (!shouldRetry) { | |
console.warn(`Failed to process message ${itemIdentifier} after ${approximateReceiveLimit} retries`, record); | |
} | |
return shouldRetry; | |
}); | |
}, | |
}) | |
.use(sqsPartialBatchFailure()) | |
// ... |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment