Case Study: Design YouTube — Video Streaming Platform

“YouTube giống một đài truyền hình quốc gia — nhưng thay vì một kênh chiếu cho tất cả, mỗi người xem một kênh khác nhau, cùng lúc hàng triệu người. Và ‘đài truyền hình’ đó phải phát mượt mà trên mọi thiết bị, mọi tốc độ mạng, mọi quốc gia.”

Tags: system-design case-study video-streaming youtube cdn transcoding alex-xu Student: Hieu Prerequisite: Tuan-02-Back-of-the-envelope · Tuan-03-Networking-DNS-CDN · Tuan-08-Message-Queue Lien quan: Tuan-06-Cache-Strategy · Tuan-07-Database-Sharding-Replication · Tuan-13-Monitoring-Observability · Tuan-15-Data-Security-Encryption Reference: Alex Xu, System Design Interview Vol 1 — Chapter 14: Design YouTube


0. Context & Why — Tại sao Video Streaming khó?

0.1 Analogie: Đài truyền hình quốc gia thời đại số

hãy tưởng tượng một đài truyền hình quốc gia. Trước đây, đài phát một kênh duy nhất — tất cả mọi người cùng xem một chương trình. Đơn giản.

Bây giờ tưởng tượng mỗi người xem một kênh khác nhau, cùng lúc. Người xem phim hành động 4K, người xem clip hài 360p trên điện thoại 3G, người tải video lên, người đang stream live. Tất cả diễn ra đồng thời với hàng triệu người.

Đó chính là YouTube. Và đó là lý do nó là một trong những bài toán system design khó nhất.

0.2 Những thách thức cốt lõi

Thách thứcGiải thíchVì sao khó?
Data volumeVideo là data type nặng nhất — 1 phút video 1080p ~ 150MBKhông gì trong web lớn bằng video
BandwidthStreaming cần băng thông liên tục, không phải burst như text/imageMỗi user tiêu thụ 2-5 Mbps liên tục
DiversityMuôn vàn thiết bị: TV 4K, điện thoại cũ, tablet, laptopPhải transcode ra nhiều resolution + codec
GlobalUser ở mọi nơi trên thế giớiCDN phải phủ khắp, latency phải thấp
CostCDN bandwidth là chi phí #1 — lên tới hàng tỷ USD/nămTối ưu chi phí CDN là sống còn
Upload vs WatchUpload ít nhưng nặng (processing), Watch nhiều nhưng nhẹ (serving)Hai pipeline hoàn toàn khác nhau

0.3 YouTube theo số liệu thực tế (tham khảo)

MetricCon sốÝ nghĩa
DAU~2 tỷGần 1/4 dân số thế giới
Video được upload mỗi phút500 giờKhông bao giờ xem hết
Tổng video đã upload> 800 triệuPetabyte-scale storage
Avg watch time/user/day~30 phútEngagement cực cao
Số resolution cần transcode5-8144p, 240p, 360p, 480p, 720p, 1080p, 1440p, 4K
CDN cost/năm (ước tính)$1-5 tỷChi phí lớn nhất của YouTube

Aha Moment: Video streaming không phải là “gửi file cho user.” Nó là chia file thành hàng ngàn mảnh nhỏ (segments), chọn đúng resolution cho từng thời điểm, và gửi từng mảnh một — giống như đút cơm cho bạn bé, từng muỗng một, đúng tốc độ bạn bé nuốt được.


1. Step 1 — Understand the Problem & Establish Design Scope

1.1 Clarifying Questions (Câu hỏi làm rõ)

Trong interview, luôn hỏi trước khi thiết kế. Dưới đây là các câu hỏi quan trọng:

Câu hỏiTrả lờiGhi chú
Những feature nào cần thiết kế?Upload video + Stream videoCore features
Clients nào?Mobile app, web browser, smart TVMulti-platform
DAU bao nhiêu?5 triệuQuy mô trung bình-lớn
Thời gian xem trung bình/ngày?30 phútEngagement metric
Cần hỗ trợ nhiều resolution?Có — từ 240p đến 4KAdaptive bitrate
Cần hỗ trợ nhiều ngôn ngữ?Có — subtitle, audio tracksi18n
Video dài tối đa bao lâu?12 giờ (như livestream rerun)Ảnh hưởng storage
Cần DRM (bảo vệ bản quyền)?Đặc biệt cho premium content
Upload file tối đa bao lớn?256 GBCho video dài, 4K
Có phân biệt user miễn phí và trả tiền?Có — priority transcodingBusiness logic

1.2 Functional Requirements (Yêu cầu chức năng)

  • FR1: Upload video — user upload video từ client, hệ thống xử lý và lưu trữ
  • FR2: Stream video — user xem video mượt mà, không giật lag
  • FR3: Multi-resolution — tự động chuyển đổi video thành nhiều resolution (240p → 4K)
  • FR4: Adaptive bitrate — tự động điều chỉnh chất lượng theo tốc độ mạng của user
  • FR5: Search — tìm kiếm video theo title, description, tags
  • FR6: Thumbnail generation — tự động tạo thumbnail cho mỗi video
  • FR7: Video metadata — title, description, view count, like/dislike, comments
  • FR8: Resumable upload — nếu upload bị gián đoạn, tiếp tục từ chỗ đang dở

1.3 Non-functional Requirements (Yêu cầu phi chức năng)

RequirementTargetGiải thích
Availability99.99%Video platform là entertainment — downtime = mất user
Latency (playback start)< 2 giâyUser nhấn play → video phải bắt đầu trong 2s
Buffering ratio< 1%Tỷ lệ thời gian user phải đợi buffer
Upload reliability99.9%Upload không được mất file
Scalability5M DAU, scale to 50MThiết kế cho tương lai
Durability99.999999999% (11 nines)Video upload lên rồi → không bao giờ mất
Global reachServe từ CDN gần nhấtUser ở VN xem video phải nhanh như user ở Mỹ

1.4 Phạm vi thiết kế (Out of scope)

Để tập trung, chúng ta không thiết kế:

  • Recommendation engine (ML-based) — chỉ thiết kế data pipeline cho nó
  • Comment system — đã có trong case study khác
  • Live streaming — chỉ focus vào Video-on-Demand (VOD)
  • Monetization / Ads system
  • Content moderation chi tiết (chỉ overview)

2. Step 2 — Propose High-Level Design

2.1 Hai luồng chính (Two Main Flows)

toàn bộ YouTube có thể chia thành hai luồng chính hoàn toàn khác nhau:

LuồngMô tảĐặc điểm
Video Upload PipelineUser upload video → hệ thống xử lý → lưu trữ → phân phốiWrite-heavy, CPU-intensive, async
Video StreamingUser nhấn play → hệ thống trả về video segmentsRead-heavy, bandwidth-intensive, real-time

