Documentations
Image Optimization Using AWS CloudFront, S3, and Lambda
Optimizing images is critical for improving website performance and search engine ranking. Google’s Largest Contentful Paint metric is heavily influenced by image optimization. This solution offers a simple and scalable method using AWS CloudFront, S3, and Lambda for automatic image transformation, resizing, and format optimization.
Architecture Overview
Image Transformation: Images are transformed centrally using AWS Lambda only when the image is not already cached. Available transformations include resizing and formatting.
CloudFront: Manages the content delivery with cache management to speed up responses.
S3: Stores both original and transformed images with a lifecycle policy to delete them after a specified period to save storage costs.
Request Flow
Here is the general flow for image requests:
- User sends an HTTP request with transformation query parameters (e.g.,
format=webp&width=200
). - CloudFront checks if the image is already cached; if not, the request is forwarded.
- A CloudFront Function normalizes and rewrites the URL to increase cache hits.
- If the image is not found in the S3 bucket, Lambda transforms the original image, stores it in S3, and returns it via CloudFront.
- The transformed image is cached for future requests.
Key Features
- CloudFront Origin Shield: Adds an additional layer of caching to improve performance.
- Automatic Format Selection: The best image format (e.g., JPEG, WebP) is selected based on the
Accept
header. - Security: CloudFront is configured with OAC to sign Lambda requests using sigV4.
Deployment with AWS CDK
To deploy the image optimization solution:
git clone https://github.com/aws-samples/image-optimization.git
cd image-optimization
npm install
cdk bootstrap
npm run build
cdk deploy
Optional Parameters
You can adjust the following parameters:
- S3_IMAGE_BUCKET_NAME: Use an existing S3 bucket for image storage.
- STORE_TRANSFORMED_IMAGES: Control whether transformed images are temporarily stored.
- S3_TRANSFORMED_IMAGE_EXPIRATION_DURATION: Set how long transformed images stay in S3 before being deleted.
- S3_TRANSFORMED_IMAGE_CACHE_TTL: Configure cache duration for transformed images.
- CLOUDFRONT_ORIGIN_SHIELD_REGION: Specify a region for Origin Shield.
- LAMBDA_MEMORY & LAMBDA_TIMEOUT: Adjust the memory and timeout settings for the Lambda function.
- MAX_IMAGE_SIZE: Define the maximum image size for requests.
- CLOUDFRONT_CORS_ENABLED: Enable/disable CORS on the CloudFront distribution.
Clean-up Resources
To remove the cloud resources created:
cdk destroy