Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - How handle timeouts gracefully in AWS Lambda

Tags:

I have a lambda that I require to gracefully shutdown and log to an external system. After looking some literature on the matter, I reached the following solution using threading:

def lambda_handler(event, context):

    threshold_millis = 10 * 1000  # leave when there are only 10 seconds left
    que = queue.Queue()
    t = threading.Thread(target=lambda q, ev: q.put(do_work(ev)), args=(que, event))
    t.daemon = True
    t.start()

    while True:
        if context.get_remaining_time_in_millis() < threshold_millis:
            # Do some logging notifying the timeout
            return {
                "isBase64Encoded": False,
                "statusCode": 408,
                "headers": {'Content-Type': "application/json"},
                "body": "Request timed out"
            }

        elif not t.isAlive():
            response = que.get()
            return response

        time.sleep(1)

Although it works I was wondering: is there any better practice than this one to gracefully handle timeouts in AWS Lambda?

like image 850
David Jiménez Martínez Avatar asked May 23 '18 08:05

David Jiménez Martínez


1 Answers

Watching get_remaining_time_in_millis is the best/recommended way of preempting a timeout in lambda; there are no special events that get invoked to let you know you're going to timeout.

Without knowing the specifics, you could infer a timeout on the client side by looking at how long it took for you to receive an error. However I would prefer your solution of having the lambda be explicit about it.

like image 87
thomasmichaelwallace Avatar answered Oct 11 '22 23:10

thomasmichaelwallace