Key Insight: Hai luồng này có yêu cầu hoàn toàn khác nhau. Upload cần processing power (transcoding). Streaming cần bandwidth (CDN). Thiết kế riêng biệt cho từng luồng.

2.2 High-Level Architecture Overview

graph TB
    subgraph Clients
        A[Web Browser]
        B[Mobile App]
        C[Smart TV]
    end

    subgraph "Upload Flow"
        D[API Gateway / Load Balancer]
        E[Upload Service]
        F[Original Video Storage<br/>Blob Store]
        G[Transcoding Service<br/>DAG Scheduler]
        H[Transcoded Video Storage<br/>Blob Store]
        I[Thumbnail Generator]
        J[Metadata Service]
        K[Message Queue<br/>Kafka/RabbitMQ]
    end

    subgraph "Streaming Flow"
        L[CDN Edge Server]
        M[CDN Regional Server]
        N[CDN Origin Server]
        O[Metadata Cache<br/>Redis]
    end

    subgraph "Data Stores"
        P[(Video Metadata DB<br/>MySQL/Vitess)]
        Q[(User Activity DB<br/>Cassandra)]
        R[Search Index<br/>Elasticsearch]
    end

    A & B & C -->|Upload| D
    D --> E
    E --> F
    E -->|Trigger| K
    K --> G
    G --> H
    G --> I
    H --> N
    E --> J
    J --> P
    J --> R

    A & B & C -->|Stream| L
    L -->|Cache miss| M
    M -->|Cache miss| N
    N -->|Fetch| H

    J --> O
    O --> L

2.3 Component Overview

ComponentChức năngTech stack (ví dụ)
API GatewayAuthentication, rate limiting, routingKong, AWS API Gateway
Upload ServiceNhận file, chia chunk, lưu vào blob storeCustom service + pre-signed URL
Original StorageLưu video gốc trước khi transcodeAWS S3, Google Cloud Storage
Transcoding ServiceChuyển đổi video thành nhiều resolution/codecFFmpeg workers, AWS Elastic Transcoder
Transcoded StorageLưu video đã transcode ở mọi resolutionS3, GCS (riêng bucket)
CDNPhân phối video đến userCloudFront, Akamai, Google CDN
Metadata ServiceQuản lý thông tin videoREST API + MySQL/Vitess
Message QueueDecouple upload và transcodingKafka, RabbitMQ → Tuan-08-Message-Queue
CacheCache metadata, CDN configRedis → Tuan-06-Cache-Strategy

3. Step 3 — Design Deep Dive

3.1 Video Upload Pipeline — Chi tiết

3.1.1 Upload Flow chi tiết

Khi user upload video, đây là toàn bộ quy trình diễn ra:

Bước 1 — Pre-signed URL

  • Client gọi API: “Tôi muốn upload video, file size = 2GB”
  • API Server kiểm tra authentication, quota, file type
  • Nếu hợp lệ → tạo pre-signed upload URL trỏ thẳng tới Blob Storage (S3)
  • Client upload trực tiếp lên S3, không đi qua API server → giảm tải server

Tại sao pre-signed URL? Nếu 1000 user upload cùng lúc, mỗi file 2GB, API server phải xử lý 2TB bandwidth. Với pre-signed URL, traffic đi thẳng vào S3 (designed for massive throughput). API server chỉ xử lý metadata (nhẹ).

Bước 2 — Chunked Upload (Resumable)

  • File 2GB được chia thành nhiều chunks (thường 5-10MB/chunk)
  • Client upload từng chunk một
  • Nếu bị mất mạng → chỉ cần upload lại chunk bị lỗi, không phải upload lại từ đầu
  • Server theo dõi progress: chunk 1/400 ✓, chunk 2/400 ✓, … chunk 235/400 ✗ (retry)

Bước 3 — Original Storage

  • Khi tất cả chunks đã upload xong → S3 ghép lại thành file hoàn chỉnh
  • File gốc được lưu vĩnh viễn (hoặc theo retention policy)
  • Một event được push vào Message Queue → trigger transcoding pipeline

Bước 4 — Transcoding (xem phần 3.1.2)

Bước 5 — CDN Distribution

  • Video đã transcode được push lên CDN origin
  • CDN tự động replicate ra edge servers khi có request

Bước 6 — Metadata Update

  • Sau khi transcode xong, Metadata DB được update:
    • Video status: “processing” → “ready”
    • Available resolutions: [240p, 360p, 480p, 720p, 1080p]
    • Duration, thumbnail URL, manifest file URL
  • User nhận notification: “Video đã sẵn sàng!“

3.1.2 Video Transcoding — DAG Architecture

Đây là phần phức tạp nhất của toàn bộ hệ thống. Transcoding không phải chỉ là “chuyển 1080p thành 720p.” Nó là một DAG (Directed Acyclic Graph) gồm nhiều bước:

graph TD
    A[Original Video File] --> B[Video Splitting<br/>Chia thanh segments]
    B --> C1[Segment 1]
    B --> C2[Segment 2]
    B --> C3[Segment 3]
    B --> C4[Segment N...]

    C1 --> D1[Encode H.264 1080p]
    C1 --> D2[Encode H.264 720p]
    C1 --> D3[Encode H.264 480p]
    C1 --> D4[Encode H.264 360p]
    C1 --> D5[Encode H.264 240p]
    C1 --> D6[Encode VP9 1080p]
    C1 --> D7[Encode VP9 720p]
    C1 --> D8[Encode AV1 1080p]

    C2 --> E1[Encode H.264 1080p]
    C2 --> E2[Encode H.264 720p]
    C2 --> E3[...]

    D1 & D2 & D3 & D4 & D5 & D6 & D7 & D8 --> F[Merge Segments<br/>Per resolution/codec]

    A --> G[Audio Extraction]
    G --> G1[AAC 128kbps]
    G --> G2[AAC 256kbps]
    G --> G3[Opus 128kbps]

    A --> H[Thumbnail Generation<br/>Extract key frames]
    H --> H1[Thumbnail 1]
    H --> H2[Thumbnail 2]
    H --> H3[Thumbnail 3]

    A --> I[Watermark Overlay<br/>Optional - for copyright]

    F --> J[Generate Manifest Files<br/>HLS .m3u8 / DASH .mpd]
    G1 & G2 & G3 --> J
    J --> K[Upload to Transcoded Storage]
    K --> L[Push to CDN Origin]
    L --> M[Update Metadata DB<br/>Status = Ready]

3.1.3 Tại sao dùng DAG?

