This Lambda function demonstrates a classic Mutable Default Argument Bug
- The
process_user_data()function hasmetadata=[]as a default parameter. - In Python, default arguments are evaluated only once when the function is defined.
- The same list object is reused across all function calls, causing data to accumulate unexpectedly.
- In case of Lambda this continues as long as the same execution environment is serving the requests.
When you call your Lambda function URL:
- First call:
resultwill have 1 item - Second call:
resultwill have 2 items (including the first call's data!) - Each subsequent Lambda invocation: The list keeps growing within that container instance
- Call your function URL:
https://your-function-url/?user_id=john - Refresh the page multiple times - watch the list grow!
- The bug persists until the Lambda container is recycled
def process_user_data(user_id, metadata=None):
if metadata is None:
metadata = []
# ... rest of function-
Deploy the SAM template:
aws cloudformation deploy --template-file template-bug.yaml --stack-name lambda-debug-demo --capabilities CAPABILITY_AUTO_EXPAND CAPABILITY_IAM CAPABILITY_NAMED_IAM
-
Get the function URL from the outputs and test the bug by calling it multiple times
-
Observe how the metadata list grows with each invocation within the same container lifecycle