Nextgen Blog
HomeLearnAIQuantumRoboticsSecuritySpaceAbout
Nextgen Blog

By Anubhav — full stack engineer, IIT Mandi CSE. Deep dives into AI, software engineering, and the technologies shaping the next generation of tech.

Navigate

  • Home
  • Learn
  • Blog
  • Archive
  • About

Topics

  • Artificial Intelligence
  • Quantum Computing
  • Robotics
  • Cybersecurity
  • Space Tech

Connect

Built with ❤️ & By - Anubhav

© 2026 Nextgen Blog by Anubhav. All rights reserved.

Privacy PolicyTerms of Service
Phase 02 · Scaling, Traffic & Data StoresChapter 10 of 33
09.
Phase 02Read time ~27 minDifficulty advanced

CDN & Edge Computing

In this chapter
  • 01Chapter Overview
  • 02What Is a CDN?
  • 03What Is an Edge Location?
  • 04Origin Server
  • 05CDN Request Flow
  • 06Cache hit
  • 07Cache miss
  • 08Why CDN Improves Performance
  • 09CDN Is More Than a Cache
  • 10Static Content
  • 11Dynamic Content
  • 12Static vs Dynamic CDN Usage
  • 13Cache Hit
  • 14Cache Miss
  • 15Cache Hit Ratio
  • 16Cache Miss Ratio
  • 17TTL
  • 18Long TTL
  • 19Cache Busting
  • 20Cache-Control
  • 21Public vs Private Content
  • 22no-store
  • 23no-cache
  • 24Browser Cache vs CDN Cache
  • 25Cache Hierarchy
  • 26Cache Key
  • 27Cache Key Problem
  • 28Query String Caching
  • 29Cache Fragmentation
  • 30Cache Invalidation
  • 31Cache Invalidation Strategies
  • 32TTL expiration
  • 33Explicit purge
  • 34Versioned URLs
  • 35Revalidation
  • 36Explicit Purging
  • 37Versioned URLs
  • 38Stale Content
  • 39Origin Shielding
  • 40Cache Stampede
  • 41Preventing Cache Stampede
  • 42Request Coalescing
  • 43CDN for Images
  • 44CDN for Video
  • 45Video Segmentation
  • 46CDN and APIs
  • 47Edge Computing
  • 48Why Run Code at the Edge?
  • 49Edge Function Example
  • 50Edge vs Origin
  • 51Edge
  • 52Origin
  • 53Edge Limitations
  • 54Geographic Routing
  • 55Anycast
  • 56CDN + DNS
  • 57CDN + Load Balancer
  • 58CDN + Object Storage
  • 59Origin Architecture
  • 60DDoS Protection Concept
  • 61Web Application Firewall
  • 62CDN Security Consideration
  • 63Protecting the Origin
  • 64CDN Failure Scenarios
  • 65Scenario 1 — Edge failure
  • 66Scenario 2 — Origin failure
  • 67Scenario 3 — Cache purge failure
  • 68Scenario 4 — Bad cache configuration
  • 69Scenario 5 — CDN provider outage
  • 70CDN as Availability Layer
  • 71Cache-Control Example
  • 72CDN Design for a Blog
  • 73Cache Hit Ratio Optimization
  • 74Cache key
  • 75TTL
  • 76Content reuse
  • 77Object size
  • 78Cache policy
  • 79Regional distribution
  • 80Cache Eviction
  • 81LRU
  • 82LFU
  • 83CDN and Compression
  • 84CDN and HTTP/2 / HTTP/3
  • 85CDN and Origin Protocols
  • 86Cache Warming
  • 87Cache Warming Trade-offs
  • 88CDN and Multi-Region Origin
  • 89CDN Failure vs Origin Failure
  • 90CDN failure
  • 91Origin failure
  • 92Cache Correctness
  • 93CDN Design Checklist
  • 94Content
  • 95Cache key
  • 96Freshness
  • 97Scale
  • 98Origin
  • 99Security
  • 100Failure
  • 101Common Mistakes
  • 102Mistake 1 — Caching everything
  • 103Mistake 2 — Thinking CDN automatically means low latency
  • 104Mistake 3 — Ignoring cache keys
  • 105Mistake 4 — Confusing no-cache with no-store
  • 106Mistake 5 — Ignoring cache invalidation
  • 107Mistake 6 — Exposing the origin directly
  • 108Mistake 7 — Ignoring cache stampedes
  • 109Mistake 8 — Moving complex logic to the edge
  • 110Mistake 9 — Ignoring private data
  • 111Interview Questions
  • 112Q1. What is a CDN?
  • 113Q2. How does a CDN reduce latency?
  • 114Q3. What is a cache hit?
  • 115Q4. What is a cache miss?
  • 116Q5. What is TTL?
  • 117Q6. What is cache invalidation?
  • 118Q7. What is cache stampede?
  • 119Q8. How can you improve cache hit ratio?
  • 120Q9. What is origin shielding?
  • 121Q10. What is edge computing?
  • 122Q11. Can APIs use CDNs?
  • 123Q12. Why should private API responses not be casually cached?
  • 124Practical Exercise
  • 125Mini Project — Global Content Delivery System
  • 126Master Mental Model
  • 127Chapter Summary
  • 128CDN Fundamentals
  • 129Caching
  • 130Scalability
  • 131Media Delivery
  • 132Edge Computing
  • 133Security
  • 134Architecture
  • 135Chapter 08 Master Checklist
  • 136What Comes Next?
  • 137Chapter 09 — Database Fundamentals
