Solve a Real-World Problem with AWS Lambda
In today’s digital landscape, websites need to handle a variety of user-generated content, like images. These images often require resizing for thumbnails or optimization for faster loading times. Instead of managing a dedicated server for this task, you can use AWS Lambda to create an efficient, serverless solution that scales automatically.
This tutorial will guide you through building a real-time image resizer using AWS Lambda, integrated with S3 and API Gateway.
Why Use AWS Lambda for Image Resizing?
- Cost Efficiency: Pay only for the compute time you use. No idle servers mean reduced costs.
- Scalability: Automatically scales to handle thousands of image resizing requests.
- Serverless: No need to manage infrastructure—focus solely on the function logic.
- Fast Execution: Lambda functions execute in milliseconds, ensuring minimal delays.
How the Solution Works
- Image Upload: A user uploads an image to an S3 bucket.
- Event Trigger: The S3 upload triggers an AWS Lambda function.
- Image Resizing: Lambda resizes the image to predefined dimensions using the Sharp library.
- Store Resized Image: The resized image is saved back to another S3 bucket or folder.
Step-by-Step: Building the Real-Time Image Resizer
Step 1: Create Two S3 Buckets
- Original Images Bucket:
- Go to the S3 Console and create a bucket, e.g.,
original-images-bucket
. - Set appropriate permissions to allow image uploads.
- Go to the S3 Console and create a bucket, e.g.,
- Resized Images Bucket:
- Create another bucket, e.g.,
resized-images-bucket
. - Configure lifecycle rules to optimize storage costs.
- Create another bucket, e.g.,
Step 2: Create a Lambda Function
- Go to Lambda Console:
- Click Create Function → Choose Author from scratch.
- Name the function, e.g.,
ImageResizerFunction
. - Select Node.js 18.x as the runtime.
- Attach an Execution Role:
- Assign a role with S3 read/write permissions. You can create a role using the AWS IAM Console:
- Attach the
AmazonS3FullAccess
policy for simplicity during development.
- Attach the
- Assign a role with S3 read/write permissions. You can create a role using the AWS IAM Console:
- Install Dependencies:
- Use the Sharp library for image processing. Zip your function code and dependencies locally
mkdir lambda-image-resizer && cd lambda-image-resizer
npm init -y
npm install sharp
zip -r function.zip .
Step 3: Write the Lambda Function Code
Add this Node.js code to your index.js
file:
const AWS = require(‘aws-sdk’);
const sharp = require(‘sharp’);
const s3 = new AWS.S3();
exports.handler = async (event) => {
try {
const bucketName = event.Records[0].s3.bucket.name;
const key = decodeURIComponent(event.Records[0].s3.object.key);
const response = await s3.getObject({ Bucket: bucketName, Key: key }).promise();
const resizedImage = await sharp(response.Body)
.resize(200, 200)
.toBuffer();
const destinationBucket = ‘resized-images-bucket’;
const destinationKey = `resized/${key}`;
await s3.putObject({
Bucket: destinationBucket,
Key: destinationKey,
Body: resizedImage,
ContentType: ‘image/jpeg’
}).promise();
console.log(`Image resized and saved to ${destinationBucket}/${destinationKey}`);
} catch (error) {
console.error(‘Error resizing image:’, error);
throw error;
}
};
Step 4: Configure S3 Trigger
- Go to the Original Images Bucket → Properties → Event Notifications.
- Add a new notification:
- Event type: PUT (trigger Lambda on image upload).
- Function: Select your
ImageResizerFunction
.
Step 5: Test the Solution
- Upload an Image:
- Upload an image to the
original-images-bucket
.
- Upload an image to the
- Check Resized Bucket:
- Navigate to the
resized-images-bucket
and confirm the resized image is stored in theresized/
folder.
- Navigate to the
Real-World Use Cases
- E-Commerce Websites: Dynamically generate product thumbnails for faster page load times.
- Social Media Platforms: Resize user-uploaded profile pictures.
- News Websites: Optimize hero images for mobile and desktop viewing.
Pro Tips for AWS Lambda
- Set Memory and Timeout:
- Allocate sufficient memory (512 MB+) for faster image processing.
- Set a reasonable timeout (e.g., 10 seconds).
- Enable Compression:
Optimize storage costs by enabling compression for resized images. - Monitor Performance:
Use AWS CloudWatch to monitor function invocations and troubleshoot errors. - Optimize Storage Costs:
Set lifecycle policies to automatically move resized images to S3 Glacier for long-term storage.
Pricing: How Much Does It Cost?
- AWS Lambda:
- First 1 million requests are free. After that, $0.20 per million requests.
- Compute time costs $0.00001667 per GB-second.
- S3 Storage:
- Store original and resized images at $0.023 per GB per month.
- Cost Estimate:
- If you resize 1,000 images per day (10 MB each), your monthly cost will be approximately $2.50 for Lambda and S3 combined.
Conclusion: Build Smarter with AWS Lambda
AWS Lambda’s serverless architecture makes it perfect for dynamic, scalable solutions like real-time image resizing. By leveraging S3 for storage and Lambda for processing, you can save costs, improve efficiency, and provide a seamless experience for your users.
Ready to simplify image processing? Build your Lambda-powered image resizer today and unlock the full potential of serverless computing!