Skip to main content

Command Palette

Search for a command to run...

AWS Lambda Function

Published
7 min read
AWS Lambda Function
K
👋 Hi, I'm Khushi Dubey, a passionate final year BCA student diving deep into the world of Cloud & DevOps. My journey is focused on the intersection of cloud technologies and cutting-edge DevOps methodologies to drive innovation and transformation. 🌍 Here’s a snapshot of who I am: 🚀 Aspiring Cloud/DevOps Professional: Passionate about streamlining processes, automating workflows, and optimizing cloud infrastructures. 💻 Tech Enthusiast: Constantly exploring new tools, trends, and techniques in cloud computing and DevOps engineering. 🎯 Problem-Solver: Dedicated to finding practical and scalable solutions to real-world challenges. ✍️ Lifelong Learner: Continuously improving my skill set to keep pace with evolving technologies and industry demands. 🌐 Collaborator: Believer in the power of teamwork and open knowledge sharing to build a thriving tech community. 📚 Follow my journey as I share insights, tutorials, and hands-on experiences from my Cloud and DevOps

What is AWS Lambda?

AWS Lambda is a cloud service that runs your code automatically without requiring you to manage servers. It follows a concept called serverless computing, meaning you don’t have to worry about setting up or maintaining physical or virtual servers.

With AWS Lambda, you simply upload your code, set some rules (called triggers), and AWS handles everything else, including execution, scaling, and maintenance.


How Does AWS Lambda Work?

Let’s break it down step by step:

  1. You Write the Code: You write a piece of code (called a function) in a programming language like Python, JavaScript, or Java. This function is designed to perform a specific task, like resizing an image, processing data, or sending an email.

  2. Upload the Code: You upload your code to AWS Lambda. You don’t need to set up any servers or infrastructure—just upload the code, and Lambda takes care of the rest.

  3. Trigger the Function: Your code sits in Lambda until something triggers it. A trigger is an event that tells Lambda to run your code. For example, if you want to resize an image whenever it’s uploaded to an S3 bucket (AWS’s storage service), you can set up S3 as a trigger. Every time an image is uploaded, Lambda automatically runs your code.

  4. Lambda Executes the Code: When the trigger occurs, AWS Lambda runs your code. It automatically allocates the necessary resources (like memory and processing power) to execute the function.

  5. You Pay Only for What You Use: Here’s the best part—you only pay for the time your code is running. If your code runs for 1 second, you pay for 1 second. If it doesn’t run at all, you pay nothing. This makes Lambda very cost-effective.


Why is AWS Lambda So Popular?

AWS Lambda has become incredibly popular because it simplifies the process of running code. Here are some of the key benefits:

  1. No Server Management: You don’t have to worry about setting up, managing, or scaling servers. AWS handles all of that for you.

  2. Automatic Scaling: If your code needs to handle 10 requests or 10,000 requests, Lambda automatically scales to meet the demand. You don’t have to do anything.

  3. Cost-Effective: Since you only pay for the time your code runs, it’s a very cost-effective solution, especially for applications with variable workloads.

  4. Fast Development: You can focus on writing code and building features without getting bogged down by infrastructure concerns. This speeds up development.

  5. Event-Driven: Lambda is designed to respond to events, making it perfect for tasks like processing data, handling API requests, or automating workflows.


Real-Life Examples of AWS Lambda

To make it even clearer, let’s look at some real-life examples of how AWS Lambda can be used:

  1. Image Processing: Imagine you have a website where users upload images. You want to automatically resize these images to fit different screen sizes. With Lambda, you can write a function that resizes the image every time it’s uploaded to an S3 bucket.

  2. Data Processing: If you have a system that generates a lot of data (like logs from a website), you can use Lambda to process this data in real-time. For example, you could analyze the logs to detect errors or extract useful information.

  3. Chatbots: If you’ve ever interacted with a chatbot on a website, there’s a good chance it’s powered by Lambda. Lambda can run the code that processes user inputs and generates responses.

  4. Automated Backups: You can use Lambda to automatically back up data from one service to another. For example, you could set up a Lambda function that backs up data from a database to an S3 bucket every night.


Limitations of AWS Lambda

While AWS Lambda is incredibly powerful, it’s not perfect for every situation. Here are a few limitations to keep in mind:

  1. Short Execution Time: Lambda functions are designed to run for a short period (up to 15 minutes). If you need to run long-running tasks, Lambda might not be the best choice.

  2. Cold Starts: If a Lambda function hasn’t been used in a while, it can take a few seconds to start up. This is called a "cold start," and while it’s usually not a big deal, it can be an issue for time-sensitive applications.

  3. Limited Control: Since AWS manages the infrastructure, you have less control over the environment compared to running your own servers.