In this chapter (137 sections)
01Chapter Overview02What Is a CDN?03What Is an Edge Location?04Origin Server05CDN Request Flow06Cache hit07Cache miss08Why CDN Improves Performance09CDN Is More Than a Cache10Static Content11Dynamic Content12Static vs Dynamic CDN Usage13Cache Hit14Cache Miss15Cache Hit Ratio16Cache Miss Ratio17TTL18Long TTL19Cache Busting20Cache-Control21Public vs Private Content22no-store23no-cache24Browser Cache vs CDN Cache25Cache Hierarchy26Cache Key27Cache Key Problem28Query String Caching29Cache Fragmentation30Cache Invalidation31Cache Invalidation Strategies32TTL expiration33Explicit purge34Versioned URLs35Revalidation36Explicit Purging37Versioned URLs38Stale Content39Origin Shielding40Cache Stampede41Preventing Cache Stampede42Request Coalescing43CDN for Images44CDN for Video45Video Segmentation46CDN and APIs47Edge Computing48Why Run Code at the Edge?49Edge Function Example50Edge vs Origin51Edge52Origin53Edge Limitations54Geographic Routing55Anycast56CDN + DNS57CDN + Load Balancer58CDN + Object Storage59Origin Architecture60DDoS Protection Concept61Web Application Firewall62CDN Security Consideration63Protecting the Origin64CDN Failure Scenarios65Scenario 1 — Edge failure66Scenario 2 — Origin failure67Scenario 3 — Cache purge failure68Scenario 4 — Bad cache configuration69Scenario 5 — CDN provider outage70CDN as Availability Layer71Cache-Control Example72CDN Design for a Blog73Cache Hit Ratio Optimization74Cache key75TTL76Content reuse77Object size78Cache policy79Regional distribution80Cache Eviction81LRU82LFU83CDN and Compression84CDN and HTTP/2 / HTTP/385CDN and Origin Protocols86Cache Warming87Cache Warming Trade-offs88CDN and Multi-Region Origin89CDN Failure vs Origin Failure90CDN failure91Origin failure92Cache Correctness93CDN Design Checklist94Content95Cache key96Freshness97Scale98Origin99Security100Failure101Common Mistakes102Mistake 1 — Caching everything103Mistake 2 — Thinking CDN automatically means low latency104Mistake 3 — Ignoring cache keys105Mistake 4 — Confusing no-cache with no-store106Mistake 5 — Ignoring cache invalidation107Mistake 6 — Exposing the origin directly108Mistake 7 — Ignoring cache stampedes109Mistake 8 — Moving complex logic to the edge110Mistake 9 — Ignoring private data111Interview Questions112Q1. What is a CDN?113Q2. How does a CDN reduce latency?114Q3. What is a cache hit?115Q4. What is a cache miss?116Q5. What is TTL?117Q6. What is cache invalidation?118Q7. What is cache stampede?119Q8. How can you improve cache hit ratio?120Q9. What is origin shielding?121Q10. What is edge computing?122Q11. Can APIs use CDNs?123Q12. Why should private API responses not be casually cached?124Practical Exercise125Mini Project — Global Content Delivery System126Master Mental Model127Chapter Summary128CDN Fundamentals129Caching130Scalability131Media Delivery132Edge Computing133Security134Architecture135Chapter 08 Master Checklist136What Comes Next?137Chapter 09 — Database Fundamentals

1. Chapter Overview#

So far, our architecture has evolved from a single server into a horizontally scalable application:

User
 ↓
DNS
 ↓
Load Balancer
 ↓
Application Servers
 ↓
Cache / Database

But there is an important problem.

If a user in India requests an image from an application server in the United States, the request may travel a long distance.

User in India
      ↓
      │ long network distance
      ↓
US Application Server

This increases:

  • latency
  • bandwidth usage
  • origin traffic
  • application load

A CDN — Content Delivery Network — can move frequently requested content closer to users.

Instead of:

User
 ↓
Origin

we can have:

User
 ↓
Nearest CDN Edge
 ├── Cache Hit → Response
 └── Cache Miss
        ↓
      Origin

This chapter explains:

  • what a CDN is
  • edge locations
  • origin servers
  • CDN caching
  • cache keys
  • TTL
  • cache-control
  • cache invalidation
  • cache hit ratio
  • static vs dynamic content
  • images and video delivery
  • origin shielding
  • edge computing
  • edge functions
  • geo-routing
  • DDoS protection concepts
  • CDN failure scenarios
  • CDN + load balancer architecture
  • practical CDN design

2. What Is a CDN?#

CDN stands for:

Content Delivery Network

