System DesignMastery
--Foundations — ভিত্তি তৈরি

CDN & Object Storage

Duration৩০-৪৫ মিনিট
LevelBeginner
FocusStatic Assets
001Core Concept

CDN ও Object Storage কী?

ধরুন আপনি ঢাকায় বসে Netflix এ একটা movie দেখছো। সেই movie র file কি USA এর server থেকে আসছে? না! Netflix CDN এর মাধ্যমে সেই file টা আপনার কাছাকাছি একটা server এ (হয়তো Singapore বা Mumbai তে) cache করে রাখে। আপনি সেখান থেকেই পাচ্ছেন — ১০x faster

দুটো Key Concept

CDN (Content Delivery Network): বিশ্বের বিভিন্ন স্থানে PoP (Point of Presence) servers রেখে static content (images, videos, CSS, JS) কাছে থেকে serve করে। Latency কমায়।

Object Storage (S3-like): Files, images, videos কে key-value store এ রাখা। Unlimited storage, highly durable (99.999999999% — 11 nines!), cheap। Database এর মতো query করা যায় না কিন্তু files store এর জন্য perfect।

CDN ছাড়া vs CDN সহ

ঢাকা → USA server: ~200-300ms latency। ঢাকা → Singapore CDN PoP: ~30-50ms latency। ৫-১০x faster! Netflix, YouTube, Facebook সবাই CDN use করে। CDN ছাড়া global scale impossible।

002CDN How it Works

CDN কীভাবে কাজ করে?

CDN এর মূল concept হলো Edge Caching। User এর request প্রথমে nearest CDN edge server এ যায়। Cache hit হলে সেখান থেকেই response। Miss হলে origin server থেকে content fetch করে cache করে রাখে।

CDN GLOBAL ARCHITECTURE

🏢 Origin Server

USA (us-east-1)

distributes to PoPs

⚡ PoP: London

EU users ~10ms

⚡ PoP: Singapore

BD users ~35ms

⚡ PoP: Mumbai

IN users ~5ms

⚡ PoP: Tokyo

JP users ~5ms

⚡ PoP: New York

US users ~5ms

BD User → Singapore PoP: ~35ms ✓  |  Without CDN (USA): ~250ms ✗

CDN Cache Control

কতক্ষণ CDN এ cache থাকবেন সেটা Cache-Control header দিয়ে control করা যায়।

cache-control.txt
# Static assets — দীর্ঘ সময় cache করুন
Cache-Control: public, max-age=31536000, immutable
# ১ বছর cache (হ্যাশ-based filename use করুন)

# HTML pages — কম সময়
Cache-Control: public, max-age=3600
# ১ ঘণ্টা cache

# Private (user-specific) — CDN cache করবেন না
Cache-Control: private, no-cache
# Browser cache করতে পারে, CDN পারবেন না

# Never cache করুন না
Cache-Control: no-store
# Real-time data, sensitive information
CDN ProviderGlobal PoPsBest ForPriceDDoS Protection
Cloudflare300+DDoS protection, global sitesFree tier available✅ Built-in
AWS CloudFront450+AWS ecosystem integrationPay per use✅ WAF Integration
Fastly100+Programmable CDN, edge computeExpensive✅ Add-on
Akamai4000+Enterprise, largest networkVery expensive✅ Enterprise-grade
003Object Storage (S3)

AWS S3 — Object Storage

S3 (Simple Storage Service) হলো AWS এর object storage। File upload করুন, একটা URL পান — ব্যস। Database এর মতো complex না, শুধু key-value: key = file path, value = file content

S3 Core Concepts

Bucket: Files এর container (folder এর মতো)। Globally unique name।

Object: একটা file + metadata।

Key: Object এর path/name।

Storage Class: Standard (frequent access), Glacier (archival, cheap), Intelligent-Tiering (auto)।

কখন S3 ব্যবহার করবো এবং করবো না

✅ S3 ব্যবহার করুন

User uploaded files (images, videos, documents), Static website hosting, Backup and archive, Application logs, ML training data।

❌ S3 ব্যবহার করুন না

