AWS client not reused in a Lambda function Medium

Recreating AWS clients from scratch in each Lambda function invocation is expensive and can lead to availability risks. Clients should be cached across invocations.

Detector ID

Noncompliant example

1def lambda_handler_noncompliant(event, context):
2    import boto3
3    # Noncompliant: recreates AWS clients in each lambda invocation.
4    client = boto3.client('s3')
5    response = client.list_buckets()

Compliant example

1import boto3
2client = boto3.client('s3')
5def lambda_handler_compliant(event, context):
6    # Compliant: uses the cached client.
7    response = client.list_buckets()