Lý doGiải thích
ParallelismMỗi segment được encode độc lập → chạy song song trên nhiều worker
FlexibilityDễ dàng thêm/bớt resolution, codec, bước xử lý mới
Fault toleranceNếu encode segment 5 lỗi → chỉ retry segment 5, không phải làm lại từ đầu
PriorityEncode 720p trước (phổ biến nhất) → user xem được sớm hơn
Resource efficiencyMỗi task có resource requirement khác nhau → schedule thông minh

3.1.4 Video Codecs — H.264 vs VP9 vs AV1

CodecƯu điểmNhược điểmDùng khi nào
H.264 (AVC)Hỗ trợ 99% thiết bị, decode nhanhFile lớn hơnDefault cho mọi video
VP9Nhỏ hơn H.264 ~30%, free (Google)Encode chậm hơn 10xChrome, Android, YouTube web
AV1Nhỏ hơn VP9 ~20%, freeEncode cực chậm (50-100x H.264)Content phổ biến, tiết kiệm bandwidth
HEVC (H.265)Nhỏ hơn H.264 ~40%License fee đắt, hỗ trợ thiết bị hạn chếApple ecosystem, Smart TV

Chiến lược của YouTube thực tế: Encode H.264 cho tất cả video (compatibility). Với video popular (nhiều view), encode thêm VP9 và AV1 để tiết kiệm bandwidth CDN — vì chi phí encode 1 lần nhưng tiết kiệm bandwidth cho hàng triệu lượt xem.

3.1.5 Transcoding Queue và Priority

Không phải mọi video đều được transcode như nhau:

PriorityĐối tượngXử lý
P0 — CriticalPaid creators (YouTube Partner)Encode ngay, dedicated workers
P1 — HighVideo từ channel lớn (>1M subs)Queue riêng, timeout ngắn
P2 — NormalUser thườngQueue chung, best-effort
P3 — LowRe-encode video cũ sang codec mớiChỉ chạy lúc off-peak (2AM-6AM)

Implement bằng multiple message queues với priority khác nhau:

graph LR
    A[Upload Event] --> B{Priority<br/>Router}
    B -->|P0| C[Critical Queue<br/>Dedicated Workers]
    B -->|P1| D[High Queue<br/>Auto-scaling Workers]
    B -->|P2| E[Normal Queue<br/>Shared Workers]
    B -->|P3| F[Low Queue<br/>Spot Instances Only]

    C --> G[Transcoding Worker Pool]
    D --> G
    E --> G
    F --> G

    G --> H[Transcoded Storage]

Cost optimization: P3 jobs (re-encode video cũ) chỉ chạy trên spot instances (rẻ hơn 70-90% so với on-demand). Nếu spot bị recall → job tự động quay lại queue, đợi spot instance mới.

3.2 Video Streaming — Adaptive Bitrate

3.2.1 Streaming Protocol: HLS và DASH

Khi user nhấn “Play,” điều gì xảy ra?

Bước 1: Client request manifest file (playlist)

  • HLS: file .m3u8
  • DASH: file .mpd

Bước 2: Manifest file chứa danh sách tất cả resolution có sẵn và URL của từng segment:

#EXT-X-STREAM-INF:BANDWIDTH=800000,RESOLUTION=640x360
360p/segment_001.ts
360p/segment_002.ts
...

#EXT-X-STREAM-INF:BANDWIDTH=2400000,RESOLUTION=1280x720
720p/segment_001.ts
720p/segment_002.ts
...

#EXT-X-STREAM-INF:BANDWIDTH=5000000,RESOLUTION=1920x1080
1080p/segment_001.ts
1080p/segment_002.ts
...

Bước 3: Client đo bandwidth hiện tại → chọn resolution phù hợp

Bước 4: Client tải từng segment (thường 2-10 giây/segment)

Bước 5: Nếu bandwidth thay đổi (vào thang máy, chuyển từ WiFi sang 4G) → client tự động chuyển resolution cho segment tiếp theo

Đây là Adaptive Bitrate Streaming (ABR) — Key của trải nghiệm xem video mượt. Thay vì buffer và chờ, player giảm resolution để video tiếp tục chạy.

3.2.2 So sánh HLS và DASH

Tiêu chíHLS (Apple)DASH (MPEG)
DeveloperAppleMPEG consortium (open standard)
Container.ts (Transport Stream).mp4 fragments
Manifest.m3u8.mpd (XML)
DRM supportFairPlayWidevine, PlayReady
Browser supportSafari native, others via JSChrome, Firefox, Edge
Latency10-30s (có thể giảm với Low-Latency HLS)3-10s
YouTube dùng?Có (cho iOS/Safari)Có (cho Android/Chrome)

Thực tế: YouTube dùng cả hai — HLS cho Apple ecosystem, DASH cho phần còn lại. Player tự động chọn protocol phù hợp.

3.2.3 Adaptive Bitrate Flow

sequenceDiagram
    participant User as User/Player
    participant CDN as CDN Edge
    participant Origin as Origin/Storage

    User->>CDN: GET /video/abc123/manifest.m3u8
    CDN-->>User: Manifest (list of resolutions + segment URLs)

    Note over User: Bandwidth = 5 Mbps → Chon 1080p

    User->>CDN: GET /video/abc123/1080p/seg_001.ts
    CDN-->>User: Segment 1 (1080p)

    User->>CDN: GET /video/abc123/1080p/seg_002.ts
    CDN-->>User: Segment 2 (1080p)

    Note over User: Bandwidth giam xuong 1.5 Mbps<br/>(vao thang may)

    User->>CDN: GET /video/abc123/480p/seg_003.ts
    CDN-->>User: Segment 3 (480p) ← Tu dong ha resolution

    User->>CDN: GET /video/abc123/480p/seg_004.ts
    CDN-->>User: Segment 4 (480p)

    Note over User: Bandwidth phuc hoi 8 Mbps<br/>(ra khoi thang may)

    User->>CDN: GET /video/abc123/1080p/seg_005.ts
    CDN-->>User: Segment 5 (1080p) ← Tu dong tang resolution

    Note over User: Pre-fetch: Player tai truoc<br/>2-3 segments tiep theo

3.2.4 Pre-fetching Strategy

Player thông minh không chỉ tải segment hiện tại mà còn tải trước (pre-fetch) các segment tiếp theo:

StrategyMô tảKhi nào dùng
Eager pre-fetchTải trước 3-5 segmentsWiFi/unlimited data, user đang xem liên tục
Conservative pre-fetchTải trước 1-2 segmentsMobile data, user hay skip
No pre-fetchChỉ tải segment hiện tạiBandwidth cực thấp, user chưa nhấn Play
Quality pre-fetchTải trước resolution thấp, replace bằng resolution cao khi rảnhBandwidth biến động