Frequently updated structured data (database use করুন), Real-time queries needed, Strong consistency needed, File system operations (rename, move costly)।

S3 Storage Classes

ClassAccessCostUse Case
S3 StandardInstantHighestFrequently accessed — profile photos, app assets
S3 Standard-IAInstant30% cheaperInfrequent access — backups, older files
S3 GlacierMinutes/hoursVery cheapLong-term archive — compliance, audit logs
Glacier Deep Archive12 hoursCheapest7-10 year retention, rarely accessed
Intelligent-TieringInstantAuto-optimizeUnknown access pattern — auto moves between tiers

Cost Saving Tip — Lifecycle Policy

S3 Lifecycle Policy দিয়ে auto-transition করুন: প্রথম ৩০ দিন Standard, ৩০-৯০ দিন S3-IA, ৯০+ দিন Glacier। এতে automatically cost কমে। Instagram এই approach এ petabytes of photos manage করে।

004CloudFront

AWS CloudFront — CDN

CloudFront হলো AWS এর CDN। S3 এর সাথে perfectly integrate হয়। S3 bucket কে origin set করুন, CloudFront globally distribute করবেন।

S3 + CLOUDFRONT INTEGRATION

👤 User

Bangladesh

DNS lookup

☁️ CloudFront

Edge: Singapore PoP

Cache HIT → serve ✓

Cache MISS → fetch origin

on miss only

🗂️ S3 Origin

us-east-1

images/, videos/

static assets

95%+ requests served from edge — origin barely touched

CloudFront Key Features

Origin Shield: Origin এর সামনে extra caching layer — origin এ আরো কম requests।

Lambda@Edge: CDN edge এ code run করুন — geolocation, A/B testing, auth।

Signed URLs: Private content এ time-limited access।

WAF Integration: DDoS এবং bot protection।

005Full Architecture

Production-Ready Media Upload Architecture

একটা social media app এ user photo upload করলেন কীভাবে S3 + CloudFront কাজ করে:

Presigned URL: Direct S3 upload (API server bandwidth save হয়)

UPLOAD FLOW DIAGRAM

📱 User

1. Request upload URL →

🔌 API Server

generate presigned URL

← 2. presigned URL

📱 User

3. Direct upload to S3 (no server!) →

🗂️ S3

raw-uploads/

4. S3 Event →

⚡ Lambda

resize: 800px, 400px, thumbnail

5. Store processed →

S3 + CloudFront

cdn.app.com/

photo_800.webp

Presigned URL — কেন Important?

User file upload করলেন API server এর bandwidth waste হবে। Presigned URL দিলে user সরাসরি S3 তে upload করে। API server শুধু temporary signed URL generate করে — নিজে file handle করে না। Security maintained, bandwidth saved।

006Code Examples

হাতে-কলমে Code

Python — S3 Upload & Presigned URL

s3_operations.py
import boto3
from botocore.exceptions import NoCredentialsError

s3 = boto3.client(
    's3',
    aws_access_key_id='YOUR_KEY',
    aws_secret_access_key='YOUR_SECRET',
    region_name='ap-southeast-1'  # Singapore
)

# ── File Upload ────────────────────────────────
def upload_file(local_path, bucket, s3_key):
    try:
        s3.upload_file(
            local_path, bucket, s3_key,
            ExtraArgs={
                'ContentType': 'image/webp',
                'CacheControl': 'public, max-age=31536000',
                'ACL': 'public-read'
            }
        )
        print(f"✅ Uploaded to s3://{bucket}/{s3_key}")
        return f"https://cdn.myapp.com/{s3_key}"
    except NoCredentialsError:
        raise Exception("AWS credentials not found")

# ── Presigned URL — Direct Browser Upload ──────
def generate_presigned_url(bucket, s3_key, expiry=3600):
    url = s3.generate_presigned_url(
        ClientMethod='put_object',
        Params={
            'Bucket': bucket,
            'Key': s3_key,
            'ContentType': 'image/jpeg'
        },
        ExpiresIn=expiry  # 1 hour
    )
    print(f"⏰ Presigned URL expires in {expiry}s")
    return url

