AWS Lambda: Instances and start types
In this article, we will continue our discussion about lambda functions. Specifically, we will delve into lambda instances, start types, and their relationship.
Hello world lambda
To better understand which code is executed, let's examine a simple 'Hello World' lambda code in Python. The code includes a counter, which we will use to demonstrate the concepts of lambda instances and start types.
Here is the Python code:
# Initialize a counter
count = 0
# Handler method
def handler(event, context):
# Increase counter on every execution
count = count + 1
# Print the count for visibility
print(count)
I will be using this lambda code in the explanations that are coming next.
Lambda cold start
When your lambda function is first deployed or is not invoked for a long time, it is called a cold start. During a cold start, AWS first loads your lambda code and all libraries into memory interprets them, executes them, and builds your lambda instance.
You might wonder what code is executed during a cold start. In a Python execution environment, code outside the handler method is executed during the cold start process. Therefore, AWS creates and initializes the `count` variable during this initialization execution.
The cold start time, or init time, is logged separately in lambda logs. At the end of each lambda execution, AWS will log the so-called report log line, and in it, you may notice the `Init time: Nms`.
Cold start can increase the overall execution time of a lambda function, which is crucial in time-sensitive environments. Therefore, minimizing the number of cold starts or cold start duration is essential to ensure optimal performance.
Lambda handler method
Once the lambda instance is built and ready to handle the execution request, AWS will call the `handler` method on a prepared lambda instance. The time taken by handler method execution counts as the primary execution time.
Lambda instance reuse
If your lambda is not executing at the moment but has just been invoked, AWS keeps a lambda instance for a little while. Therefore, you can immediately invoke your lambda again, and AWS will execute the handler method only. In this scenario, we call the lambda function in a hot state. As a result, we can expect the count to be greater than one.