Thunderbolt Engineer
Thunderbolt Engineer

Reputation: 1563

What happens if timeout handler is not cancelled inside lambda function?

I have a lambda function that sets timeout handler with a certain delay (60 seconds) at the beginning. I 'd like to know what is the exact behavior of lambda when the timeout handler is not cancelled till the lambda returns response (in less than 60 seconds). Especially, when there are hundreds of lambda invocation, the uncancelled timeout handler in the previous lambda execution will affect the next process that runs on the same instance? More info - lambda function is invoked asynchronously.

Upvotes: 1

Views: 604

Answers (2)

saart
saart

Reputation: 402

As you wrote in the comments, the lambda is written in python. This simple example shows that the event is passing to the next invocation:

The code:

import json
import signal 
import random

def delayed(val):
    print("Delayed:", val)

def lambda_handler(event, context):
    r = random.random()
    print("Generated", r)
    signal.signal(signal.SIGALRM, lambda *args: delayed(r))
    signal.setitimer(signal.ITIMER_REAL, 1)
    return {'statusCode': 200}

Yields: Cloudwatch logs

Think about the way that AWS implements lambdas: When a lambda is being invoked, a container is being raised and the environment starts to initialize (this is the cold-start phase). During this initialization, the python interpreter is starting, and behind the scene, an AWS code fetches events from the lambda service and triggers your handler. This initialization is costly, so AWS prefers to wait with the same "process" for the next event. On the happy flow, it arrives "fast enough" after the previous finished, so they spared the initialization and everyone is happy. Otherwise, after a small period, they will shutdown the container. As long as the interpreter is still on - the signal that we fired in one invocation will leak to the next invocation.

Note also the concurrency of the lambdas - two invocations that run in parallel are running on different containers, thus have different interpreters and this alarm will not leak.

Upvotes: 0

jarmod
jarmod

Reputation: 78918

You haven't mentioned which language you're using or provided any code indicating how you're creating timeouts, but the general process is described at AWS Lambda execution environment.

Lambda freezes the execution environment following an invocation and it remains frozen, up to a certain maximum amount of time (15 mins afaik), and is thawed if a new invocation happens quickly enough, and the prior execution environment is re-used.

A key quote from the documentation is:

Background processes or callbacks that were initiated by your Lambda function and did not complete when the function ended [will] resume if Lambda reuses the execution environment. Make sure that any background processes or callbacks in your code are complete before the code exits.

Upvotes: 3

Related Questions