I know that when a Lambda function fails (for example when there is a time out), it tries to run the function 3 more times again. Is there any way to avoid this behavior? I\
If you are using Python, I recommend you to follow this thread.
If you are using Java, inside handleRequest
method add this lines:
ClientConfiguration config = new ClientConfiguration();
config.setMaxErrorRetry(0);
EDITED: It's now possible to change the lambda settings to disable retries (see announcement)
Original answer:
There isn't a way to disable retry behavior of Lambda functions. I suggest two options to deal with that:
If using python then need to put the code in try/catch block as well however there will be no callback. For example:
try:
do_something()
except Exception as e:
print('Error: ' + str(e))
Since the error has been handled, Lambda will not retry.
It retries when it is an unhandled failure (an error that you didn't catch) or if you handled it but still told Lambda to retry (e.g. in Node, when you call callback()
with a non-null first argument).
To stop it from retrying, you should make sure that any error is handled and you tell Lambda that your invocation finished successfully by returning a non-error (or in Node, calling callback(null, <any>)
.
To do this you can enclose the entire body of your handler function with a try-catch.
module.exports.handler(event, context, callback) {
try {
// Do you what you want to do.
return callback(null, 'Success')
} catch (err) {
// You probably still want to log it.
console.error(err)
// Return happy despite all the hardships you went through.
return callback(null, 'Still success')
}
}
As for failures due to timeouts there are things you can do.
If it times out outside of your handler, there's usually something wrong with your code (e.g. incorrect database config, etc) that you should look at.
If it times out inside your handler during an invocation, there is something you can do about it.
context.getRemainingTimeInMillis()
to know if the Lambda is about to timeout, so you can handle it earlier.Use below code to identify and stop retry when there is a failure.
exports.handler = (event, context, callback) => {
context.callbackWaitsForEmptyEventLoop = false;
let lastReqId;
if (lastReqId == context.awsRequestId) {
console.log("Lambda auto retry detected. Aborting");// you can write your own logic to decide what to do with the failure data
return context.succeed();
} else {
console.log("new context");
lastReqId = context.awsRequestId;
}
};
you can read more about it here
Since November 2019, it is possible to set the retry count to 0.
That means the lambda will not be retried on error.