AWS Lambda Function

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:
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.
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.
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.
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.
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:
No Server Management: You don’t have to worry about setting up, managing, or scaling servers. AWS handles all of that for you.
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.
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.
Fast Development: You can focus on writing code and building features without getting bogged down by infrastructure concerns. This speeds up development.
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:
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.
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.
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.
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:
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.
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.
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
Go to AWS Lambda Console
Click "Create function"
Step 2: Choose "Author from scratch"
Function name:
HelloLambdaRuntime: 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
Click "Test"
Choose "Create new test event"
Name it "TestEvent" and click "Create"
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
Open the AWS Management Console
Search for S3 and open the S3 dashboard
Click "Create bucket"
Enter a unique bucket name (e.g.,
my-lambda-bucket)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.
Open AWS IAM Console
Click Roles → Create Role
Select AWS Service → Choose Lambda
Click Next: Permissions
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"]
}
]
}
Click Review Policy → Name it
LambdaS3Access→ Click CreateGo back to IAM Roles, attach the
LambdaS3Accesspolicy, and name the role LambdaS3Role.
Step 3: Create a Lambda Function
Open AWS Lambda Console
Click "Create function"
Choose "Author from scratch"
Function name:
S3FileProcessorRuntime: Python 3.9
Execution Role: Choose "Use an existing role" → Select LambdaS3Role
Click "Create function"
Step 4: Add S3 as a Trigger
Scroll down to Function overview → Click "Add trigger"
Choose S3
Select your bucket (
my-lambda-bucket)Event type: PUT (Trigger when a new file is uploaded)
Click "Add"
Step 5: Write the Lambda Code
Scroll to the Code Source section
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"
- Click Deploy
Step 6: Test the Function
Upload a file (e.g.,
test.txt) tomy-lambda-bucket.Lambda automatically renames the file to
processed_test.txt.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!