Aha Moment: Pre-fetching là lý do bạn thấy thanh buffer chạy trước vị trí đang xem trên YouTube. Nó giúp video tiếp tục chạy ngay cả khi mạng chậm đột ngột trong 2-3 giây.

3.3 CDN Architecture — Đa tầng (Multi-tier)

3.3.1 CDN là gì và tại sao là chi phí #1?

CDN (Content Delivery Network) là mạng lưới server phân tán trên toàn cầu, cache nội dung gần user nhất có thểTuan-03-Networking-DNS-CDN.

Với video streaming, CDN bandwidth chính là chi phí lớn nhất:

Hạng mục chi phí% tổng chi phí (ước tính)Ghi chú
CDN bandwidth50-70%Chi phí #1, không thể tránh
Storage (S3/GCS)10-15%Video gốc + transcoded
Transcoding compute10-15%CPU-intensive
Metadata infra (DB, cache)5-10%Tương đối rẻ
Network (non-CDN)3-5%Inter-region transfer
Other (monitoring, etc.)2-5%

3.3.2 CDN Multi-tier Architecture

graph TD
    subgraph "Tier 1 — Edge (PoP)"
        E1[Edge HCM<br/>Cache: Hot content<br/>TTL: 24h]
        E2[Edge Ha Noi<br/>Cache: Hot content<br/>TTL: 24h]
        E3[Edge Bangkok<br/>Cache: Hot content<br/>TTL: 24h]
        E4[Edge Tokyo<br/>Cache: Hot content<br/>TTL: 24h]
        E5[Edge SF<br/>Cache: Hot content<br/>TTL: 24h]
    end

    subgraph "Tier 2 — Regional"
        R1[Regional Singapore<br/>Cache: Warm content<br/>TTL: 7 days]
        R2[Regional US-West<br/>Cache: Warm content<br/>TTL: 7 days]
        R3[Regional EU-West<br/>Cache: Warm content<br/>TTL: 7 days]
    end

    subgraph "Tier 3 — Origin"
        O1[Origin Storage<br/>US-East<br/>All content]
        O2[Origin Storage<br/>EU-Central<br/>All content]
    end

    E1 & E2 & E3 -->|Cache miss| R1
    E4 -->|Cache miss| R1
    E5 -->|Cache miss| R2

    R1 -->|Cache miss| O1
    R2 -->|Cache miss| O1
    R3 -->|Cache miss| O2

    O1 <-->|Cross-region<br/>replication| O2

3.3.3 Push vs Pull CDN

KiểuCách hoạt độngƯu điểmNhược điểmDùng cho
PushServer chủ động đẩy content lên CDN trước khi có requestLượt xem đầu tiên cũng nhanh (đã có cache)Tốn storage, đẩy nội dung không ai xemVideo trending, popular creators
PullCDN chỉ fetch content khi có request đầu tiên (cache miss)Tiết kiệm storage, chỉ cache content thực sự cầnRequest đầu tiên chậm (phải fetch từ origin)Long-tail content (video ít view)

Chiến lược kết hợp: Video mới từ popular creators (>100K subs) → Push lên edge ngay. Video từ user thường → Pull khi có người xem.

3.3.4 Long-tail Content Strategy

Thực tế, phân bố view của YouTube tuân theo Power Law (quy luật lũy thừa):

  • Top 1% video chiếm ~80% tổng view → đẩy lên CDN edge, cache lâu
  • Top 10% video chiếm ~95% tổng view → cache ở regional CDN
  • Bottom 90% video (“long-tail”) chiếm ~5% tổng view → serve từ origin, không cache
TierContent typeCache policyChi phí/view
Edge (expensive)Top 1% — trending, viralCache 24h, push proactivelyThấp nhất (đã cache)
Regional (moderate)Top 10% — popular, recentCache 7 ngày, pull-basedTrung bình
Origin (cheapest storage)Bottom 90% — long-tailKhông cache trên CDNCao nhất (fetch từ origin)

Aha Moment: Nếu bạn cache tất cả video trên CDN edge → chi phí CDN sẽ gấp 10-20 lần. Bí quyết là chỉ cache những gì thực sự được xem nhiều. Đây là lý do YouTube chi tiêu hàng tỷ USD/năm cho CDN mà vẫn phải tối ưu liên tục.

3.4 Metadata System

3.4.1 Video Metadata DB

TrườngTypeGiải thích
video_idUUID / Snowflake IDPrimary key, globally unique
titleVARCHAR(500)Tiêu đề video
descriptionTEXTMô tả, có thể dài
uploader_idBIGINT (FK)Người upload
statusENUMuploading, processing, ready, failed, deleted
duration_secondsINTThời lượng
file_size_bytesBIGINTKích thước file gốc
upload_timeTIMESTAMPThời gian upload
available_resolutionsJSON[“240p”, “360p”, “480p”, “720p”, “1080p”]
manifest_urlVARCHAR(1000)URL tới HLS/DASH manifest
thumbnail_urlsJSONMảng URL thumbnails
view_countBIGINTSố lượt xem (eventual consistent)
like_countBIGINTSố lượt thích
categoryVARCHAR(100)Thể loại
tagsJSONTags cho search
is_publicBOOLEANVideo công khai hay riêng tư
drm_protectedBOOLEANCó bảo vệ DRM không

Chọn DB: MySQL với Vitess (sharding layer) hoặc CockroachDB — vì metadata cần strong consistency (không được hiển thị video chưa transcode xong).

Sharding key: video_id — phân bố đều, query chính là theo video_id.

3.4.2 User Activity Data

Data typeVolumeStorageGiải thích
Watch historyCực lớnCassandra / BigTableMỗi user xem ~20 video/ngày
Search historyLớnElasticsearchFull-text search
Like/dislikeLớnMySQL (counter) + KafkaEvent-driven update
Watch progressCực lớnRedis (TTL) → Cassandra”Tiếp tục xem từ 15:32”
Recommendation dataCực lớnBigQuery / Data warehouseML pipeline input

Lưu ý: View count là eventually consistent. YouTube không đảm bảo view count chính xác tức thời — nó được aggregate theo batch (mỗi 5-10 phút) để giảm write load.

3.4.3 Search Index

Video metadata được index vào Elasticsearch để hỗ trợ full-text search:

Trường được indexBoost weightGiải thích
title10xQuan trọng nhất
description3xPhụ, nhưng có nhiều keyword
tags5xCreator tự gắn tag
channel_name7xSearch theo kênh
captions/subtitles1xTìm trong phụ đề (cực mạnh)

3.5 Error Handling & Reliability

3.5.1 Resumable Upload