Create an AWS Lambda Function (Practical Example)

Let’s create a simple Lambda function in Python that prints "Hello from AWS Lambda!" when triggered.

Step 1: Log in to AWS Lambda Console

  1. Go to AWS Lambda Console

  2. Click "Create function"

Step 2: Choose "Author from scratch"

  • Function name: HelloLambda

  • Runtime: Python 3.9

  • Execution role: Create a new role with basic permissions

  • Click "Create function"

Step 3: Write Your Code

Scroll down to the Code source section and replace the default code with this:

def lambda_handler(event, context):  
    return "Hello from AWS Lambda!"

Click "Deploy" to save the function.

Step 4: Test the Function

  1. Click "Test"

  2. Choose "Create new test event"

  3. Name it "TestEvent" and click "Create"

  4. Click "Test" again

You will see the output: "Hello from AWS Lambda!"


AWS Lambda Function with S3 Integration

Use Case: AWS Lambda with S3

We will create an AWS Lambda function that automatically renames a file when it is uploaded to an S3 bucket.

Example Scenario:

User uploads a file → AWS S3 bucket
Lambda is triggered → Renames the file
Updated file is stored in the same S3 bucket

AWS Lambda with S3

Step 1: Create an S3 Bucket

  1. Open the AWS Management Console

  2. Search for S3 and open the S3 dashboard

  3. Click "Create bucket"

  4. Enter a unique bucket name (e.g., my-lambda-bucket)

  5. Keep other settings as default and click "Create bucket"


Step 2: Create an IAM Role for Lambda

AWS Lambda needs permissions to access S3. We will create an IAM role for this.

  1. Open AWS IAM Console

  2. Click RolesCreate Role

  3. Select AWS Service → Choose Lambda

  4. Click Next: Permissions

  5. Click "Create Policy" → Select JSON and paste this:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": ["s3:GetObject", "s3:PutObject", "s3:ListBucket"],
            "Resource": ["arn:aws:s3:::my-lambda-bucket/*", "arn:aws:s3:::my-lambda-bucket"]
        }
    ]
}
  1. Click Review Policy → Name it LambdaS3Access → Click Create

  2. Go back to IAM Roles, attach the LambdaS3Access policy, and name the role LambdaS3Role.


Step 3: Create a Lambda Function

  1. Open AWS Lambda Console

  2. Click "Create function"

  3. Choose "Author from scratch"

  4. Function name: S3FileProcessor

  5. Runtime: Python 3.9

  6. Execution Role: Choose "Use an existing role" → Select LambdaS3Role

  7. Click "Create function"


Step 4: Add S3 as a Trigger

  1. Scroll down to Function overview → Click "Add trigger"

  2. Choose S3

  3. Select your bucket (my-lambda-bucket)

  4. Event type: PUT (Trigger when a new file is uploaded)

  5. Click "Add"


Step 5: Write the Lambda Code

  1. Scroll to the Code Source section

  2. Replace the default code with the following:

import boto3  

def lambda_handler(event, context):  
    s3 = boto3.client('s3')  

    # Get bucket and file details from event  
    bucket_name = event['Records'][0]['s3']['bucket']['name']  
    file_key = event['Records'][0]['s3']['object']['key']  

    # Define new file name  
    new_file_key = "processed_" + file_key  

    # Copy the file with a new name  
    copy_source = {'Bucket': bucket_name, 'Key': file_key}  
    s3.copy_object(Bucket=bucket_name, CopySource=copy_source, Key=new_file_key)  

    print(f"File {file_key} renamed to {new_file_key}")  
    return "Success"
  1. Click Deploy

Step 6: Test the Function

  1. Upload a file (e.g., test.txt) to my-lambda-bucket.

  2. Lambda automatically renames the file to processed_test.txt.

  3. Check your S3 bucket to confirm the renamed file!


Real-World Use Cases of AWS Lambda + S3

Auto-resize images when uploaded
Convert CSV to JSON for data processing
Move logs to a different storage bucket
Auto-generate reports when files are uploaded


AWS Lambda Pricing

First 1 million requests per month are FREE!
AWS charges based on:
Number of requests – Every function execution counts.
Execution time – Billed in milliseconds.

For small tasks, AWS Lambda is almost free!


Linkedin: https://www.linkedin.com/in/khushi-dubey-6036a2305

Thank You!