DEV Community

Cover image for Caching Content with AWS CloudFront: A Detailed Guide
marocz
marocz

Posted on

Caching Content with AWS CloudFront: A Detailed Guide

Hello, Community!

Today, we're exploring the acceleration of web content delivery using AWS CloudFront.
Additionally, we'll delve into automating this setup with Terraform, ensuring you have an efficient, replicable, and maintainable infrastructure.

Understanding AWS CloudFront

AWS CloudFront is a content delivery network (CDN) service that securely delivers data, videos, applications, and APIs to customers globally with low latency and high transfer speeds. CloudFront is integrated with AWS โ€“ both physical locations that are directly connected to the AWS global infrastructure, as well as other AWS services.

  • Edge Locations: CloudFront caches copies of your content in edge locations across the globe ensuring fast delivery to users.
  • Origin Fetches: When content is not cached, CloudFront fetches it from specified origins, like S3 buckets or HTTP servers.
  • Content Delivery: CloudFront provides a secure and optimized delivery of your content to users via HTTPS.
  • Invalidation: You can remove cached content to refresh it with updated versions.
  • Customization: Customize content delivery by configuring cache behaviors, geo-restrictions, and more.
  • Integration: Seamlessly integrate CloudFront with other AWS services like AWS WAF, AWS Shield, and Lambda@Edge for enhanced security and functionality.

Benefits:

  1. Performance: Reduced latency due to proximity-based content delivery.
  2. Scalability: Smooth handling of traffic spikes.
  3. Integration: Compatibility with other AWS services like Amazon S3, EC2, and Lambda.
  4. Security: Features HTTPS, AWS WAF integration, and DDoS protection.

CloudFront Cache Invalidation

If you update your content and want to remove the old content from CloudFront edge locations, you need to create an invalidation.

  1. Go to the Distribution.
  2. Invalidations tab โ†’ Create Invalidation.
  3. Enter the path for the content to invalidate (e.g., /images/*).

AWS Cloudfront Integration with S3 bucket

Setting Up CloudFront Manually

Prerequisites:

  • An AWS account.
  • Content to distribute, e.g., a website on S3 or EC2.

Procedure:

  1. Login to the AWS Management Console.
  2. Go to CloudFront.
  3. Click Create Distribution and choose Web.
  4. Configure Distribution:

    • Origin Settings: Define where CloudFront fetches content.
    • Default Cache Behavior Settings: Set policies, like redirecting HTTP to HTTPS.
    • Distribution Settings: Define price class, logging, SSL, etc.
  5. Click Create Distribution. Upon creation, you'll receive a unique CloudFront URL.

  6. Testing: Access content via the CloudFront URL to verify.

Setting Up AWS CloudFront using AWS CLI

  1. Create an S3 Bucket:
aws s3api create-bucket --bucket my-bucket-name --region us-west-2
Enter fullscreen mode Exit fullscreen mode
  1. Configure CloudFront Distribution:
  • Navigate to CloudFront in the AWS Management Console.
  • Select 'Create Distribution'.
  • Choose 'Web' and specify your S3 bucket as the origin.
aws cloudfront create-distribution \
--origin-domain-name my-bucket-name.s3.amazonaws.com
Enter fullscreen mode Exit fullscreen mode
  1. Set Cache Behavior:
    • Choose suitable caching rules under 'Cache Behavior Settings'.
aws cloudfront create-distribution \
--default-cache-behavior AllowedMethods=GET,HEAD
Enter fullscreen mode Exit fullscreen mode

Automating Setup with Terraform

Prerequisites:

  1. Terraform installed and configured.
  2. AWS CLI set up with the necessary permissions.

Procedure using Terraform:

  1. Initialize Configuration
provider "aws" {
  region = "us-west-1"
}
Enter fullscreen mode Exit fullscreen mode
  1. Define S3 Bucket
resource "aws_s3_bucket" "b" {
  bucket = "my-tf-test-bucket"
  acl    = "private"
}
Enter fullscreen mode Exit fullscreen mode
  1. Define CloudFront Distribution
resource "aws_cloudfront_distribution" "s3_distribution" {
  origin {
    domain_name = aws_s3_bucket.b.bucket_regional_domain_name
    origin_id   = "S3-BUCKET-ORIGIN-ID"

    s3_origin_config {
      origin_access_identity = "origin-access-identity/cloudfront/ID_GOES_HERE"
    }
  }

  enabled             = true
  is_ipv6_enabled     = true
  default_root_object = "index.html"

  default_cache_behavior {
    allowed_methods  = ["DELETE", "GET", "HEAD", "OPTIONS", "PATCH", "POST", "PUT"]
    cached_methods   = ["GET", "HEAD"]
    target_origin_id = "S3-BUCKET-ORIGIN-ID"

    forwarded_values {
      query_string = false

      cookies {
        forward = "none"
      }
    }

    viewer_protocol_policy = "allow-all"
    min_ttl                = 0
    default_ttl            = 3600
    max_ttl                = 86400
  }

  price_class = "PriceClass_100"

  restrictions {
    geo_restriction {
      restriction_type = "none"
    }
  }

  viewer_certificate {
    cloudfront_default_certificate = true
  }
}

Enter fullscreen mode Exit fullscreen mode
  1. Deploy
  • terraform init to initialize.
  • terraform plan to preview.
  • terraform apply to deploy.

Conclusion:
AWS CloudFront is a powerful tool to cache and deliver content efficiently. By creating an S3 bucket, configuring a CloudFront distribution, and setting up cache behaviors, you can significantly accelerate content delivery to end-users.

Best Practices

  1. Use CloudFront with S3 Origin Access Identity to restrict direct bucket access.
  2. Enable Gzip compression for optimized data transfer.
  3. Employ Lambda@Edge for advanced content handling.
  4. Implement asset versioning to reduce the need for cache invalidations.

Conclusion

Pairing AWS CloudFront with Terraform offers both speed in content delivery and efficiency in infrastructure management. Whether serving small sites or global apps, this combo ensures swift, secure content delivery. Happy caching! ๐Ÿš€


AWS Cloud Front

Top comments (0)