There is a piece of interesting information in the AWS Lambda Developer Guide that I think deserves further investigation.
Background processes or callbacks initiated by your Lambda function that did not complete when the function ended resume if AWS Lambda chooses to reuse the execution context.
A quick refresher
Lambda executes functions inside containers which isolate them from one another. These containers are lightweight Firecracker microVMs, not Kubernetes or Docker containers. Each time you execute your function, Lambda may create a new container or reuse an existing one. When a new container is created it’s called a cold start. Conversely, reusing a container is called a warm start, which we’ll be discussing.
Below is the function I started my investigation with. It’s written in C# but the outcome should be the same regardless of language.
The constructor generates a GUID and starts a new thread that runs the
Background logs the GUID and an incrementing counter’s value once every second.
Lambda will call the
EntryPoint method which sleeps for a couple of seconds before returning.
According to the development guide, the
Background thread will be paused between executions.
After running multiple executions, I checked the CloudWatch logs and found that it’s true!
Despite having 5–31 seconds between executions, the GUID remains the same and the counter increments across executions.
We can go one step further and use the
Stopwatch class to see how long the thread is actually sleeping for.
The logs show that the thread is sleeping much longer than it’s supposed to. We can now see the time spent paused between executions.
As interesting as it is, I’m not sure how useful pausing and resuming threads actually is. Can you think of a case where you would want this? If so, please let me know in the comments!
One last thing. Remember that it’s Lambda’s prerogative to create a new container. You shouldn’t expect your function to run on a warm container; you should just be happy when it does.