A CDN is a geographically distributed network of servers designed to deliver content closer to end users.

Conceptually:

                    Origin
                       │
        ┌──────────────┼──────────────┐
        ↓              ↓              ↓
      Edge A         Edge B         Edge C
        │              │              │
      Users          Users          Users

Instead of every user contacting the origin, users can receive cached content from a nearby edge location.


3. What Is an Edge Location?#

An edge location is a location where CDN infrastructure is deployed close to users.

For example:

User in India
      ↓
India Edge
 
User in Europe
      ↓
Europe Edge
 
User in USA
      ↓
USA Edge

The exact routing depends on the CDN.

The goal is generally:

Serve content from infrastructure that is network-close to the user.


4. Origin Server#

The origin is the authoritative source from which the CDN obtains content.

For example:

CDN
 ↓
Origin
 ↓
Application / Object Storage

The origin could be:

  • application servers
  • object storage
  • web servers
  • media storage
  • API infrastructure

Example:

Origin
 ├── HTML
 ├── CSS
 ├── JavaScript
 ├── Images
 └── Video

5. CDN Request Flow#

Suppose the user requests:

https://example.com/logo.png

The request is routed to a CDN edge.

Cache hit#

User
 ↓
CDN Edge
 ↓
Cached logo.png
 ↓
User

The origin is not contacted.

Cache miss#

User
 ↓
CDN Edge
 ↓
Origin
 ↓
logo.png
 ↓
CDN Edge
 ↓
User

The edge can cache the object for future requests according to the configured policy.


6. Why CDN Improves Performance#

Without CDN:

100,000 users
       ↓
Origin

With CDN:

100,000 users
       ↓
CDN
 ├── 90,000 cache hits
 └── 10,000 origin requests

The origin sees far fewer requests.

This can improve:

  • latency
  • origin scalability
  • bandwidth consumption
  • availability for cached content

7. CDN Is More Than a Cache#

A modern CDN can provide:

  • caching
  • TLS termination
  • request routing
  • compression
  • image optimization
  • DDoS protection
  • WAF integration
  • bot controls
  • edge functions
  • traffic analytics

Therefore:

A CDN is a distributed edge platform, not merely a collection of cache servers.


8. Static Content#

CDNs are especially effective for static content.

Examples:

JavaScript
CSS
Images
Fonts
Videos
PDFs
Downloads

For example:

/app.js
/styles.css
/logo.png
/font.woff2

These objects can often be cached for long periods.


9. Dynamic Content#

Dynamic content is generated based on the request or user.

Example:

GET /profile

The response might depend on:

  • logged-in user
  • permissions
  • current database state
  • cookies
  • location
  • request parameters

Caching dynamic content requires much more careful design.


10. Static vs Dynamic CDN Usage#

Static Dynamic
Images Personalized profile
CSS Account balance
JS Private dashboard
Fonts User-specific API response
Public videos Real-time data

Static content is usually easier to cache safely.

Dynamic content can also be cached, but only with appropriate cache rules.


11. Cache Hit#

A cache hit occurs when the requested content is already available at the edge.

Request
 ↓
Edge
 ↓
Object exists
 ↓
Cache HIT
 ↓
Response

This is fast because the origin does not need to process the request.


12. Cache Miss#

A cache miss occurs when the edge does not have a usable cached copy.

Request
 ↓
Edge
 ↓
Cache MISS
 ↓
Origin
 ↓
Object
 ↓
Edge stores object
 ↓
Response

Future requests may become cache hits.


13. Cache Hit Ratio#

A key CDN metric is:

Cache Hit Ratio

Formula:

Cache Hit Ratio =
Cache Hits / Total Cache Requests

Example:

900,000 hits
100,000 misses

Total:

1,000,000

Hit ratio:

900,000 / 1,000,000
= 90%

A higher hit ratio generally means less origin traffic, assuming the cached responses are appropriate.


14. Cache Miss Ratio#

Similarly:

Miss Ratio =
Cache Misses / Total Requests

If:

Hit Ratio = 90%

then:

Miss Ratio = 10%

A low hit ratio can indicate:

  • highly dynamic content
  • poor cache keys
  • short TTLs
  • low object reuse
  • cache fragmentation
  • incorrect caching configuration

15. TTL#

TTL stands for:

Time To Live

TTL determines how long an object can remain fresh in a cache before it needs revalidation or replacement according to the caching policy.

Example:

Cache-Control: max-age=3600

means the response can be considered fresh for up to 3600 seconds under the relevant HTTP caching semantics.


16. Long TTL#

Static assets often benefit from long TTLs.

Example:

app.8f32a1.js

If the filename changes whenever the content changes:

app.v1.js
app.v2.js

then a long cache lifetime can be safer.

This pattern is called:

Cache busting / asset fingerprinting


17. Cache Busting#

Suppose:

app.js

is cached for one year.

You deploy a new version.

Users may still have:

old app.js

A common solution is content-based filenames:

app.a83f21.js

After a new build:

app.b92c11.js

The URL changes, so the CDN can treat it as a different object.


18. Cache-Control#

HTTP provides cache-control directives.