Vấn đềGiải phápChi tiết
Mất mạng giữa uploadChunked upload + checksumClient ghi nhớ chunk cuối thành công, retry từ đó
File corruptMD5/SHA256 checksum per chunkServer verify từng chunk, reject nếu sai
Upload timeoutPre-signed URL có TTL (thường 24h)Quá hạn → client request URL mới
Duplicate uploadIdempotency key (hash của file)Nếu cùng file → không upload lại
Server crashUpload state lưu trong durable storageKhởi động lại → đọc state, tiếp tục

3.5.2 Transcoding Error Handling

LỗiXử lýRetry policy
Segment encode failRetry segment đó (không phải cả video)3 lần, exponential backoff (1s → 2s → 4s)
Worker crashTask quay lại queue, worker khác pick upHeartbeat timeout = 30s
Out of memoryRetry trên worker có nhiều RAM hơnScale up worker class
Corrupt inputMark video = “failed,” thông báo userKhông retry — user cần upload lại
Timeout (encode quá lâu)Chia segment nhỏ hơn, retryDynamic segment sizing

3.5.3 Streaming Error Handling

Vấn đềGiải pháp
CDN edge downDNS failover sang edge khác (automatic)
Segment 404 (chưa cache)CDN pull từ regional → origin
Bandwidth dropABR tự động hạ resolution
Video bị xóa giữa lúc xemGraceful error message, gợi ý video khác
Region-specific outageCross-region CDN failover

3.5.4 Pre-signed URL Security

BướcChi tiết
1. Client request uploadGửi authentication token + file metadata
2. Server validateKiểm tra token, quota, file type allowed
3. Generate pre-signed URLURL chứa: bucket, key, expiration, signature
4. Client upload trực tiếpUpload thẳng lên S3 với pre-signed URL
5. URL hết hạnSau 1-24h, URL không còn sử dụng được
6. Playback URLCũng dùng pre-signed URL với TTL ngắn (vd 6h) → chống share link trái phép

3.6 Cost Optimization — Chiến lược sống còn

3.6.1 CDN Cost Optimization

Đây là phần quan trọng nhất về mặt business — vì CDN chiếm 50-70% chi phí:

Chiến lượcTiết kiệmChi tiết
Long-tail từ origin30-40% CDN cost90% video ít view → serve từ origin (S3 bandwidth rẻ hơn CDN)
Regional CDN selection10-20%Dùng CDN rẻ hơn ở region ít traffic (VD: dùng ISP CDN cho VN thay vì Akamai)
Codec optimization20-30% bandwidthVP9/AV1 cho popular video → giảm bandwidth 20-30% per view
Off-peak transcoding40-60% computeTranscode video không gấp vào lúc 2AM-6AM, dùng spot instances
Intelligent caching15-25% CDN costCache TTL based on popularity — hot video cache lâu, cold video cache ngắn
Peer-to-peer (P2P)10-30% CDN costCho phép viewers share segments với nhau (WebRTC)
Multi-CDN10-15%Dùng nhiều CDN provider, route traffic theo giá + performance

3.6.2 Storage Cost Optimization

Chiến lượcChi tiết
Tiered storageVideo mới → S3 Standard. Sau 30 ngày → S3 Infrequent Access. Sau 1 năm → S3 Glacier
Delete old resolutionsVideo >2 năm, không ai xem → xóa resolution thấp (240p, 360p), giữ 720p + 1080p
Lazy transcodingVideo mới: chỉ encode 720p + 1080p trước. 240p, 360p, 4K → chỉ encode khi có request
DeduplicationDetect video trùng lặp (fingerprinting) → không lưu 2 bản

3.6.3 Transcoding Cost Optimization

Chiến lượcChi tiết
Spot instancesDùng AWS Spot / GCP Preemptible cho P2, P3 jobs → rẻ hơn 70-90%
Reserved capacityP0, P1 jobs chạy trên reserved instances → đảm bảo availability
Off-peak schedulingP3 jobs (re-encode) chỉ chạy 2AM-6AM khi giá compute rẻ nhất
Right-sizingVideo ngắn (<1 phút) → worker nhỏ. Video dài (>1h) → worker lớn với nhiều CPU
Hardware accelerationDùng GPU (NVENC) hoặc dedicated hardware (AWS MediaConvert) cho encode nhanh hơn 5-10x

4. Capacity Estimation — Ước lượng chi tiết

4.1 Assumptions

Thông sốGiá trịGiải thích
DAU5,000,0005M daily active users
Avg watch time/day30 phútEngagement trung bình
Avg video bitrate (streaming)2.5 MbpsTrung bình giữa 480p và 1080p
Upload users/day0.1% DAU5,000 creators upload/day
Avg upload video duration10 phútTrung bình
Avg upload video size (original)1.5 GB1080p, 10 phút
Transcoding expansion factor3x1 video gốc → ~3x storage (nhiều resolution)
Video segment size4 giâyCho HLS/DASH

4.2 Storage Estimation

Upload storage mỗi ngày (video gốc):

Transcoded storage mỗi ngày (nhiều resolution):

Tổng storage mỗi ngày:

Storage 1 năm:

Chi phí storage (AWS S3 Standard ~ $0.023/GB/month):

Lưu ý: Con số này chưa tính tiered storage (chuyển video cũ sang S3 IA/Glacier sẽ giảm 50-70%).

4.3 Bandwidth Estimation — Streaming

Concurrent viewers (peak):

Bandwidth peak:

Aha Moment: 781 Gbps là con số khổng lồ. Đây là lý do YouTube cần mạng lưới CDN toàn cầu với hàng ngàn edge server — không một data center đơn lẻ nào có thể serve lượng bandwidth này.

Bandwidth trung bình:

Data transfer mỗi ngày:

Chi phí CDN bandwidth (AWS CloudFront ~ $0.02/GB ở scale lớn):

Đây là chi phí CDN cho 5M DAU. YouTube với 2 tỷ DAU → nhân lên ~400x (nhưng được discount volume). Đây là lý do CDN cost là #1 expense.

4.4 Transcoding Compute Estimation

Số video cần transcode mỗi ngày:

Trung bình mỗi video cần encode ra 6 resolution × 2 codec = 12 variants:

Thời gian encode trung bình 1 variant (10 phút video):

Tổng compute time (giả định 70% H.264, 30% VP9):

Số workers cần (mỗi worker 1 vCPU, chạy 20h/day):

Chi phí (AWS c5.xlarge spot ~ $0.05/h):

4.5 Tổng hợp chi phí

Hạng mụcChi phí/tháng%
CDN bandwidth$1,700,00072%
Storage (S3)$253,00011%
Transcoding compute$42,7502%
Metadata infra (DB, cache, search)$150,0006%
Network (non-CDN)$120,0005%
Monitoring, ops, other$100,0004%
Tổng~$2,365,750100%

Validation: CDN chiếm 72% — đúng với industry benchmark (50-70%). Con số này xác nhận rằng CDN cost optimization là ưu tiên #1.


