HomeAWSAWS Lambda Tutorial: Building a Real-Time Image Resizer for Your Web Application

AWS Lambda Tutorial: Building a Real-Time Image Resizer for Your Web Application

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?

  1. Cost Efficiency: Pay only for the compute time you use. No idle servers mean reduced costs.
  2. Scalability: Automatically scales to handle thousands of image resizing requests.
  3. Serverless: No need to manage infrastructure—focus solely on the function logic.
  4. Fast Execution: Lambda functions execute in milliseconds, ensuring minimal delays.

How the Solution Works

  1. Image Upload: A user uploads an image to an S3 bucket.
  2. Event Trigger: The S3 upload triggers an AWS Lambda function.
  3. Image Resizing: Lambda resizes the image to predefined dimensions using the Sharp library.
  4. 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

  1. Original Images Bucket:
    • Go to the S3 Console and create a bucket, e.g., original-images-bucket.
    • Set appropriate permissions to allow image uploads.
  2. Resized Images Bucket:
    • Create another bucket, e.g., resized-images-bucket.
    • Configure lifecycle rules to optimize storage costs.

Step 2: Create a Lambda Function

  1. 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.
  2. 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.
  3. 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

  1. Go to the Original Images BucketPropertiesEvent Notifications.
  2. Add a new notification:
    • Event type: PUT (trigger Lambda on image upload).
    • Function: Select your ImageResizerFunction.

Step 5: Test the Solution

  1. Upload an Image:
    • Upload an image to the original-images-bucket.
  2. Check Resized Bucket:
    • Navigate to the resized-images-bucket and confirm the resized image is stored in the resized/ folder.

Real-World Use Cases

  1. E-Commerce Websites: Dynamically generate product thumbnails for faster page load times.
  2. Social Media Platforms: Resize user-uploaded profile pictures.
  3. News Websites: Optimize hero images for mobile and desktop viewing.

Pro Tips for AWS Lambda

  1. Set Memory and Timeout:
    • Allocate sufficient memory (512 MB+) for faster image processing.
    • Set a reasonable timeout (e.g., 10 seconds).
  2. Enable Compression:
    Optimize storage costs by enabling compression for resized images.
  3. Monitor Performance:
    Use AWS CloudWatch to monitor function invocations and troubleshoot errors.
  4. Optimize Storage Costs:
    Set lifecycle policies to automatically move resized images to S3 Glacier for long-term storage.

Pricing: How Much Does It Cost?

  1. AWS Lambda:
    • First 1 million requests are free. After that, $0.20 per million requests.
    • Compute time costs $0.00001667 per GB-second.
  2. S3 Storage:
    • Store original and resized images at $0.023 per GB per month.
  3. 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!

Share: