What is CDN? How to use  Cloudfront with S3?

Photo by Clint Adair on Unsplash

What is CDN? How to use Cloudfront with S3?

Make your Website 100X Faster and reliable.

Have you ever faced a high loading time while loading assets over the Internet or have you had questions like how YouTube serves videos very smoothly? So the answer is CDN.

Content Delivery Networks (CDNs) are a globally distributed network of servers that cache and serve static content, such as images, videos, CSS, and JavaScript files. When a user requests a website or an application, the CDN servers closest to the user's location deliver the cached assets, significantly reducing the latency and improving the overall performance.

The way CDNs work is ingenious. Instead of serving all content from a single origin server, which could be located far away from the end-user, CDNs have servers strategically placed in various geographical locations around the world. When a user requests content, the CDN automatically routes the request to the nearest server, which then delivers the cached assets from its local storage.

This distributed architecture solves a fundamental problem: distance. The further the user is from the origin server, the longer it takes for the content to travel, resulting in slower load times. By caching content on servers closer to the users, CDNs minimize the physical distance between the user and the server, reducing latency and enabling faster content delivery.

Uses of CDNs

CDNs are an important network of servers which is the backbone of the modern internet because of the following reasons:

  1. Reduce Latency

CDN network can cache the content in it and distribute over the network of proxy servers which serves them whenever nearby user ask for it, which overall reduce latency.

  1. Security
  • CDN can protect websites from DDoS attacks, block spammers, and secure applications.

  • Many CDNs offer web application firewalls (WAFs) that can detect and block suspicious or malicious requests, such as SQL injection attacks, cross-site scripting (XSS) attacks, and brute-force login attempts.

  • CDNs often use advanced DDoS mitigation techniques such as rate limiting, traffic profiling, and IP reputation analysis to identify and block malicious requests in real-time.

  1. Analytics
  • CDNs can track user interactions with websites or applications, such as page views, clicks, and session duration

  • It caches static content and serve it from edge servers located closer to the user's location, reducing latency and improving page load times.

  • It can also provide analytics related to security events, such as DDoS attacks, web application attacks, and bot traffic.

What is Cloudfront?

Amazon CloudFront is a web service that speeds up distribution of your static and dynamic web content, such as .html, .css, .js, and image files, to your users. CloudFront delivers your content through a worldwide network of data centers called edge locations. When a user requests content that you're serving with CloudFront, the request is routed to the edge location that provides the lowest latency (time delay), so that content is delivered with the best possible performance.

  • If the content is already in the edge location with the lowest latency, CloudFront delivers it immediately.

  • If the content is not in that edge location, CloudFront retrieves it from an origin that you've defined—such as an Amazon S3 bucket, a MediaPackage channel, or an HTTP server that you have identified as the source for the definitive version of your content.

How to use Cloudfront with S3 Bucket?

If you have been following our blog for a long then you may be familiar with S3 and its configuration and how to use it in our Node.js App. So today we are going to add the power of CDNs in our Photoapp from the S3 tutorial to bring the latency down.

  1. First, we have to create a CloudFront network and integrate our S3 bucket with it which will first distribute the content of S3 over proxy servers.

search cloudfront and make the distribution as mentioned below.

in origin domain choose the s3 bucket for which we have to make the distribution network.

Now choose the origin access to Origin access control settings to give the S3 access to cloudfront so that no one can directly access the assets from S3.It will also prevent abuse of S3.

Enable Origin Shield to add caching layer that reduce load on your origin which increase availability.

Keep the Cache policy recommended for S3 and then click on create to make a distribution.It may take time and after some time it will be ready to change the bucket policy.

go to the s3 and change the bucket policy to give the access of bucket to CDNs.

Please Block all the public access of the Bucket before changing the bucket policy.

Now we are all ready to test the power of CDNs so now you have to copy the Distribution Domain and object of s3 bucket and hit like this

https://Distribution-domain-name/s3-object-name and see the result.

If you want to test and see the actual difference with number then go to the keycdn performance test and check the both the endpoints and see the result.

without CDN

The above result is without CDN.

The above result is with CDN.

Now to improve our photoapp we just have to change few code in the upload photo controller as mentioned below.

async function uploadImage(req, res) {
  try {

    const { location } = req.file;
    const urlParts = new URL(location);
    let key = urlParts.pathname.substring(1);
    const newPhoto = new photo({
      picUrl: "https://{distribution domain}.cloudfront.net/"+key, 
      tag: req.body.tag 
    await newPhoto.save(); 
  } catch (error) {
    res.status(500).json({ error: 'Internal server error' });

Thank you for reading this blog and learning about the importance of Content Delivery Networks (CDNs) in enhancing website performance by minimizing asset loading latency.

If you found this information valuable, I encourage you to share this blog with your friends and colleagues. Don't forget to tag me on X when you do!

Signing off for now, but stay tuned for more insightful blogs next week. Until then, keep learning and coding! 👨‍💻👨‍💻

Did you find this article valuable?

Support Vishal Sharma by becoming a sponsor. Any amount is appreciated!