System Design

CDN (Content Delivery Network)

CDN — foydalanuvchiga eng yaqin serverdan content yetkazish tizimi.

Muammo: Latency

Siz San Francisco’dasiz, server Tokyo’da:

User (SF) → Tokyo Server
Distance: 8,000 km
Latency: 150-200 ms 

Har bir request 200ms. Sahifa 50 ta resurs yuklasa → 10 sekund!

Yechim: CDN

CDN global edge serverlarda content nusxalaydi:

User (SF) → San Francisco CDN
Distance: 10 km
Latency: 5-10 ms 

40x tezroq!

CDN qanday ishlaydi?

Edge locations

CDN dunyoning ko’p shaharlarida serverlar (edge locations):

┌─────────────┐
│ Origin      │ ← Asosiy server (masalan, AWS Oregon)
│ Server      │
└──────┬──────┘

┌──────┴───────────────────────────────┐
│                                      │
▼                ▼                     ▼
┌────────┐    ┌────────┐         ┌────────┐
│CDN Edge│    │CDN Edge│         │CDN Edge│
│New York│    │London  │         │Tokyo   │
└────────┘    └────────┘         └────────┘

Cloudflare: 300+ shaharlarda
AWS CloudFront: 400+ edge locations

Request flow

1. User (London) → image.jpg so'raydi

2. DNS → Eng yaqin CDN edge (London)

3. London CDN:
   - Cache'da bormi? Tekshiradi
   
4a. CACHE HIT 
   - Cache'dan qaytaradi (5ms)
   
4b. CACHE MISS 
   - Origin serverdan oladi (150ms)
   - Cache'ga saqlaydi
   - User'ga qaytaradi
   
5. Keyingi London userlari → Cache Hit (5ms) 

Birinchi user: Sekin (150ms)
Keyingi userlar: Tez (5ms)

Push vs Pull CDN

Pull CDN (Ko’proq qo’llaniladi)

CDN o’zi kerakli contentni oladi:

