Chuyển đến nội dung chính

Lesson 6: CDN (Content Delivery Network) - Global acceleration

What is a CDN and how does it work? Push CDN vs Pull CDN. Cache Invalidation strategies. Multi-tier CDN architecture. Edge Computing. Compare CloudFlare, AWS CloudFront, Fastly. Use cases and anti-patterns.

🏗️ Architecture — Lesson 6 Lesson 6: CDN (Content Delivery Network) - Global acceleration

System Architecture: From Zero to Hero

Part 2: Infrastructure Components

xdev.asia

Introduction

If the server is located in Singapore, users in Hanoi have to wait ~50ms roundtrip for each request. Users in the US have to wait ~200ms. CDN solves this problem by placing content as close to the user as possible.


1. What is CDN?

CDN is a globally distributed network of proxy servers, serving content from locations closest to users.

Không có CDN:
  User (Hà Nội) ──── 200ms ────► Origin Server (US)

Có CDN:
  User (Hà Nội) ──── 10ms ────► CDN Edge (Hà Nội)
                                    │ cache miss
                                    ▼
                              CDN Edge ── 200ms ──► Origin Server (US)
                                    │ cache result
                                    ▼
  User (Hà Nội) ──── 10ms ────► CDN Edge (Hà Nội)  ← Lần sau = 10ms!

1.1 CDN Architecture

                    Origin Server
                         │
              ┌──────────┼──────────┐
              ▼          ▼          ▼
         ┌────────┐ ┌────────┐ ┌────────┐
         │Regional│ │Regional│ │Regional│
         │  PoP   │ │  PoP   │ │  PoP   │
         │ (Asia) │ │  (EU)  │ │ (US)   │
         └───┬────┘ └───┬────┘ └───┬────┘
         ┌───┴───┐  ┌───┴───┐  ┌───┴───┐
         │Edge   │  │Edge   │  │Edge   │
         │Servers│  │Servers│  │Servers│
         └───────┘  └───────┘  └───────┘
             ▲           ▲          ▲
           Users       Users      Users

2. Push CDN vs Pull CDN

2.1 Push CDN

Origin Server ──push──► CDN Edge
  Khi content thay đổi, origin chủ động push lên CDN

Flow:
  1. Developer deploy new image
  2. CI/CD pipeline push image to CDN
  3. CDN distributes to all edges
  4. User request → Edge server → Return immediately
AdvantagesDisadvantages
Content is always availableMust manage push process
There is no "first request" delayConsumes storage on all edges
Full ControlComplicated when content changes a lot

Best for: Static content with few, small changes

2.2 Pull CDN

User ──request──► CDN Edge
  Edge: "Tôi không có content này"
  Edge ──request──► Origin Server
  Origin ──response──► Edge
  Edge: cache content + return to user

Lần sau:
  User ──request──► CDN Edge
  Edge: "Tôi có rồi!" → Return from cache
AdvantagesDisadvantages
Automatic, no management neededFirst request is slow (cache miss)
Only cache content is requestedNeed TTL strategy
Easy setupCache stampede risk

Best for: Dynamic content, high traffic


3. Cache Invalidation Strategies

3.1 TTL (Time To Live)

CDN cache product image với TTL = 1 giờ
  T=0:  User request → Cache MISS → Fetch from origin → Cache 1 giờ
  T=30m: User request → Cache HIT → Return cached
  T=61m: Cache expired → Fetch from origin → Cache lại

Trade-off: TTL ngắn = fresh hơn nhưng nhiều origin hits
           TTL dài = nhanh hơn nhưng content có thể cũ

3.2 Cache Purge

CDN API: DELETE /cache?url=https://blog.xdev.asia/images/logo.png
→ Xóa content khỏi tất cả edge servers

Use case: Cập nhật logo, fix typo trong hình ảnh

3.3 Cache Busting

Thay đổi URL khi content thay đổi:

Trước: /style.css
Sau:   /style.css?v=2
Hoặc:  /style.a1b2c3d4.css (hash trong filename)

→ CDN coi đây là content mới → fetch from origin

3.4 Stale-While-Revalidate

Cache expired, nhưng:
  1. Trả cached content ngay (stale)
  2. Đồng thời fetch fresh content từ origin
  3. Update cache khi origin respond

→ User luôn nhận response nhanh
→ Content cuối cùng sẽ fresh

4. Edge Computing

Traditional CDN:
  Edge chỉ serve static files

Edge Computing:
  Edge chạy code (logic) tại edge location

Ví dụ Cloudflare Workers:
  - A/B testing tại edge
  - Geolocation-based redirects
  - Authentication tại edge
  - Image resizing tại edge
  - API response transformation

5. Compare CDN Providers

FeaturesCloudFlareAWS CloudFrontFastly
PoPs300+450+90+
Edge ComputeWorkersLambda@EdgeCompute@Edge
Free tierGenerousLimitedNone
Price$$$$$$
DDoS protectionBuilt-inAWS ShieldLimited
Best forGeneral, small-mediumAWS ecosystemPerformance-critical

6. CDN Anti-patterns

Anti-patternProblemSolution
Cache personalized contentUser A sees data User BCache-Control: private
Too long TTL for APIData staleShort TTL + stale-while-revalidate
Do not use CDN for APISlow API in remoteCache GET APIs at edge
CDN for everythingPOST/PUT/DELETE via CDNCDN only for GET requests

Summary

ConceptsKey Takeaway
CDNServe content from the location closest to the user
Push vs PullPush for static, Pull for dynamic
Cache InvalidationTTL + purge + cache busting
Edge ComputingRun logic at the edge, reduce latency

Exercises

  1. CDN Strategy: Design CDN strategy for e-commerce site with: product images (few changes), product prices (change frequently), user profile (personalized).

  2. Cache Invalidation: Blog platform needs to update posts as soon as the author edits. Design cache invalidation strategy.

  3. Cost Estimation: Website has 10M page views/day, each page is 2MB (500KB HTML + 1.5MB images). Estimated CDN bandwidth/month and cost (CloudFront: $0.085/GB).