5. Security — Bảo mật Video Platform

5.1 DRM (Digital Rights Management)

DRM bảo vệ nội dung có bản quyền (phim, show, music video) khỏi bị sao chép trái phép.

DRM SystemPlatformSử dụng bởi
Widevine (Google)Chrome, Android, ChromecastYouTube, Netflix, Disney+
FairPlay (Apple)Safari, iOS, Apple TVYouTube (trên iOS), Apple TV+
PlayReady (Microsoft)Edge, Xbox, WindowsYouTube (trên Edge), Netflix

Cách DRM hoạt động:

BướcChi tiết
1. Encrypt videoMỗi segment được encrypt bằng AES-128 key
2. License serverKey được lưu trên License Server (không gửi cùng video)
3. Client request licensePlayer gửi device info + authentication → License Server
4. License Server validateKiểm tra: user có quyền xem? Device hợp lệ? Region cho phép?
5. Trả về licenseLicense chứa decryption key, có TTL (vd 24h)
6. Client decrypt & playPlayer decrypt segments in-memory, không lưu file giải mã

Lưu ý: DRM không phải bulletproof — luôn có cách bypass (screen recording). Nhưng nó tăng chi phí cho piracy, đủ để bảo vệ cho đa số use case.

YouTube dùng hệ thống Content ID để phát hiện vi phạm bản quyền:

BướcChi tiết
1. FingerprintingMỗi video được tạo “fingerprint” (audio + visual) khi upload
2. Database matchingFingerprint được so sánh với database của copyright holders
3. Match foundNếu match → tự động: block video, cho chạy nhưng chia doanh thu, hoặc chỉ track
4. Appeal processUploader có thể khiếu nại (dispute) nếu là fair use
Kỹ thuậtGiải thích
Audio fingerprintingChromaprint / Shazam-like — trích xuất melody, rhythm, tạo hash
Visual fingerprintingPerceptual hashing — so sánh frame-by-frame, chịu được crop/resize
Temporal matchingKhông chỉ match toàn bộ video mà còn match 1 đoạn (vd: 30 giây nhạc nền)

5.3 Abuse Prevention

Loại abuseGiải pháp
Illegal contentML-based scanning (CSAM detection, violence detection) trước khi publish
Spam uploadRate limiting per user, CAPTCHA cho upload, file type validation
View bottingAnomaly detection: IP clustering, behavioral analysis, không đếm view từ bot
DDoSCDN-level protection (Cloudflare, AWS Shield), rate limiting → Tuan-09-Rate-Limiter
Account takeover2FA, suspicious login detection, session management

5.4 Pre-signed URL cho Upload và Playback

Use caseTTLGiải thích
Upload URL1-24hĐủ thời gian upload file lớn, nhưng không quá lâu để bị leak
Playback manifest URL6-12hĐủ cho 1 session xem, hết hạn → client request mới
Playback segment URL1-6hNgắn hơn manifest, vì segment URL được refresh liên tục
Thumbnail URL30 ngàyThumbnail công khai, không cần bảo mật cao

5.5 Watermarking cho Leak Tracking

Loại watermarkChi tiếtDùng khi
Visible watermarkLogo/text hiển thị trên videoNgăn sao chép re-upload
Invisible watermarkEmbed thông tin user vào pixel data (không nhìn thấy)Tracking leak source
Forensic watermarkMỗi user nhận version video hơi khác nhauXác định chính xác ai leak

Forensic watermarking: Netflix dùng kỹ thuật này — mỗi subscriber nhận video với watermark khác nhau (invisible). Nếu video bị leak, phân tích watermark → biết chính xác account nào leak.


6. DevOps & Monitoring — Vận hành Video Platform

6.1 Transcoding Pipeline Monitoring

MetricMô tảAlert threshold
Queue depthSố job đang chờ trong transcoding queue> 10,000 jobs → scale up workers
Processing time p99Thời gian encode 1 video (p99)> 2h cho video 10 phút → investigate
Failure rate% job bị fail> 2% → alert, > 5% → page on-call
Worker utilizationCPU usage của transcoding workers< 30% → scale down, > 80% → scale up
Queue wait timeThời gian job chờ trong queue trước khi được pick upP0 > 1 phút → alert ngay

6.2 CDN Performance Monitoring

MetricMô tảTarget
Cache hit ratio% request được serve từ cache (không cần fetch origin)> 95% cho edge, > 85% cho regional
Origin offload% traffic KHÔNG phải đi về origin> 90%
Edge latency (TTFB)Time to First Byte từ CDN edge< 50ms
Cache fill rateTốc độ content được cache lần đầuMonitor để detect cache stampede
Bandwidth per PoPBandwidth tại mỗi CDN edgeDùng để capacity planning
Error rate per PoP% request lỗi tại mỗi edge> 0.1% → investigate edge health

6.3 Streaming Quality Monitoring

MetricMô tảTargetẢnh hưởng UX
Buffering ratio% thời gian user phải đợi buffer< 1%Cao nhất — user rời đi nếu buffer nhiều
Video Start Time (VST)Thời gian từ nhấn Play → frame đầu tiên< 2sUser mất kiên nhẫn sau 3s
Rebuffer frequencySố lần buffer/giờ xem< 0.5 lần/giờMỗi lần buffer = trải nghiệm xấu
Resolution distribution% user xem ở mỗi resolutionTrend trackingGiảm 1080p → mạng có vấn đề
Bitrate switchesSố lần player đổi resolution/phút< 2 lần/phútNhiều lần đổi = mạng không ổn định
Playback failure rate% video không play được< 0.1%User không xem được = worst case

6.4 Error Rate per Region

RegionMetric cần theo dõiHành động
VietnamBuffering ratio, CDN latencyNếu cao → thêm edge ở VN hoặc dùng ISP peering
SEACache hit ratioNếu thấp → tăng cache capacity ở Singapore
US/EUPlayback failure rateNếu cao → check CDN provider health
Emerging marketsResolution distributionNếu đa số 240p/360p → tối ưu cho low bandwidth

6.5 Cost Dashboard

DashboardMetricUpdate frequency
CDN Cost per ViewTổng CDN cost / tổng viewsHourly
CDN Cost per RegionCDN cost breakdown theo regionDaily
Transcoding Cost per VideoAvg cost để transcode 1 videoDaily
Storage Growth RateTB added/day, projected cost in 30 daysDaily
Cost per DAUTổng infra cost / DAUWeekly
CDN Provider ComparisonCost + performance của mỗi CDN providerWeekly

6.6 Alerting Tiers