Example:

Cache-Control: public, max-age=3600

Other directives include:

private
no-cache
no-store
must-revalidate
s-maxage

The exact behavior depends on the caching layer and HTTP semantics.


19. Public vs Private Content#

A public response may be cacheable by shared caches.

Example:

Public homepage
Public logo
Public product image

A private response may be intended only for one user.

Example:

Account balance
Private messages
Personal dashboard

Never assume that putting content behind a CDN automatically makes it safe to cache.

Caching private content incorrectly can cause data leakage.


20. no-store#

no-store tells caches not to store the response.

This is useful for highly sensitive responses where storage in caches is not desired.

Example:

Cache-Control: no-store

Use it intentionally based on the data and caching requirements.


21. no-cache#

The name can be confusing.

no-cache does not necessarily mean:

"Never store this."

It generally means a stored response must be revalidated before reuse when the directive applies.

Therefore:

no-cache ≠ no-store

This is a common interview trap.


22. Browser Cache vs CDN Cache#

There can be multiple caching layers:

User
 ↓
Browser Cache
 ↓
CDN
 ↓
Reverse Proxy
 ↓
Application Cache
 ↓
Database

Each layer has different behavior and policies.

A response may be served from:

Browser

without making any network request.

Or:

CDN

without reaching the origin.


23. Cache Hierarchy#

A useful mental model:

              User
                ↓
          Browser Cache
                ↓
            CDN Edge
                ↓
          CDN Shield
                ↓
        Reverse Proxy
                ↓
         Application
                ↓
             Redis
                ↓
           Database

Not every system has every layer.

The principle is:

Keep frequently needed data as close to the consumer as safely possible.


24. Cache Key#

A cache key determines whether two requests should use the same cached object.

A simplistic key might be:

URL

For example:

https://example.com/image.jpg

But sometimes the response depends on:

URL
+ query parameters
+ host
+ selected headers
+ cookies

The exact cache key must match the response's variation rules.


25. Cache Key Problem#

Suppose:

/product?id=10

returns Product 10.

And:

/product?id=20

returns Product 20.

The query parameter must be considered appropriately in the cache key.

Otherwise:

Product 10

could accidentally be served for:

Product 20

Cache-key mistakes can be correctness and security bugs.


26. Query String Caching#

Suppose:

/image.jpg?width=100
/image.jpg?width=500

If width affects the response, the cache key needs to distinguish them.

Potentially:

Key 1 → image.jpg?width=100
Key 2 → image.jpg?width=500

But excessive query parameters can fragment the cache.

Therefore cache-key design is a major optimization problem.


27. Cache Fragmentation#

Suppose 1 million requests use:

/product?id=10&utm_source=A
/product?id=10&utm_source=B
/product?id=10&utm_source=C

If every tracking parameter becomes part of the cache key, the CDN may store many copies of effectively identical content.

This lowers the hit ratio.

Possible solution:

Normalize irrelevant parameters before constructing the cache key.

Only do this when those parameters truly do not affect the response.


28. Cache Invalidation#

A famous caching problem is:

How do we remove stale data?

Suppose:

Product price = ₹1,000

CDN caches it.

Price changes:

₹1,200

The CDN may still have:

₹1,000

until its TTL expires or it is invalidated.


29. Cache Invalidation Strategies#

Common strategies:

TTL expiration#

Wait until the object becomes stale.

Explicit purge#

Tell the CDN to remove a specific object.

Versioned URLs#

Change the URL when content changes.

Revalidation#

Ask the origin whether the cached representation is still valid.


30. Explicit Purging#

Example:

Purge:
/images/product-123.jpg

The CDN removes or invalidates the object.

This can be useful when updates must propagate quickly.

However, large-scale purge operations can be expensive or operationally complex depending on the platform.


31. Versioned URLs#

Instead of:

/logo.png

use:

/logo.v2.png

or:

/logo.8a32fd.png

Then a new version naturally becomes a different cache object.

This is often an excellent strategy for immutable assets.


32. Stale Content#

A CDN can sometimes serve stale content under carefully designed policies.

For example:

Fresh
 ↓
Stale
 ↓
Revalidate

Some architectures allow serving stale content temporarily if the origin is unavailable.

This can improve availability.

But stale serving must be appropriate for the data.

Serving a stale:

blog image

may be acceptable.

Serving stale:

account balance

may not be acceptable.


33. Origin Shielding#

Suppose many CDN edges miss the cache at the same time.

Without shielding:

Edge A ─┐
Edge B ─┼──→ Origin
Edge C ─┤
Edge D ─┘

Many requests can hit the origin.

An origin shield adds another caching layer:

Edge A ─┐
Edge B ─┼──→ Shield ──→ Origin
Edge C ─┤
Edge D ─┘

The shield can consolidate requests.


34. Cache Stampede#

Suppose a very popular object expires.

Millions of users request it simultaneously.

Object expires
      ↓
Many requests miss
      ↓
Many origin requests
      ↓
Origin overloaded

This is called a:

Cache stampede / thundering herd


35. Preventing Cache Stampede#

