บทที่ 11 · News Feed System

ออกแบบ News Feed System

News Feed System แสดงรายการ Posts ที่อัปเดตอย่างต่อเนื่องจากการเชื่อมต่อของผู้ใช้ ตัวอย่างรวมถึง Facebook News Feed, Instagram Feed และ Twitter Timeline

บทนำ

News Feed System แสดงรายการ Posts ที่อัปเดตอย่างต่อเนื่อง (Status Updates, Photos, Videos และ Links) จากการเชื่อมต่อของผู้ใช้

ข้อกำหนด

Overview

การออกแบบประกอบด้วยสอง Flows หลัก:

1. Feed Publishing

ผู้ใช้ Publish Post ซึ่งถูกเขียนไปยัง Database และ Propagate ไปยัง Feeds ของเพื่อน

2. News Feed Building

News Feed Building

ภาพที่ 1: News Feed Building Process

ผู้ใช้ดึง News Feed โดย Aggregate Posts จากเพื่อนใน Reverse Chronological Order

Feed Publishing Flow

Feed Publishing

ภาพที่ 2: Feed Publishing Flow

ขั้นตอน

  1. User Interaction: ผู้ใช้ Publish Post ผ่าน Feed Publishing API
  2. Load Balancer: กระจาย Traffic ไปยัง Web Servers
  3. Web Servers: ยืนยัน Requests และ Redirect ไปยัง Services
  4. Post Service: เก็บ Post ใน Database และ Cache
  5. Fanout Service: Propagate Post ไปยัง News Feeds ของเพื่อนใน Cache
  6. Notification Service: ส่งการแจ้งเตือนไปยังเพื่อน

Fanout Service Deep Dive

Fanout on Write (Push)

ข้อดี: อัปเดตแบบ Real-time, ดึง Feed เร็ว

ข้อเสีย: ใช้ทรัพยากรมากสำหรับผู้ใช้ที่มีเพื่อนมาก

Fanout on Read (Pull)

ข้อดี: มีประสิทธิภาพสำหรับผู้ใช้ที่ไม่ active

ข้อเสีย: ดึง Feed ช้าลง

Hybrid Approach

ใช้ Push Model สำหรับผู้ใช้ส่วนใหญ่และ Pull Model สำหรับผู้ใช้ที่มีการเชื่อมต่อสูง (เช่น Celebrities)

Cache Architecture

Cache แบ่งเป็น 5 Layers:

  1. News Feed Cache: เก็บ Post IDs สำหรับการดึงที่รวดเร็ว
  2. Content Cache: เก็บรายละเอียด Posts (Content ยอดนิยมใน Hot Cache)
  3. Social Graph Cache: เก็บข้อมูลความสัมพันธ์ของผู้ใช้
  4. Action Cache: ติดตาม User Actions (Likes, Replies, Shares)
  5. Counter Cache: เก็บ Counts สำหรับ Likes, Replies, Followers

เนื้อหานี้อ้างอิงจาก ByteByteGo - System Design Interview - An Insider's Guide