# ── Lifecycle Policy — Auto archive ────────────
s3.put_bucket_lifecycle_configuration(
    Bucket='my-app-uploads',
    LifecycleConfiguration={
        'Rules': [{
            'ID': 'auto-archive',
            'Status': 'Enabled',
            'Transitions': [
                {'Days': 30, 'StorageClass': 'STANDARD_IA'},
                {'Days': 90, 'StorageClass': 'GLACIER'},
            ]
        }]
    }
)

Node.js — Express + S3 Upload API

upload_api.js
const { S3Client, PutObjectCommand } = require('@aws-sdk/client-s3');
const { getSignedUrl } = require('@aws-sdk/s3-request-presigner');
const { v4: uuidv4 } = require('uuid');

const s3 = new S3Client({ region: 'ap-southeast-1' });

// Generate presigned URL for direct browser upload
app.post('/api/upload-url', async (req, res) => {
  const { fileType, fileName } = req.body;

  // Unique key prevent overwrite
  const key = `uploads/${uuidv4()}-${fileName}`;

  const command = new PutObjectCommand({
    Bucket: 'my-app-bucket',
    Key: key,
    ContentType: fileType,
  });

  // URL expires in 15 minutes
  const uploadUrl = await getSignedUrl(s3, command, { expiresIn: 900 });
  const publicUrl = `https://cdn.myapp.com/${key}`;

  res.json({ uploadUrl, publicUrl, key });
  // Frontend: PUT uploadUrl সরাসরি, তারপর publicUrl save করুন
});
007Interview Prep

Common Interview Questions

Q1: CDN ব্যবহার না করলেন কী হবে?

উত্তর: Global users কে origin server থেকে serve করতে হবে। USA → Bangladesh: ~250ms latency। CDN সহ: Singapore PoP → ~35ms। ৭x slow। Large files (videos) এ এটা catastrophic। Origin server এ extra load।

Q2: CDN Cache Invalidation কীভাবে করবেন?

উত্তর: ৩টা approach: (১) Versioned filenames — logo.v2.png (সবচেয়ে reliable)। (২) CloudFront Invalidation API — নির্দিষ্ট paths invalidate করুন (কিছুটা delay)। (৩) Short TTL — frequent updates এর files এ কম TTL দিন।

Q3: S3 vs Database — কখন কোনটা?

উত্তর: S3 — Binary files (images, video, PDF), Large objects, No complex queries, High durability cheap। Database — Structured data, Complex queries (JOIN, filter), Transactions needed, Frequently updated। Instagram: Photos → S3, User data/likes/comments → PostgreSQL।

Q4: Presigned URL কেন ব্যবহার করবেন?

উত্তর: File upload এ API server কে bypass করা। Client সরাসরি S3 এ upload করে → API server এর bandwidth ও CPU save। Time-limited URL (15 mins expire) → secure। Server scaling করতে হয় না শুধু uploads এর জন্য।

008Lesson Summary

SUMMARY — আজকে যা শিখলাম

Conceptএক লাইনে
CDNEdge servers এ content cache — globally fast delivery
Object Storage (S3)Files/images/videos store করুন — unlimited, cheap, durable
CloudFrontAWS CDN — S3 + CloudFront = globally fast static content
Presigned URLClient সরাসরি S3 তে upload — API server bypass
Cache-ControlCDN কতক্ষণ cache রাখবে সেটা control করুন
S3 LifecycleAuto-archive পুরানো files — cost save
PoPCDN এর edge location — users এর কাছাকাছি
009Knowledge Check
010Assignments
011Practical Lab
🎉

Phase 2 সম্পন্ন!

আপনি System Design Mastery Course এর Phase 2 — Core Components সম্পন্ন করেছেনো! ৬টা critical topic master করেছেনো যেগুলো প্রতিটা large-scale system এ use হয়।

Caching Strategy & Redis
Load Balancing (L4/L7)
Message Queues (Kafka, RabbitMQ)
API Design (REST, GraphQL, gRPC)
Database Sharding & Replication
CDN & Object Storage (S3)

System Design Patterns

Circuit Breaker · CQRS · Event Sourcing · Saga Pattern