Possible techniques include:

  • request coalescing
  • stale-while-revalidate
  • randomized expiration
  • background refresh
  • locking
  • prewarming

The goal is to prevent every request from independently rebuilding the same cache entry.


36. Request Coalescing#

Suppose:

100 requests

all request the same missing object.

Instead of:

100 origin requests

the CDN or cache can coordinate:

100 requests
     ↓
1 origin request
     ↓
100 responses

This is request coalescing.


37. CDN for Images#

Image-heavy applications benefit significantly from CDNs.

Example:

User
 ↓
CDN
 ↓
image.jpg

The CDN can potentially provide:

  • caching
  • compression
  • format conversion
  • resizing
  • thumbnails
  • device-aware variants

Example:

Original:
4000 × 3000
 
Mobile:
800 × 600

Generating the appropriate representation can reduce bandwidth.


38. CDN for Video#

Video is particularly bandwidth-intensive.

Without CDN:

Millions of users
       ↓
Origin

This can overwhelm origin bandwidth.

With CDN:

Users
 ↓
CDN Edge
 ↓
Cached video segments

The origin only needs to supply content that is not already available at the edge.


39. Video Segmentation#

Large video files are often delivered as segments.

Conceptually:

Video
├── Segment 1
├── Segment 2
├── Segment 3
├── Segment 4
└── ...

CDNs can cache these segments independently.

This is useful for adaptive streaming systems.


40. CDN and APIs#

CDNs are not only for images.

Some APIs can also be cached.

For example:

GET /public/products

If the response is public and changes infrequently, caching at the edge may be appropriate.

But:

GET /account/balance

should not be casually cached in a shared CDN.


41. Edge Computing#

CDNs traditionally focus on content delivery.

Modern edge platforms can also execute code near users.

Instead of:

User
 ↓
Origin
 ↓
Application logic

some logic can run at the edge:

User
 ↓
Edge Function
 ↓
Response

This is:

Edge computing


42. Why Run Code at the Edge?#

Potential benefits:

  • lower latency
  • reduced origin traffic
  • faster personalization
  • geographic routing
  • request filtering
  • authentication decisions
  • lightweight transformations

Examples:

Redirect
A/B test assignment
Header normalization
Geo-based behavior
Bot filtering

43. Edge Function Example#

Suppose:

User from India

The edge function could route:

/api
 ↓
India region

User from Europe:

/api
 ↓
Europe region

The routing decision happens close to the user.


44. Edge vs Origin#

A useful distinction:

Edge#

Optimized for:

  • low latency
  • lightweight computation
  • routing
  • caching
  • filtering

Origin#

Optimized for:

  • complex business logic
  • databases
  • persistent state
  • long-running processing
  • authoritative data

Do not move everything to the edge.


45. Edge Limitations#

Edge environments often have constraints such as:

  • limited execution time
  • limited memory
  • restricted runtime APIs
  • limited filesystem access
  • distributed deployment complexity
  • data locality challenges

Therefore edge computing is usually best for lightweight operations.


46. Geographic Routing#

Suppose users are distributed globally:

India
Europe
USA
Australia

We can route users to nearby infrastructure.

India → India/Asia region
Europe → Europe region
USA → US region
Australia → Asia-Pacific region

This can reduce network latency.

However:

Geographic proximity does not always guarantee the lowest latency.

Actual network paths, congestion, and infrastructure placement matter.


47. Anycast#

Anycast allows multiple locations to advertise the same IP address.

The network routes users toward an appropriate location according to routing policies.

Conceptually:

Same IP
 ├── Edge A
 ├── Edge B
 └── Edge C

Users may reach different physical locations despite using the same destination IP.

Anycast is commonly used in global network infrastructure.


48. CDN + DNS#

A typical CDN architecture can involve DNS:

User
 ↓
DNS
 ↓
CDN endpoint
 ↓
Nearest / selected edge
 ↓
Cache
 ↓
Origin if needed

DNS can help direct users to the CDN infrastructure.

The CDN then handles request-level delivery.


49. CDN + Load Balancer#

A common architecture:

                       Internet
                           │
                           ▼
                         DNS
                           │
                           ▼
                          CDN
                       /       \
                Cache Hit     Cache Miss
                   │              │
                   ▼              ▼
                Client       Load Balancer
                                  │
                                  ▼
                            App Servers
                                  │
                                  ▼
                              Database

The CDN reduces the amount of traffic reaching the load balancer and application layer.


50. CDN + Object Storage#

Static assets are often stored in object storage:

Client
 ↓
CDN
 ↓
Object Storage

Example:

Images
Videos
PDFs
Downloads

This can separate media delivery from application compute.


51. Origin Architecture#

A scalable origin might be:

CDN
 ↓
Load Balancer
 ↓
App Servers
 ├── App 1
 ├── App 2
 └── App 3
 ↓
Object Storage / Database

The CDN becomes the first protection layer.


52. DDoS Protection Concept#

A distributed denial-of-service attack can generate huge amounts of traffic.

A CDN can absorb or filter some attacks at distributed edge locations.

Attack Traffic
      ↓
Distributed Edge
      ↓
Filtering / Mitigation
      ↓
Origin

The important idea is:

Do not allow all unwanted traffic to reach the origin.

CDN-based protection is only one part of a broader security architecture.


53. Web Application Firewall#

A WAF can inspect HTTP requests for suspicious patterns.

Conceptually:

User
 ↓
CDN
 ↓
WAF
 ↓
Origin

Potential protections include:

  • common injection patterns
  • malicious request signatures
  • abnormal traffic
  • application-specific rules

WAF behavior must be tuned carefully to avoid blocking legitimate users.


54. CDN Security Consideration#

A CDN does not automatically make an application secure.

You still need:

  • authentication
  • authorization
  • TLS
  • input validation
  • rate limiting
  • origin protection
  • access controls
  • secret management

The CDN is one security layer.


55. Protecting the Origin#

If the origin is directly reachable from the public internet, attackers may bypass the CDN.

Example:

User
 ├── CDN
 │    ↓
 │   Origin
 │
 └────────────→ Direct Origin IP

If direct origin access is not intended, infrastructure can restrict origin access to trusted CDN traffic.

The exact mechanism depends on the platform.


56. CDN Failure Scenarios#

Scenario 1 — Edge failure#

Traffic can potentially be routed to another edge.

Scenario 2 — Origin failure#

Cached content may continue working if policy permits.

Dynamic uncached requests may fail.

Scenario 3 — Cache purge failure#

Old content may remain until TTL/revalidation.

Scenario 4 — Bad cache configuration#

Private or incorrect content can be served to the wrong users.

Scenario 5 — CDN provider outage#

Traffic may require failover to another provider or origin path if the architecture supports it.


57. CDN as Availability Layer#

Caching can sometimes allow content to remain available even when the origin is temporarily unhealthy.

Example:

Origin → unavailable
 
Cached public content
       ↓
Still served

This can improve resilience.

But availability through stale cache must be explicitly designed.


58. Cache-Control Example#

For an immutable versioned asset:

Cache-Control: public, max-age=31536000, immutable

Conceptually:

Versioned asset
      ↓
Long cache lifetime

For a frequently changing public resource:

Cache-Control: public, max-age=60

For sensitive content:

Cache-Control: private, no-store

These are examples, not universal rules.


59. CDN Design for a Blog#

Suppose we have:

NextGen Blog

Content:

  • HTML
  • CSS
  • JS
  • images
  • article pages
  • public API
  • admin dashboard

A possible architecture:

                        Users
                          │
                          ▼
                         CDN
                    ┌─────┴─────┐
                    │           │
               Static/Public   Dynamic
                    │           │
                    ▼           ▼
              Cache / Edge   Load Balancer
                                │
                                ▼
                         Application Servers
                                │
                    ┌───────────┼───────────┐
                    ▼           ▼           ▼
                  Redis      Database    Object Storage

Public images and static assets can have long TTLs.

Private admin content should not be treated as public cacheable content.


60. Cache Hit Ratio Optimization#

Suppose:

Current hit ratio = 70%

We want to improve it.

Investigate:

1. Cache key#

Are irrelevant query parameters fragmenting the cache?

2. TTL#

Are objects expiring too quickly?

3. Content reuse#

Are requests actually repetitive?

4. Object size#

Are large objects causing eviction?

5. Cache policy#

Are public responses incorrectly marked uncacheable?

6. Regional distribution#

Does each edge receive enough repeated traffic?


61. Cache Eviction#

A cache has finite storage.

Suppose:

Cache capacity = 1 TB

but objects total:

10 TB

The cache must evict objects.

Common cache eviction concepts include:

  • LRU
  • LFU
  • TTL-based expiration

CDN implementations vary.

The key idea is:

A cache cannot retain every object forever.


62. LRU#

LRU means:

Least Recently Used

When the cache is full, remove objects that have not been accessed recently.

Conceptually:

Recently used
     ↑
     │
A B C D E
         ↓
    least recent

LRU works well when recently accessed objects are likely to be accessed again.


63. LFU#

LFU means:

Least Frequently Used

Remove objects with low access frequency.

This can be useful when some objects are consistently popular.

Different cache systems use different policies and optimizations.


64. CDN and Compression#

A CDN can compress content before delivery.

Example:

Origin
 ↓
Large HTML
 ↓
CDN compression
 ↓
Smaller response
 ↓
User

Compression can reduce bandwidth and latency.

Trade-off:

CPU cost
 ↕
Network savings

65. CDN and HTTP/2 / HTTP/3#

Modern CDNs commonly support modern HTTP protocols.

This can improve:

  • connection efficiency
  • multiplexing
  • transport behavior
  • performance

The CDN can terminate client-side HTTP/2 or HTTP/3 while using a different protocol toward the origin.

Thus:

Client
 ↓ HTTP/3
CDN
 ↓ HTTP/2 or HTTP/1.1
Origin

The exact configuration depends on the CDN and origin.


66. CDN and Origin Protocols#

The client-facing protocol does not necessarily need to match the origin-facing protocol.

Example:

Client
   ↓
HTTP/3
   ↓
CDN
   ↓
HTTP/2
   ↓
Origin

This abstraction allows the CDN to optimize each side independently.


67. Cache Warming#

Suppose we know a new product page will become extremely popular at 10 AM.

Instead of waiting for the first user to cause a cache miss, we can proactively populate the cache.

Before launch
 ↓
Fetch popular objects
 ↓
CDN cache populated
 ↓
Traffic spike
 ↓
High cache-hit rate

This is called:

Cache warming / prewarming


68. Cache Warming Trade-offs#

Benefits:

  • lower initial latency
  • reduced origin spike
  • better handling of predictable traffic

Costs:

  • additional prefetch traffic
  • unnecessary objects if demand is lower than expected
  • operational complexity

Use it when demand is sufficiently predictable.


69. CDN and Multi-Region Origin#

A global system may use multiple origins:

                CDN
             /       \
            ↓         ↓
        US Origin   India Origin
            │           │
            ▼           ▼
          Data        Data

The CDN can route misses to an appropriate origin.

This introduces additional concerns:

  • data consistency
  • replication
  • failover
  • routing
  • origin health

Multi-region data architecture will be studied later.


70. CDN Failure vs Origin Failure#

This distinction is important.

CDN failure#

The delivery layer itself is unavailable.

Potential strategies:

  • secondary CDN
  • direct origin fallback
  • DNS failover

Origin failure#

The CDN remains available.

Cached content may still work.

CDN
 ├── Cache HIT → works
 └── Cache MISS → origin fails

This can create partial availability.


71. Cache Correctness#

Performance is not more important than correctness.

Bad cache:

User A's private response
       ↓
Shared cache
       ↓
User B receives User A's data

This is a severe security failure.

Therefore always ask:

Who can receive this response?
Does the response vary by user?
Is it safe to share?
What forms part of the cache key?
How long can it remain fresh?

72. CDN Design Checklist#

For every CDN design, ask:

Content#

  • What should be cached?
  • What must never be cached?

Cache key#

  • URL?
  • Query parameters?
  • Headers?
  • Cookies?

Freshness#

  • TTL?
  • Revalidation?
  • Purge?

Scale#

  • Expected traffic?
  • Object sizes?
  • Hit ratio?

Origin#

  • Where is the source?
  • Can it handle cache misses?
  • Is origin protected?

Security#

  • TLS?
  • WAF?
  • Authentication?
  • Private content?

Failure#

  • What happens if the edge fails?
  • What happens if the origin fails?
  • What happens if the CDN provider fails?

73. Common Mistakes#

Mistake 1 — Caching everything#

Private or rapidly changing content may be unsafe or incorrect to cache.

Mistake 2 — Thinking CDN automatically means low latency#

Routing, cache misses, network congestion, and origin latency still matter.

Mistake 3 — Ignoring cache keys#

Incorrect keys can return incorrect content.

Mistake 4 — Confusing no-cache with no-store#

They have different semantics.

Mistake 5 — Ignoring cache invalidation#

Updated content may remain stale.

Mistake 6 — Exposing the origin directly#

Attackers may bypass CDN protections.

Mistake 7 — Ignoring cache stampedes#

Popular objects can create huge origin spikes after expiration.

Mistake 8 — Moving complex logic to the edge#

Edge environments are often intentionally constrained.

Mistake 9 — Ignoring private data#

CDN caching must respect authorization and privacy boundaries.


74. Interview Questions#

Q1. What is a CDN?#

A geographically distributed infrastructure layer that delivers content closer to users, commonly through caching and edge processing.


Q2. How does a CDN reduce latency?#

By serving content from an edge location closer to the user and reducing the distance to the origin.


Q3. What is a cache hit?#

The requested object is available in the cache and can be served without fetching it from the origin.


Q4. What is a cache miss?#

The cache does not have a usable copy, so the request may need to reach the origin.


Q5. What is TTL?#

The period for which a cached object can be considered fresh according to the applicable caching policy.


Q6. What is cache invalidation?#

The process of making a cached representation no longer usable so that newer content can be fetched or revalidated.


Q7. What is cache stampede?#

A large number of requests simultaneously miss or revalidate the same popular object, potentially overwhelming the origin.


Q8. How can you improve cache hit ratio?#

Investigate:

  • cache keys
  • TTLs
  • content reuse
  • irrelevant query parameters
  • caching policies
  • object popularity

Q9. What is origin shielding?#

An additional caching layer that reduces the number of requests from many CDN edges directly reaching the origin.


Q10. What is edge computing?#

Running selected lightweight computation closer to users rather than executing everything at a centralized origin.


Q11. Can APIs use CDNs?#

Yes, if the response is safe and appropriate to cache.


Q12. Why should private API responses not be casually cached?#

Because shared caching can accidentally expose one user's data to another user.


75. Practical Exercise#

Design a CDN architecture for a global image-sharing application.

Requirements:

100 million images
1 billion image requests/day
Global users
Low image latency
Images are mostly public
Users can replace images

Design:

User
 ↓
CDN
 ↓