TierSeverityResponse timeVí dụ
P0 — CriticalToàn bộ streaming down5 phútCDN origin unreachable, DB master down
P1 — Major1 region bị ảnh hưởng15 phútEdge HCM down, transcoding queue stuck
P2 — MinorPerformance degrade1 giờCache hit ratio < 90%, encode time tăng 2x
P3 — WarningAnomaly detectedNext business dayCost spike, unusual traffic pattern

7. Mermaid Diagrams — Tổng hợp

7.1 Upload Pipeline — End to End

graph TD
    A[Client] -->|1. Request pre-signed URL| B[API Server]
    B -->|2. Validate auth + quota| B
    B -->|3. Return pre-signed URL| A
    A -->|4. Upload chunks truc tiep| C[Blob Storage<br/>S3/GCS]
    C -->|5. All chunks received<br/>Trigger event| D[Message Queue<br/>Kafka]
    D -->|6. Dispatch| E{Priority Router}

    E -->|P0| F[Critical Queue]
    E -->|P1| G[High Queue]
    E -->|P2| H[Normal Queue]
    E -->|P3| I[Low Queue]

    F & G & H & I --> J[DAG Scheduler]

    J --> K[Video Splitting]
    K --> L[Parallel Encoding<br/>H.264 / VP9 / AV1<br/>Multiple resolutions]
    K --> M[Audio Extraction<br/>AAC / Opus]
    K --> N[Thumbnail Generation]
    K --> O[Watermark Overlay]

    L --> P[Segment Merging<br/>Per resolution/codec]
    P --> Q[Manifest Generation<br/>HLS .m3u8 / DASH .mpd]
    M --> Q
    Q --> R[Transcoded Storage<br/>S3/GCS]
    R --> S[CDN Origin Push]
    S --> T[CDN Edge Distribution]

    Q --> U[Metadata DB Update<br/>status = ready]
    U --> V[Notification Service<br/>Video san sang!]
    V --> A

7.2 Streaming Architecture — Full Flow

sequenceDiagram
    participant Client as Client (Player)
    participant DNS as DNS / GSLB
    participant Edge as CDN Edge
    participant Regional as CDN Regional
    participant Origin as CDN Origin
    participant Storage as Blob Storage
    participant Meta as Metadata Service
    participant Cache as Redis Cache

    Client->>Meta: GET /api/video/abc123 (video info)
    Meta->>Cache: Lookup video metadata
    Cache-->>Meta: Cache hit ✓
    Meta-->>Client: Video info + manifest URL

    Client->>DNS: Resolve CDN hostname
    DNS-->>Client: Nearest edge IP (GSLB)

    Client->>Edge: GET manifest.m3u8
    Edge-->>Client: Manifest (resolution list)

    loop Moi segment (2-10s video)
        Client->>Edge: GET /1080p/seg_N.ts
        alt Cache HIT
            Edge-->>Client: Segment (from cache)
        else Cache MISS
            Edge->>Regional: Fetch segment
            alt Regional cache HIT
                Regional-->>Edge: Segment
            else Regional cache MISS
                Regional->>Origin: Fetch segment
                Origin->>Storage: Read from blob
                Storage-->>Origin: Raw segment
                Origin-->>Regional: Segment (cached)
            end
            Regional-->>Edge: Segment (cached)
            Edge-->>Client: Segment (cached for next user)
        end
    end

    Note over Client: ABR: neu bandwidth giam<br/>→ chuyen sang resolution thap<br/>cho segment tiep theo

7.3 Adaptive Bitrate Decision Flow

graph TD
    A[Player bat dau] --> B[Request manifest file]
    B --> C[Nhan danh sach resolutions<br/>240p / 360p / 480p / 720p / 1080p / 4K]
    C --> D[Do bandwidth hien tai]
    D --> E{Bandwidth level?}

    E -->|"> 8 Mbps"| F[Chon 4K<br/>~15 Mbps bitrate]
    E -->|"5-8 Mbps"| G[Chon 1080p<br/>~5 Mbps bitrate]
    E -->|"2.5-5 Mbps"| H[Chon 720p<br/>~2.5 Mbps bitrate]
    E -->|"1-2.5 Mbps"| I[Chon 480p<br/>~1 Mbps bitrate]
    E -->|"0.5-1 Mbps"| J[Chon 360p<br/>~0.5 Mbps bitrate]
    E -->|"< 0.5 Mbps"| K[Chon 240p<br/>~0.25 Mbps bitrate]

    F & G & H & I & J & K --> L[Tai segment N voi resolution da chon]
    L --> M[Play segment N]
    M --> N{Tai segment N+1?}
    N --> O[Do lai bandwidth]
    O --> P{Bandwidth thay doi?}

    P -->|"Giam > 20%"| Q[Ha resolution<br/>cho segment N+1]
    P -->|"Tang > 30%"| R[Tang resolution<br/>cho segment N+1]
    P -->|"On dinh"| S[Giu nguyen resolution]

    Q & R & S --> T[Pre-fetch 2-3 segments tiep]
    T --> L

7.4 CDN Multi-tier Decision Flow

graph TD
    A[User request video segment] --> B[DNS/GSLB<br/>Route to nearest Edge]
    B --> C{Edge cache<br/>co segment?}

    C -->|HIT| D[Serve tu Edge<br/>Latency: 5-20ms]
    C -->|MISS| E{Regional cache<br/>co segment?}

    E -->|HIT| F[Serve tu Regional<br/>Cache len Edge<br/>Latency: 20-50ms]
    E -->|MISS| G{Origin cache<br/>co segment?}

    G -->|HIT| H[Serve tu Origin<br/>Cache len Regional + Edge<br/>Latency: 50-200ms]
    G -->|MISS| I[Fetch tu Blob Storage<br/>Cache len Origin + Regional + Edge<br/>Latency: 100-500ms]

    D --> J[User xem video]
    F --> J
    H --> J
    I --> J

    J --> K{Video popular?}
    K -->|"Top 1%"| L[Proactive push<br/>to all edges]
    K -->|"Top 10%"| M[Cache dai han<br/>o regional]
    K -->|"Bottom 90%"| N[Ngan cache TTL<br/>hoac khong cache]

8. Aha Moments & Pitfalls

8.1 Aha Moments — Những điều bất ngờ

