Creating Your Own CDN Using AWS in 2024

5 min read
Last updated: Jul 24, 2024

A Content Delivery Network (CDN) helps deliver web content more quickly by caching copies of the content at various locations around the world. This guide will show you how to create a CDN using AWS services: S3 for storage, CloudFront for content delivery, and Lambda@Edge for image and video processing. Follow these steps to set up your own scalable and optimized CDN.

Table of Contents

  1. Setting Up S3 Buckets
  2. Configuring CloudFront Distribution
  3. Creating Lambda@Edge Functions
  4. Connecting S3, CloudFront, and Lambda@Edge
  5. Testing Your CDN
  6. Optimizing Performance

1. Setting Up S3 Buckets

Amazon S3 (Simple Storage Service) will be used to store your static assets like images and videos.

Step-by-Step Instructions:

  1. Create an S3 Bucket:

    • Go to the AWS Management Console.
    • Navigate to S3 and click on “Create bucket”.
    • Enter a unique bucket name and choose a region.
    • Configure settings as needed (e.g., versioning, logging).
    • Click “Create bucket”.
  2. Upload Your Assets:

    • Open your newly created bucket.
    • Click on “Upload” and add your files (images, videos).
    • Set appropriate permissions to make your content accessible.

2. Configuring CloudFront Distribution

Amazon CloudFront is a CDN service that accelerates the delivery of your content.

Step-by-Step Instructions:

  1. Create a CloudFront Distribution:

    • Navigate to CloudFront in the AWS Management Console.
    • Click “Create Distribution” and choose “Web”.
    • In the “Origin Settings”, set your S3 bucket as the origin.
    • Configure default cache behavior settings:
    • Set the Viewer Protocol Policy to “Redirect HTTP to HTTPS”.
    • Configure caching and allowed HTTP methods as needed.
  2. Configure Distribution Settings:

    • Under “Distribution Settings”, configure additional options such as logging, price class, and SSL certificates.
    • Click “Create Distribution”.
  3. Get Distribution Domain Name:

    • Once the distribution is deployed, note down the CloudFront domain name (e.g., d1234abcde.cloudfront.net).

3. Creating Lambda@Edge Functions

Lambda@Edge allows you to run code closer to your users, improving performance and reducing latency.

Step-by-Step Instructions:

  1. Create a Lambda Function:

    • Navigate to Lambda in the AWS Management Console.
    • Click “Create function” and choose “Author from scratch”.
    • Enter a function name and choose the latest Node.js runtime.
    • Set up execution role permissions.
  2. Write Your Function Code:

    • Use the inline code editor or upload a ZIP file with your code.
    • Example function to resize images on the fly:
    const aws = require("aws-sdk");
    const s3 = new aws.S3();
    const sharp = require("sharp");
    
    exports.handler = async (event) => {
     const { request } = event.Records[0].cf;
     const { uri } = request;
     const bucket = "your-s3-bucket-name";
    
     // Parse width and height from URI
     const [, width, height, key] = uri.match(/\/(\d+)x(\d+)\/(.+)/);
    
     try {
       const { Body: image } = await s3
         .getObject({
           Bucket: bucket,
           Key: key,
         })
         .promise();
    
       const resizedImage = await sharp(image)
         .resize(parseInt(width), parseInt(height))
         .toBuffer();
    
       return {
         status: "200",
         statusDescription: "OK",
         body: resizedImage.toString("base64"),
         bodyEncoding: "base64",
         headers: {
           "content-type": [{ key: "Content-Type", value: "image/jpeg" }],
         },
       };
     } catch (err) {
       return {
         status: "404",
         statusDescription: "Not Found",
         body: "The image does not exist or another error occurred.",
       };
     }
    };
  3. Deploy Lambda Function to Edge:

    • Under “Actions”, click “Deploy to Lambda@Edge”.
    • Select “Origin Request” or “Viewer Request” as appropriate.
    • Choose the CloudFront distribution and deploy.

4. Connecting S3, CloudFront, and Lambda@Edge

Now that you have your S3 bucket, CloudFront distribution, and Lambda@Edge function, you need to connect them.

Step-by-Step Instructions:

  1. Update CloudFront Distribution:

    • Go to your CloudFront distribution settings.
    • Under “Behaviors”, edit the default behavior.
    • Add your Lambda@Edge function ARN to the “Lambda function associations”.
  2. Set Up Cache Behavior:

    • Define cache policies to ensure images and videos are cached correctly.
    • Configure path patterns to route specific requests to Lambda@Edge functions.

5. Testing Your CDN

To ensure everything is working correctly, perform the following tests:

  1. Access Content Through CloudFront:

    • Use the CloudFront domain name to access your assets.
    • Test by fetching resized images using the defined URI pattern (e.g., https://d1234abcde.cloudfront.net/300x300/image.jpg).
  2. Verify Cache and Processing:

    • Check CloudFront and S3 logs to verify that requests are being cached and processed by Lambda@Edge.

6. Optimizing Performance

To ensure optimal performance, consider the following:

  1. Enable Compression:

    • Enable Gzip or Brotli compression in CloudFront to reduce the size of your assets.
  2. Set Cache-Control Headers:

    • Configure appropriate cache-control headers to optimize caching.
  3. Monitor and Analyze:

    • Use AWS CloudWatch and CloudFront logs to monitor performance and identify bottlenecks.
  4. Implement Security Best Practices:

    • Use AWS WAF to protect against common web exploits.
    • Ensure your S3 bucket permissions are secure.

Conclusion

By following these steps, you can set up a powerful and scalable CDN using AWS S3, CloudFront, and Lambda@Edge. This setup will help you deliver your content efficiently, providing a better experience for your users worldwide.

Any thoughts, let's discuss on twitter

Sharing this article is a great way to educate others like you just did.



If you’ve enjoyed this issue, do consider subscribing to my newsletter.


Subscribe to get more such interesting content !

Tech, Product, Money, Books, Life. Discover stuff, be inspired, and get ahead. Box Piper is on Twitter and Discord. Let's Connect!!

To read more such interesting topics, let's go Home

More Products from the maker of Box Piper:

Follow GitPiper Instagram account. GitPiper is the worlds biggest repository of programming and technology resources. There is nothing you can't find on GitPiper.

Follow SharkTankSeason.com. Dive into the riveting world of Shark Tank Seasons. Explore episodes, pitches, products, investment details, companies, seasons and stories of entrepreneurs seeking investment deals from sharks. Get inspired today!.


Scraper API

More Blogs from the house of Box Piper: