News Feed System แสดงรายการ Posts ที่อัปเดตอย่างต่อเนื่องจากการเชื่อมต่อของผู้ใช้ ตัวอย่างรวมถึง Facebook News Feed, Instagram Feed และ Twitter Timeline
บทนำ
News Feed System แสดงรายการ Posts ที่อัปเดตอย่างต่อเนื่อง (Status Updates, Photos, Videos และ Links) จากการเชื่อมต่อของผู้ใช้
ข้อกำหนด
- รองรับทั้ง Web และ Mobile Apps
- ผู้ใช้สามารถ Publish Posts ได้
- ผู้ใช้สามารถ ดู Posts จากเพื่อน ใน News Feed ของตน
- รองรับผู้ใช้ได้สูงสุด 5,000 เพื่อน
- 10 ล้าน DAU
Overview
การออกแบบประกอบด้วยสอง Flows หลัก:
1. Feed Publishing
ผู้ใช้ Publish Post ซึ่งถูกเขียนไปยัง Database และ Propagate ไปยัง Feeds ของเพื่อน
2. News Feed Building
ภาพที่ 1: News Feed Building Process
ผู้ใช้ดึง News Feed โดย Aggregate Posts จากเพื่อนใน Reverse Chronological Order
Feed Publishing Flow
ภาพที่ 2: Feed Publishing Flow
ขั้นตอน
- User Interaction: ผู้ใช้ Publish Post ผ่าน Feed Publishing API
- Load Balancer: กระจาย Traffic ไปยัง Web Servers
- Web Servers: ยืนยัน Requests และ Redirect ไปยัง Services
- Post Service: เก็บ Post ใน Database และ Cache
- Fanout Service: Propagate Post ไปยัง News Feeds ของเพื่อนใน Cache
- 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:
- News Feed Cache: เก็บ Post IDs สำหรับการดึงที่รวดเร็ว
- Content Cache: เก็บรายละเอียด Posts (Content ยอดนิยมใน Hot Cache)
- Social Graph Cache: เก็บข้อมูลความสัมพันธ์ของผู้ใช้
- Action Cache: ติดตาม User Actions (Likes, Replies, Shares)
- Counter Cache: เก็บ Counts สำหรับ Likes, Replies, Followers
เนื้อหานี้อ้างอิงจาก ByteByteGo - System Design Interview - An Insider's Guide