We all love serverless especially when it comes to AWS LAMBDA functions.

There are good reasons to do so for event-driven, decoupling, automation and many other reasons that time aws lambda was released.

But there can be situations when our dear friend LAMBDA can turn in to a foe and cost us money, downtime and those times are unintentional recursive Loops.
In this blog we will talk about a very simple feature yet a powerful one, recursive loop detection between aws lambda and s3 bucket.

Motivation

What is AWS lambda recursive loop and loop detection?

What does it mean for you?

THIS IS THE EXACT PROBLEM AWS LAMBDA LOOP DETECTION TRIES TO SOLVE.

What this Update mean for you?

How Lambda detects loop

You can learn more about here.

Let’s see it in Action.


import boto3
import os
import random
import string

def lambda_handler(event, context):
    # Define the S3 bucket
    s3_bucket = 'your-s3-bucket-name'  # Replace with your S3 bucket name

    # Generate a random string to append to the file name
    random_string = ''.join(random.choices(string.ascii_lowercase + string.digits, k=6))

    # Define the file content and key (with random string appended)
    s3_key = f'your-file-{random_string}.txt'  # The key (path) of the file in S3
    file_content = "Hello, this is a sample text file created by Lambda with a random suffix!"

    # Create the file locally in the /tmp directory
    local_file_path = '/tmp/sample_file.txt'

    # Write content to the file
    with open(local_file_path, 'w') as file:
        file.write(file_content)

    # Initialize S3 client
    s3 = boto3.client('s3')

    # Upload the file to S3
    try:
        s3.upload_file(local_file_path, s3_bucket, s3_key)
        return {
            'statusCode': 200,
            'body': f"File successfully uploaded to {s3_bucket}/{s3_key}"
        }
    except Exception as e:
        return {
            'statusCode': 500,
            'body': f"Error uploading file: {str(e)}"
        }

Ways to Receive notification for Loop detection

The CloudWatch metric RecursiveInvocationsDropped records the number of function invocations that Lambda has stopped because your function has been invoked more than approximately 16 times in a single chain of requests.

From Solutions Architect POV

In this blog we saw how we can save money and avoid downtime for our account’s lambda when triggered with S3 leading to recursive loop.

Do you also agree this update just made Lambda even better ?

You can always reach out to me on Linkedin, X.

このウェブサイトでは、よりよいユーザー体験のためにCookieを使用しています。詳細は、Cookieに関する方針をご参照ください。OK をクリックまたは本サイトの利用を続行することで、我々がCookieを使用することに同意したとみなされます。