Writing Code for AWS Lambda—Statelessness and Reuse - Serverless Architectures with AWS Lambda

Writing Code for AWS Lambda—Statelessness and Reuse

It’s important to understand the central tenant when writing code for Lambda: your code cannot make assumptions about state. This is because Lambda fully manages when a new function container will be created and invoked for the first time. A container could be getting invoked for the first time for a number of reasons. For example, the events triggering your Lambda function are increasing in concurrency beyond the number of containers previously created for your function, an event is triggering your Lambda function for the first time in several minutes, etc. While Lambda is responsible for scaling your function containers up and down to meet actual demand, your code needs to be able to operate accordingly. Although Lambda won’t interrupt the processing of a specific invocation that’s already in flight, your code doesn’t need to account for that level of volatility.

This means that your code cannot make any assumptions that state will be preserved from one invocation to the next. However, each time a function container is created and invoked, it remains active and available for subsequent invocations for at least a few minutes before it is terminated. When subsequent invocations occur on a container that has already been active and invoked at least once before, we say that invocation is running on a warm container. When an invocation occurs for a Lambda function that requires your function code package to be created and invoked for the first time, we say the invocation is experiencing a cold start.



Invocations of warm function containers and cold
        function containers

Figure 3: Invocations of warm function containers and cold function containers

Depending on the logic your code is executing, understanding how your code can take advantage of a warm container can result in faster code execution inside of Lambda. This, in turn, results in quicker responses and lower cost. For more details and examples of how to improve your Lambda function performance by taking advantage of warm containers, see the Best Practices section later in this whitepaper.

Overall, each language that Lambda supports has its own model for packaging source code and possibilities for optimizing it. Visit this page to get started with each of the supported languages.