Facebook Friends (Karat)
Problem Statement
You're building a Facebook-like social media platform. Each post should display the number of friends the author has at the moment when the post is being viewed. The friend count must reflect the most up-to-date state of a user's friendships.
Your database has the following schema:
USER
USER_RELATIONSHIP
A friendship is mutual, meaning if user A is a friend of B, user B is also a friend of A.
The system should scale to millions of users and friendships, and the friend count must load quickly (ideally <100ms), even on high-traffic pages with many posts.
Solution
🔹 Option 1: Real-time Count (Not Scalable)
You can count friends on-the-fly by querying:
1SELECT COUNT(*) FROM USER_RELATIONSHIP
2WHERE user_id = :author_id OR user2_id = :author_id;❌ Not scalable: This results in full table scans for popular users and becomes inefficient at scale.
✅ Option 2: Maintain a Precomputed friend_count Column (Scalable)
Add a friend_count column to the USER table or a separate USER_STATS table.
On Friendship Create/Delete:
You can do this via:
This ensures reads are instantaneous and writes are efficiently processed.
🔹 Option 3: Cache Layer for Popular Users
For frequently viewed users: