Skip to content

Thực hành: Thiết kế News Feed System

🎯 Mục tiêu

🎯 Sau bài thực hành này, bạn sẽ:

  • So sánh fan-out on write vs fan-out on read
  • Thiết kế feed ranking và giải quyết celebrity problem
  • Xây dựng real-time feed update mechanism

Yêu cầu hệ thống

Functional: Tạo post, feed sorted by relevance, real-time update, infinite scroll, engagement. Non-functional: Feed dưới 500ms (p99), 500M users, 100M DAU, 99.99% uptime.

Ước lượng

MetricGiá trị
Posts/day50M
Feed reads/day1B
Fanout writes/day10B (50M x 200 followers)
Feed cache/user~5KB (200 post IDs)

Kiến trúc

Thiết kế chi tiết

Fan-out on Write

Post → query followers → push post ID vào Redis sorted set (top 200).

Fan-out on Read

User mở feed → query followed users → merge + rank → top N.

Ranking & Celebrity

Score: Recency + Affinity + Engagement + Content type. Celebrity 10M followers → write = 10M writes → Hybrid: pull on-the-fly, merge với cached feed.

🎯 Scenario Choice

Fan-out Strategy

Pure Write: Read nhanh nhưng celebrity → 10M writes, quá tải. Pure Read: Write rẻ nhưng read latency cao, không đạt 500ms. Hybrid (Production): Regular (<10K followers) → write. Celebrity (>10K) → read.

💡 Twitter dùng hybrid. Facebook dùng write + heavy caching. Instagram chuyển sang hybrid khi scale lên.

Trắc nghiệm

🧠 Quiz

Câu 1: Fan-out on write lưu post ID thay vì content vì?

  • [ ] A) Redis không lưu dữ liệu lớn
  • [x] B) Tiết kiệm memory, edit/delete chỉ update Post DB thay vì 10M entries
  • [ ] C) ID sort nhanh hơn
  • [ ] D) Content gây lỗi cache

💡 Lưu content: 1 edit → update 10M entries. Lưu ID: edit Post DB, hydration lấy mới nhất.

🧠 Quiz

Câu 2: Hybrid xử lý celebrity post khi đọc feed?

  • [ ] A) Fan-out on write 10M followers
  • [ ] B) Chỉ hiển thị trên profile
  • [x] C) Merge cached regular feed với pull real-time celebrity posts, rồi rank
  • [ ] D) Broadcast qua CDN

💡 Regular feed pre-computed (fast). Celebrity pull on-the-fly (~50ms). Merge + rank = complete feed.

🧠 Quiz

Câu 3: Nếu CHỈ rank chronological, vấn đề gì xảy ra?

  • [ ] A) Feed chính xác hơn
  • [ ] B) Không có vấn đề
  • [x] C) User bị ngập low-quality content, bỏ lỡ posts từ close friends
  • [ ] D) Server load tăng

💡 Follow 500 accounts → scroll qua spam để thấy post bạn thân. Ranking ưu tiên relevant content tăng satisfaction.