DEV Community

Mohamed Fakhr
Mohamed Fakhr

Posted on

CDN (Content Delivery Network)

What is a CDN?
It's a network of servers distributed in different locations around the world.

The CDN stores or caches static files such as:
Images
CSS
JavaScript
Videos
Fonts
PDFs

For example, imagine your project server is in Egypt:

            project Server
              πŸ‡ͺπŸ‡¬ Egypt
                 β”‚
      β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
      ↓          ↓          ↓
    CDN        CDN        CDN
   πŸ‡©πŸ‡ͺ         πŸ‡ΊπŸ‡Έ         πŸ‡ΈπŸ‡¬
 Germany      USA       Singapore
Enter fullscreen mode Exit fullscreen mode

Suppose you have:
Project Server
↓
/storage/products/iphone.jpg

Without CDN:
<img src="https://project-domain.com/storage/products/iphone.jpg">

The user in Germany requests the image:
Germany πŸ‡©πŸ‡ͺ
↓
Egypt πŸ‡ͺπŸ‡¬
↓
iphone.jpg
↓
Germany

Every request travels to your server.

With a CDN:

You configure a CDN, for example:
cdn.project-domain.com
Your image might become:
<img src="https://cdn.project-domain.com/products/iphone.jpg">

Now:
User πŸ‡©πŸ‡ͺ
↓
CDN πŸ‡©πŸ‡ͺ
↓
iphone.jpg

The image can be delivered from a server much closer to the user.

But where does the image come from initially?
This is the important part.

Suppose the image doesn't exist on the German CDN server yet.

The first request could work like:
User πŸ‡©πŸ‡ͺ
↓
CDN πŸ‡©πŸ‡ͺ
↓
"I don't have iphone.jpg"
↓
Project/Storage πŸ‡ͺπŸ‡¬
↓
iphone.jpg
↓
CDN πŸ‡©πŸ‡ͺ ← cache it
↓
User

Then another user in Germany requests the same image:
User πŸ‡©πŸ‡ͺ
↓
CDN πŸ‡©πŸ‡ͺ
↓
iphone.jpg βœ…

The request doesn't need to go back to your project server.

That's one of the biggest benefits.

Another approach: Object Storage + CDN

For a modern application, you might have:

Your Project
β”‚
↓
Amazon S3 / Azure Blob Storage
β”‚
↓
CDN
β”‚
↓
Users

For example:

Your Project
↓
S3
↓
CloudFront
↓
Users

Your application uploads:
iphone.jpg
to S3.

The CDN delivers it to users.

This is especially useful when you have millions of images because you don't need to store all those images on your application server.

Why do we use a CDN?

  1. Faster
    The user gets the content from a nearby server.

  2. Less load on your project
    Instead of:
    10,000 users
    ↓
    Project Server

You can have:
10,000 users
↓
CDN
↓
Project only when necessary

  1. Better scalability Your Project server focuses on: API Business Logic Database Authentication Orders Payments

while the CDN handles:
Images
CSS
JS
Videos
Static files

  1. Protection Many CDN providers also provide things like: DDoS protection Caching WAF TLS/HTTPS Rate limiting One important distinction

Top comments (0)