Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle timeouts in a python lambda?

I know this has been questioned before, but no real solution was proposed and I was wondering if there any new ways nowadays.

Is there anyway to hook an event using any AWS service to check if a lambda has timed out? I mean it logs into the CloudWatch logs that it timed out so there must be a way.

Specifically in Python because its not so simple to keep checking if its reaching the 20 minute mark as you can with Javascript and other naturally concurrent languages.

Ideally I want to execute a lambda if the python lambda times out, with the same payload the original one received.

like image 407
Mojimi Avatar asked Jul 29 '19 17:07

Mojimi


People also ask

What happens when Lambda timeouts?

Note: When a Lambda function invocation times out, a Task timed out error message appears in the failed invocation's CloudWatch logs, not an Error message. If you search your function's CloudWatch logs for Error messages only, then the search returns only code-related runtime errors, not invocation timeout errors.

What is the most likely issue with the Lambda function timeout?

Finding the root cause of the timeout. There are many reasons why a function might time out, but the most likely is that it was waiting on an IO operation to complete.


1 Answers

Here's an example from cloudformation-custom-resources/lambda/python · GitHub showing how an AWS Lambda function written in Python can realise that it is about to timeout.

(I've edited out the other stuff, here's the relevant bits):

import signal

def handler(event, context):

    # Setup alarm for remaining runtime minus a second
    signal.alarm((context.get_remaining_time_in_millis() / 1000) - 1)

    # Do other stuff
    ...

def timeout_handler(_signal, _frame):
    '''Handle SIGALRM'''
    raise Exception('Time exceeded')

signal.signal(signal.SIGALRM, timeout_handler)
like image 121
John Rotenstein Avatar answered Oct 08 '22 09:10

John Rotenstein