AWS Lambda User Guide
Introduction
AWS Lambda is a leading "Serverless" computing service from Amazon Web Services (AWS). It allows you to run your code without having to manage or provision any servers.
Simply put, instead of renting a virtual computer (like EC2), installing an OS, and maintaining it, you just upload your code. Lambda handles everything else—from activating resources and executing the code to shutting everything down once the job is done.
Key Advantages of AWS Lambda
- No Server Management (Serverless): You don't need to worry about OS updates, security patches, or hardware maintenance. AWS handles all the heavy lifting of infrastructure operations.
- Auto-scaling: Lambda reacts instantly to the number of requests. If there is 1 request, it runs once; if there are 10,000 simultaneous requests, it automatically scales up to handle them in parallel without any extra configuration.
- Cost Optimization (Pay-as-you-go): This is the best part. You only pay for the time your code is actually running (measured in milliseconds). If the code isn't running, you don't pay a cent. This is a huge shift from traditional servers where you pay even when the server is just sitting idle.
- Event-driven Architecture: Lambda is extremely flexible. It can be triggered by various AWS services, such as uploading a photo to S3, adding new data to DynamoDB, or through a user's API request.
- Multi-language Support: You can write code in popular languages like Python, Node.js, Java, Go, C#, Ruby, and PowerShell.
In short: AWS Lambda is the perfect solution for developers who want to focus entirely on their product logic while keeping operational costs to a minimum.
Real-world Example: On-the-fly Image Resizing
In this guide, I will show you how to use Lambda combined with S3 and CloudFront to resize images instantly when accessing an image URL. This is very useful when you upload high-resolution images but need to display smaller thumbnails to save bandwidth and improve performance.
Prerequisites
You should have a basic understanding of S3 Buckets and CloudFront. Ensure the AWS profile you are using has sufficient permissions for these services.
Detailed Implementation
First, create a file named resize-lambda.ts:
Explanation:
- This code triggers when a user visits a URL like: {cloudfront}/{width}x{height}/{image-name}
- s3.putObject: Saves the resized image back to the bucket with a cache duration of 1 year.
- Redirect: Finally, it redirects the user to the newly created CloudFront image link.
Next, create the infrastructure stack in lib/image-resize-stack.ts:
Explanation:
- imageBucket: This creates the bucket. You’ll notice that public access isn't completely blocked like in my previous S3 and CloudFront tutorials. This is because we can't use an internal connection (S3 REST API Endpoint) here. Instead, we use the S3 Website Endpoint (HTTP) so that when someone tries to access an image that isn't there yet, S3 can redirect them to Lambda to create it, rather than just throwing a 403 or 404 error.
- distribution: This creates the CloudFront setup. I’ve added CUSTOM_HEADER_NAME and CUSTOM_HEADER_VALUE as a security measure. Since the bucket isn't fully public, I use this "secret header" for communication between CloudFront and the bucket. Only requests with this specific header can access the files, which prevents random users from bypassing CloudFront to access your bucket directly.
- resizerLambda: This is the Lambda function itself. Note that I've passed BUCKET_NAME and CF_DOMAIN into the environment variables so the code in resize-lambda.ts knows which bucket to use and where to redirect.
- LambdaRestApi: This is the API Gateway that triggers the Lambda code to resize the image if the bucket doesn't have it.
- websiteConfiguration: This is the bucket setting that handles the magic—it tells S3 to redirect to our Lambda API whenever an image isn't found.
Step-by-Step Workflow
- Upload the original image to the S3 Bucket.
- Access the image via the CloudFront URL. If CloudFront has it cached, it serves it immediately. If not, it checks the Bucket.
- Check Bucket: If the Bucket has the image (the specific size requested), it returns it to CloudFront. If it’s missing, S3 redirects the request to API Gateway to run the Lambda code.
- Process & Redirect: The Lambda code creates the resized image based on your URL parameters and saves it back to the Bucket. Finally, it redirects you back to the CloudFront link to view the newly created image.
Update your bin/aws-cdk.ts:
Successful Deployment Results
Use the values provided, such as CloudFrontURL and InputBucketName, in your NestJS project.
Next, here is the code for the NestJS s3.service.ts file:
Explanation:
- createPresignedUrl: I am still using a pre-signed URL to upload images. The mime.lookup(fileName) part is used to get the correct content type for the AWS file based on its file extension.
- listFiles: This is used to retrieve both the original images and the resized ones. The resized images will have a file key that includes the dimensions (for example: 300x300).
After that, try uploading an image and accessing the resize URL to check the results.
The images uploaded to the Bucket will look like this:
Happy coding!
Comments
Post a Comment