
Stop Using Default Arguments in AWS Lambda Functions
Discover why your AWS Lambda costs might be spiralling out of control due to a common Python programming practice.

user_cache
as an empty dictionary and settings
with default TTL and max items values. The function checks if the user ID exists in the cache, and if not, it fetches and processes the data, stores it in the cache, and returns the result.- In Python, default arguments are evaluated when the function is defined, not when it's called.
- All invocations of the function share the same dictionary objects for
user_cache
andsettings
. - This leads to unexpected behavior and memory leaks in the Lambda environment.

- Memory usage grows linearly with each new user, but memory isn't released between invocations.
- Concurrent invocations can lead to inconsistent user experiences due to different cache states.

None
. When the function runs, we check if the arguments are None
and initialize new dictionaries if needed. This ensures that each invocation gets its own fresh copies of the cache and settings dictionaries, eliminating the risk of shared state, memory leaks, and inconsistent behavior with concurrent executions.- Use
None
as the default value for mutable arguments. - Initialize new dictionaries within the function if the arguments are
None
. - This ensures each invocation gets its own fresh copies of the cache and settings.

@metrics.log_metrics
decorator ensures that all our custom metrics are sent to CloudWatch, while the @tracer.capture_lambda_handler
decorator adds distributed tracing capability, helping us understand the end-to-end execution flow of our Lambda function.- Use AWS Lambda Powertools to simplify the implementation of AWS Lambda best practices.
- Log metrics and trace execution for better monitoring and debugging.
Any opinions in this post are those of the individual author and may not reflect the opinions of AWS.