Origin
 ↓
Object Storage

Answer:

  1. What is the cache key?
  2. What TTL should you consider?
  3. How will image updates work?
  4. Would you use versioned URLs?
  5. What happens during a cache miss?
  6. How will you protect the origin?
  7. How will you handle cache stampedes?
  8. What happens if the origin is temporarily unavailable?
  9. How will you measure cache performance?
  10. Would you use image resizing at the edge?

76. Mini Project — Global Content Delivery System#

Design:

                         Global Users
                              │
                              ▼
                         DNS / Routing
                              │
                              ▼
                         CDN Network
                    ┌─────────┼─────────┐
                    ▼         ▼         ▼
                  Edge A    Edge B    Edge C
                    │         │         │
                    └─────────┼─────────┘
                              ▼
                       Origin Shield
                              │
                              ▼
                        Load Balancer
                              │
                    ┌─────────┴─────────┐
                    ▼                   ▼
                App Servers        Object Storage
                    │
                    ▼
                  Cache
                    │
                    ▼
                Database

Implement/document:

  • cache policy
  • cache key
  • TTL strategy
  • purge strategy
  • origin protection
  • health checks
  • cache warming
  • monitoring
  • failure handling

77. Master Mental Model#

When designing a CDN, think:

                   USERS
                     │
                     ▼
                  ROUTING
                     │
                     ▼
                CDN EDGE
                     │
             ┌───────┴───────┐
             │               │
          HIT             MISS
             │               │
             ▼               ▼
          RESPONSE         ORIGIN
                             │
                             ▼
                           DATA

Then ask:

Can this response be cached?
        ↓
What is the cache key?
        ↓
How long can it remain fresh?
        ↓
How is it invalidated?
        ↓
What happens on a cache miss?
        ↓
Can the origin handle a miss storm?
        ↓
Can stale content be served safely?
        ↓
How is private data protected?
        ↓
What happens if the origin fails?
        ↓
What happens if the CDN fails?

That is the CDN design mindset.


78. Chapter Summary#

You should now understand:

CDN Fundamentals#

  • CDN
  • edge locations
  • origin
  • cache hit
  • cache miss
  • cache hit ratio
  • cache hierarchy

Caching#

  • TTL
  • Cache-Control
  • public vs private
  • no-cache
  • no-store
  • cache keys
  • cache fragmentation
  • invalidation
  • purging
  • versioned URLs
  • stale content
  • cache eviction
  • LRU
  • LFU

Scalability#

  • origin shielding
  • cache stampede
  • request coalescing
  • cache warming
  • CDN bandwidth reduction
  • origin protection

Media Delivery#

  • image delivery
  • image resizing
  • video delivery
  • video segments
  • object storage

Edge Computing#

  • edge functions
  • lightweight computation
  • geographic routing
  • Anycast
  • edge vs origin

Security#

  • DDoS protection concepts
  • WAF
  • origin protection
  • private content
  • cache correctness

Architecture#

  • CDN + DNS
  • CDN + load balancer
  • CDN + object storage
  • multi-region origin
  • CDN failure
  • origin failure

79. Chapter 08 Master Checklist#

Before moving forward, make sure you can explain:

  • What a CDN is
  • Edge location
  • Origin server
  • CDN request flow
  • Cache hit
  • Cache miss
  • Cache hit ratio
  • TTL
  • Cache-Control
  • public vs private caching
  • no-cache
  • no-store
  • Browser cache vs CDN cache
  • Cache hierarchy
  • Cache key
  • Query-string caching
  • Cache fragmentation
  • Cache invalidation
  • Explicit purge
  • Versioned URLs
  • Stale content
  • Origin shielding
  • Cache stampede
  • Request coalescing
  • Image CDN
  • Video CDN
  • API caching
  • Edge computing
  • Edge functions
  • Geographic routing
  • Anycast
  • CDN + DNS
  • CDN + load balancer
  • CDN + object storage
  • DDoS protection concepts
  • WAF
  • Origin protection
  • Cache eviction
  • LRU
  • LFU
  • Cache warming
  • Multi-region origin
  • CDN failure handling
  • Cache correctness

80. What Comes Next?#

Chapter 09 — Database Fundamentals#

We have now built the complete request-delivery path:

User
 ↓
DNS
 ↓
CDN
 ↓
Load Balancer
 ↓
Application Servers
 ↓
Cache
 ↓
???

The ??? is one of the most important components in almost every system:

The database.

In Chapter 09, we start databases from the ground up.

We will learn:

What is a database?
        ↓
Why databases exist
        ↓
Data models
        ↓
Tables / Rows / Columns
        ↓
Keys
        ↓
Relationships
        ↓
Indexes
        ↓
Transactions
        ↓
ACID
        ↓
SQL vs NoSQL
        ↓
Database scaling

We will establish the database fundamentals before moving into SQL databases, NoSQL databases, indexing, replication, partitioning, and sharding.

Finished this chapter?

Mark it as complete to track your mastery.

Previous ChapterChapter 07 — Load BalancersNext ChapterChapter 09 — Database Fundamentals
PrevNext