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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With