User → CDN (cache yo'q)
CDN → Origin (contentni oladi)
CDN → User (va cache'laydi)

Setup:

// Siz faqat CDN URL ishlatasz
<img src="https://cdn.example.com/logo.png">

// CDN avtomatik origin'dan oladi:
// Origin: https://origin.example.com/logo.png

Afzalliklari:

Kamchiliklari:

Qachon: Dinamik saytlar, ko’p content

Push CDN

Siz contentni CDN’ga oldindan yuklaysiz:

Deploy vaqti:
Your Server → CDN (barcha static files)

User request:
User → CDN (allaqachon bor) 

Setup:

npm run build

aws s3 sync ./dist s3://cdn-bucket
aws cloudfront create-invalidation

Afzalliklari:

Kamchiliklari:

Qachon: Static saytlar (Jamstack), kam o’zgaradigan content

Cache Control

CDN qachongacha cache’laydi?

Cache-Control header

Cache-Control: max-age=3600

Cache-Control: max-age=31536000, immutable

Cache-Control: no-cache, no-store, must-revalidate

Best practice:

location ~* \.(jpg|png|gif|svg|ico)$ {
    # Images: 1 yil
    add_header Cache-Control "public, max-age=31536000, immutable";
}

location ~* \.(js|css)$ {
    # JS/CSS: 1 yil (versioning bilan)
    add_header Cache-Control "public, max-age=31536000, immutable";
}

location ~* \.(html)$ {
    # HTML: Cache'lama (har doim yangi)
    add_header Cache-Control "no-cache, must-revalidate";
}

Versioning (Cache busting)

Muammo: File o’zgarsa, CDN eski versionni ko’rsatadi.

Yechim: URL’ga version qo’shish

<!-- Bad: URL bir xil -->
<link rel="stylesheet" href="/style.css">

<!-- Good: Hash/version qo'shish -->
<link rel="stylesheet" href="/style.a3f5b9.css">
<link rel="stylesheet" href="/style.css?v=1.2.3">

Webpack/Vite avtomatik qiladi:

style.css → style.a3f5b9c2.css
app.js → app.7f3e8d1a.js

Yangi deploy → yangi hash → yangi URL → CDN cache bypass

CDN’da nimalar cache’lanadi?

Static content

Images:  .jpg, .png, .gif, .svg, .webp
Styles:  .css
Scripts: .js
Fonts:   .woff, .woff2, .ttf
Videos:  .mp4, .webm
Docs:    .pdf

Dynamic content (odatda)

API responses: /api/users
Personalized: Dashboard, cart
Real-time: Stock prices, scores

Lekin: Ba’zi API’lar ham cache’lanishi mumkin (qisqa TTL bilan).

Cache Invalidation

Content o’zgarsa, CDN cache’ni yangilash:

1. Wait for TTL

Cache-Control: max-age=3600

1 soatdan keyin avtomatik yangilanadi.

Kamchilik: 1 soat eski content

2. Purge/Invalidate

CDN’ga “bu file’ni o’chir” deyish:

curl -X POST "https://api.cloudflare.com/client/v4/zones/{id}/purge_cache" \
  -H "Authorization: Bearer {token}" \
  -d '{"files":["https://example.com/style.css"]}'

aws cloudfront create-invalidation \
  --distribution-id E1234 \
  --paths "/style.css" "/script.js"

** Narx:** Ba’ziлари pul oladi (AWS: 1000 path free/month)

3. Versioning (Eng yaxshi!)

<!-- Eski -->
<link rel="stylesheet" href="/style.v1.css">

<!-- Yangi deploy -->
<link rel="stylesheet" href="/style.v2.css">

Yangi URL = CDN yangi file oladi. Invalidation kerak emas!

CDN provayderlar

Cloudflare (Ko’p ishlatiladi)

Bepul plan (cheksiz bandwidth!)
Global: 300+ cities
DDoS protection
SSL bepul
 Pro: $20/month

AWS CloudFront

AWS bilan integratsiya
400+ edge locations
 Pay-as-you-go: $0.085/GB
 Qimmatroq (lekin AWS ecosystem uchun)

Cloudinary (Images uchun)

Image optimization
Auto format (WebP, AVIF)
Resize, crop, filters
 Free: 25GB/month

Vercel Edge Network

Jamstack uchun ideal
Automatic
Next.js bilan juda yaxshi
 Hobby: bepul

CDN Performance optimizations

1. Image optimization

<!-- Bad: Katta PNG -->
<img src="photo.png" width="800"> <!-- 3MB -->

<!-- Good: Optimized WebP -->
<img src="photo.webp" width="800"> <!-- 200KB -->

<!-- Best: Responsive + modern format -->
<picture>
  <source srcset="photo.avif" type="image/avif">
  <source srcset="photo.webp" type="image/webp">
  <img src="photo.jpg" alt="Photo">
</picture>

Cloudinary:

https://res.cloudinary.com/demo/image/upload/
  w_800,f_auto,q_auto/sample.jpg

2. Lazy loading

<!-- Viewport'da bo'lsa yuklaydi -->
<img src="image.jpg" loading="lazy">

3. Preload critical resources

<!-- Muhim CSS/JS ni oldindan yuklash -->
<link rel="preload" href="critical.css" as="style">
<link rel="preload" href="critical.js" as="script">

4. HTTP/2 Server Push

CDN bir requestda bir nechta filelarni yuboradi:
Request: index.html
Response: index.html + style.css + script.js

Security: CDN va DDoS

CDN DDoS hujumlardan himoya qiladi:

Normal traffic:  10K req/sec → CDN handle qiladi
DDoS attack:     1M req/sec → CDN filter qiladi
Origin server:   10K req/sec (faqat real traffic)

DDoS protection:

Real-world misollar

Netflix

- Custom CDN: Open Connect
- 17,000+ servers
- ISP'larda serverlar
- Result: Internetning 15% trafigi

Spotify

- Google Cloud CDN
- Audio chunks cache
- Regional edge servers
- Result: <100ms latency

Instagram

- Facebook CDN
- Image optimization
- 1000+ edge locations
- Result: Instant photo load

Best Practices

  1. Barcha static content CDN’da

    • Images, CSS, JS, fonts
  2. Long cache TTL + versioning

    • Cache: 1 yil
    • Filename: app.{hash}.js
  3. Image optimization

    • WebP/AVIF format
    • Resize to actual size
    • Lazy load
  4. Separate domain

    • static.example.com or cdn.example.com
    • Cookie yuborilmaydi (performance++)
  5. Monitor performance

    • Cache hit rate > 90%
    • P95 latency < 50ms

Xulosa

CDN:

Setup:

  1. CDN provayder tanlash (Cloudflare yaxshi start)
  2. DNS sozlash
  3. Cache-Control headerlar qo’yish
  4. Image optimization

Natija:

Keyingi dars: Reverse Proxy va API Gateway.