#Aha MomentGiải thích
1CDN cost là #1 expenseKhông phải server, không phải storage — CDN bandwidth chiếm 50-70% tổng chi phí. Mọi quyết định thiết kế phải xoay quanh việc giảm CDN cost.
2Video không được “gửi” — nó được “cắt thành lát mỏng và đút”Streaming = gửi hàng ngàn segment nhỏ, mỗi segment 2-10 giây. Player quyết định resolution cho từng segment. Không phải download toàn bộ rồi play.
3Adaptive Bitrate là key của UXKhông có ABR, user phải tự chọn resolution. Chọn sai → buffer. ABR tự động điều chỉnh → video luôn chạy, chỉ đổi chất lượng. Đây là lý do YouTube hiếm khi buffer.
4Long-tail strategy quyết định lợi nhuận90% video chỉ có 5% view. Nếu cache tất cả trên CDN → phá sản. Bí quyết: chỉ cache 10% popular content, 90% còn lại serve từ origin (rẻ hơn 10x).
5Transcoding là CPU-heavy, phù hợp spot instancesTranscoding là batch job, có thể retry. Spot instances rẻ hơn 70-90% → tiết kiệm hàng triệu USD/năm. Chấp nhận được vì transcoding là async, không ảnh hưởng user trực tiếp.
6Encode 1 lần, serve triệu lầnChi phí encode VP9/AV1 gấp 10-50x H.264, nhưng tiết kiệm 20-30% bandwidth mỗi lần xem. Với video 10 triệu view → tiết kiệm khổng lồ.
7DAG architecture cho transcodingKhông phải “1 job = 1 video.” 1 video = nhiều task độc lập (split, encode, merge, thumbnail). DAG cho phép parallel, retry từng task, và priority scheduling.
8Pre-signed URL là must-haveUpload: tránh API server làm bottleneck. Playback: kiểm soát ai được xem, bao lâu, chống share link trái phép.

8.2 Pitfalls — Những lỗi thường gặp trong interview

#PitfallGiải thíchCách tránh
1Không tách Upload và StreamingHai luồng này có yêu cầu hoàn toàn khác nhau. Thiết kế chung → không tối ưu được.Luôn vẽ 2 pipeline riêng biệt
2Quên CDN costNói “dùng CDN” mà không bàn về cost optimization → interviewer nghĩ bạn không hiểu scale thực tếLuôn đề cập long-tail strategy, multi-CDN, codec optimization
3Chỉ nói “transcode video”Không giải thích DAG, parallel processing, priority queue → interviewer nghĩ bạn chỉ biết surface levelMô tả DAG: split → encode từng segment → merge. Nói về priority và spot instances
4Quên Adaptive BitrateNói “stream video cho user” mà không nói về ABR → interviewer sẽ hỏi “nếu mạng chậm thì sao?”Luôn nói về HLS/DASH, ABR, segment-based streaming
5Không nói về resumable uploadVới file 2-50GB, upload thường bị gián đoạn. Không có resumable = UX tệNói về chunked upload, checksum, retry
6Thiết kế monolithicGộp tất cả vào 1 service → không scale được từng phầnUpload service, transcoding service, streaming (CDN), metadata service — tách riêng
7Quên error handling”Video upload xong, transcode xong, xem được” — quá lý tưởng. Thực tế: network fail, disk full, codec errorNói về retry, exponential backoff, dead letter queue, alerting

8.3 Interview Tips — Chiến lược trình bày

BướcThời gianNói gì
1. Clarify3-5 phútHỏi: upload + streaming? Scale? Resolution? Paid vs free?
2. High-level5-7 phútVẽ 2 pipeline: Upload (pre-signed URL → storage → transcode → CDN) + Streaming (CDN → ABR)
3. Deep dive15-20 phútChọn 2-3 topic để deep dive: transcoding DAG, CDN multi-tier, ABR. Không cố làm tất cả
4. Cost & Scale5 phútBack-of-envelope cho storage + bandwidth. Nhấn mạnh CDN cost là #1
5. Wrap up3 phútNói về DRM, error handling, monitoring. Gợi ý extensions: live streaming, recommendation

Pro tip: Khi interviewer hỏi “Design YouTube,” họ không mong đợi bạn thiết kế tất cả. Họ muốn thấy bạn chọn đúng vấn đề để deep divegiải thích rõ ràng tại sao.


9. Wrap Up — Step 4: Extensions & Trade-offs

9.1 Possible Extensions (nếu có thời gian)

ExtensionMô tả ngắn
Live StreamingRTMP ingest → transcode real-time → HLS/DASH out. Khác VOD: latency quan trọng, không có pre-transcode
Recommendation EngineCollaborative filtering + content-based. Input: watch history, like, search. Output: suggested videos
Comment SystemThreaded comments, real-time update, spam detection. Sharding by video_id
Analytics DashboardCreator analytics: views, watch time, demographics. Dùng data warehouse (BigQuery)
Multi-languageAuto-generated captions (Speech-to-Text), translation, subtitle management
MonetizationAd insertion (pre-roll, mid-roll), subscription tiers, super chat
Offline ViewingDownload video cho xem offline. DRM vẫn phải hoạt động offline (license pre-fetched)

9.2 Trade-offs Summary

Quyết địnhOption AOption BYouTube chọn
Transcoding timingEager (encode tất cả resolution ngay)Lazy (encode khi có request)Eager cho popular codecs, Lazy cho rare resolutions
CDN strategyPush (đẩy lên CDN trước)Pull (CDN fetch khi cần)Push cho popular, Pull cho long-tail
Storage1 regionMulti-regionMulti-region với cross-region replication
Codec priorityChỉ H.264 (nhanh, compatible)Multi-codec (H.264 + VP9 + AV1)Multi-codec — tiết kiệm bandwidth cho popular content
UploadQua API serverPre-signed URL trực tiếp lên storagePre-signed URL — giảm tải API server
Metadata consistencyStrong consistencyEventual consistencyStrong cho video status, Eventual cho view count
Queue architecture1 queue chungMulti-queue với priorityMulti-queue — P0/P1/P2/P3 riêng biệt
TopicLinkLiên quan
CDN và DNSTuan-03-Networking-DNS-CDNCDN multi-tier, DNS-based routing, GSLB
Cache StrategyTuan-06-Cache-StrategyCDN cache policy, Redis metadata cache, cache invalidation
Message QueueTuan-08-Message-QueueTranscoding queue, priority queue, event-driven architecture
Database ShardingTuan-07-Database-Sharding-ReplicationMetadata DB sharding by video_id, replication cho read
Rate LimiterTuan-09-Rate-LimiterUpload rate limiting, API protection
MonitoringTuan-13-Monitoring-ObservabilityStreaming quality metrics, alerting tiers
SecurityTuan-15-Data-Security-EncryptionDRM, encryption, pre-signed URL
Back-of-envelopeTuan-02-Back-of-the-envelopeCapacity estimation methodology

“YouTube không phải là 1 hệ thống — nó là hàng chục hệ thống làm việc cùng nhau. Upload pipeline, transcoding DAG, CDN network, metadata service, recommendation engine… Mỗi phần có thể là 1 bài system design riêng. Bí quyết trong interview là biết focus vào đúng phần quan trọng nhất: CDN cost optimization và adaptive bitrate streaming.”