Facebook Friends (Karat)

Difficulty: EASYCategory: HLDFrequency: 1Asked On 2025-05-09

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

1.user_id (Primary Key)
2.name
3.created_date

USER_RELATIONSHIP

1.friendship_id (Primary Key)
2.user_id (Indexed)
3.user2_id (Indexed)
4.start_date

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:

•When a new friendship is created between A and B:
•Increment A's and B's friend_count by 1.
•When a friendship is deleted:
•Decrement both counts.

You can do this via:

•Transactional updates (in RDBMS like Postgres)
•Asynchronous processing using a message queue (for large scale)
•Friendship create event → queue → FriendshipService → update friend_count

This ensures reads are instantaneous and writes are efficiently processed.


🔹 Option 3: Cache Layer for Popular Users

For frequently viewed users:

•Cache friend_count in Redis or Memcached.
•Periodically invalidate or update the cache on friendship changes.


Comments