SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
  • Design a Chat App
  • Design a News Feed
  • Design a Notification System
  • Design a Web Crawler
  • Design Search Autocomplete
  • Design File Storage (Dropbox)
  • Design Video Streaming (YouTube/Netflix)
  • Design a Distributed Cache
  • Design a Leaderboard
  • Design a Job Scheduler
  • Design a Social Media Platform (Facebook)
System Design/Case Studies/Medium
Interview case study

Design a Social Media Platform (Facebook)

Profiles, friends, posts, likes, comments and privacy for billions of people, stitched into one platform.

⏱ 36 min readMedium case studyIntermediate26 cross-questionsHas visualizer
Prompt60-sec answer45-min plan1 Clarify2 Estimate3 API + Data4 Design5 Deep dives6 Scale7 Wrap upCross-questionsVariationsScoringMistakesCheat-sheet

StartThe prompt and what is really being tested

The interviewer says

“Design a social media platform like Facebook.”

It is short on purpose. Your first job is to make it specific.

What they checkWhy it matters
Scoping an umbrella prompt“A social network” is ten systems. A strong candidate picks three or four flows, says what is left out, and points to the pieces that are separate designs (feed, chat, notifications, video, search).
Modelling the social graphFriends are the data everything else hangs on. The interviewer wants to see sharding by user, two-sided writes for a friendship, and a plan for accounts with millions of followers.
Hot counters and idempotent actionsA like is tiny, but a viral post gets 100,000 a second on one row. You must make likes exact in one place and approximate in another.
Privacy as a correctness problemWho can see what is not a feature, it is an invariant. The check has to survive caches, fan-out, unfriending and blocking, and you must say where it runs.
Prioritising and phasingWhat would you build first, what is hardest, and where does it fall over at 10 times the load? Interviewers use these to separate people who can lead a design from people who can fill a diagram.

TL;DRThe whole design in 60 seconds

We build the platform core: profiles, a friend graph, posts with photos, likes and comments, and privacy enforced on every read. The feed, messaging, notifications, video and search are separate designs: the feed is covered in “Design a News Feed”, messaging in “Design a Chat App”.

  • Scale: 500M daily users, 500M posts a day (about 5,800 a second), 10 billion likes a day (about 116,000 a second, 350,000 at peak) and about 1.2 million post reads a second.
  • Graph: 1 billion users with about 300 friends is 300 billion rows, about 4.8 TB. Shard by user ID, so one user's friend list lives in one place. Accepting a friendship writes both sides through an outbox, and is idempotent.
  • Posts and photos: post metadata in a sharded store (cached by ID), photos uploaded straight to object storage with a pre-signed URL, processed into sizes, and served from a CDN.
  • Likes: an exact record of (post, user) with a unique key, so a like happens once. The count is a separate sharded counter, added up on read and cached for a second or two, so a viral post is not one hot row.
  • Privacy: check on every read, against the current friend list, blocks and audience lists. Cache the content, never the decision. Default deny.
  • Phasing: MVP is profiles, friends, posts and likes on one sharded database. Add the media pipeline, sharded counters, a permission service and multi-region as load grows.
💡How to use this page
Read the 60-second answer first. Then work through steps 1 to 7 in order, and try each step yourself before reading the model answer. Finish with the cross-questions: say your answer out loud, then open the model one.

PlanA 45-minute plan

4
3
4
7
17
7
3
Minutes per step (total 45). A guide, not a rule: move time to the part the interviewer cares about.
StepMinutesWhat to get done
1. Clarify4Scope hard: pick 3 to 4 flows, name what is out, then scale and privacy rules.
2. Estimate3Posts, likes and post reads per second, graph size, photo storage and egress.
3. API and data4Post, like, comment, friend request, privacy. Users, graph, posts, likes, comments.
4. High-level design7Gateway, user, graph, post, media, interaction and counter services, plus a shared permission check.
5. Deep dives17Graph at scale, likes and comments, privacy on every read, media pipeline, running it at scale.
6. Scale and failures7Hot posts, lost caches, cross-shard friend writes, regions, abuse.
7. Wrap up3Recap, trade-offs, the build order, and what comes next.

Step 1Clarify requirementsabout 4 min

🤔
Pause. Try it yourself first
You have 60 seconds. This prompt is huge on purpose. Write down which three or four flows you will design, and which you will refuse to design today.

Questions to ask, and why

AskWhy you ask itTypical answerHow it changes the design
This is a big product. Which flows should I design in 45 minutes?An umbrella prompt tests whether you can scope. Saying it out loud is the answer.Profiles and friends, creating a post with photos, likes and comments, and privacy. Treat the feed, chat, notifications and video as separate systems.We design the platform core, and link the siblings instead of repeating them.
Is it a friend (two-sided) graph, a follow (one-sided) graph, or both?Friendship is two writes that must agree. Follow is one write but can have huge lists.Friends, with a follow model for public pages and creators.Symmetric edges written on two shards, and a separate follow list for large accounts.
How many users, posts, likes and comments a day?The ratios show where the load is: likes dominate writes.500M daily users, 500M posts, 10B likes and 1B comments a day.Likes are about 116,000 writes a second, so counters need special care.
What can a post contain?Media decides storage, egress and the upload pipeline.Text, links and photos. Video is a separate design.Photos go to object storage and a CDN. Metadata stays small.
Who can see a post: only public, or friends and custom lists too?Privacy models decide how hard the read path is.Public, friends, friends except some people, a custom list, and only me.A permission check on every read, with default deny.
If I unfriend or block someone, how fast must they lose access?This is a freshness requirement on privacy, and it rules out stale caches of decisions.Immediately, within a second.Never cache the decision. Cache the content, check on read.
Do likes and comments need to be exact, or approximate?Exact is cheap for one user, costly for one viral post.The user must never like twice. The displayed total can be a little stale.Exact record, approximate count.
Do I need to delete everything when an account is deleted?Deletion across caches, replicas and search is a design cost.Yes, within a stated period, including backups on their normal cycle.A deletion pipeline, not a single DELETE. See Data Privacy and GDPR Basics.
Is the product in one region or worldwide?Regions change where the graph and the permission data live.Worldwide, but start in one region and plan for more.Home region per user, and asynchronous replication later.
What availability and latency do we need?This sets the cache and fallback strategy.99.99% for reads, p99 under 200 ms for a post read, writes can take 500 ms.Cache aggressively, degrade counters and comments before posts.

Write the scope on the board

Functional (must do)
  • •Create a profile, send, accept and remove friend requests
  • •Create a post with text and photos, and set who can see it
  • •Like and unlike a post, and comment on it, with replies
  • •View a post, a profile and a friend list, with privacy applied
  • •Change privacy settings, block and unfriend
Non-functional (how well)
  • •Privacy: a post is never shown to someone who is not allowed to see it, even through a cache
  • •Latency: p99 under 200 ms to read a post, under 500 ms to write
  • •Availability: 99.99% for reads. Counts and comment loading may degrade first
  • •Scale: 500M daily users, about 5,800 posts and 116,000 likes a second
  • •Consistency: strong for friend changes and privacy, eventual for counts
Out of scope (say it)
  • •Feed ranking and fan-out (see “Design a News Feed”)
  • •Direct messages and groups chat (see “Design a Chat App”)
  • •Push, email and SMS notifications (see “Design a Notification System”)
  • •Video (see “Design Video Streaming (YouTube/Netflix)”) and search (see “Design a Search Engine”)
  • •Ads, marketplace, and content moderation tooling beyond a hook
🎤
Say it out loud
“This prompt is a whole company, so let me scope it. I will design the platform core: profiles and the friend graph, posts with photos, likes and comments, and privacy enforced on every read. I will leave the feed, messaging, notifications, video and search to their own designs, and say where they plug in. I will assume 500 million daily users, a few hundred friends each, and ten billion likes a day. Privacy changes such as blocking must take effect immediately, but counts may be a little stale. Does that scope work?”

Step 2Estimate the scaleabout 3 min

🤔
Pause. Try it yourself first
On paper: posts, likes and post reads per second. Then the size of the friend graph and the photos. Which number is the scary one: posts, likes, or post reads?

Assumptions (say them first)

AssumptionValue
Daily active users500 million, out of 1 billion accounts
Posts per day, average post record500 million, about 1 KB each
Likes per day, comments per day10 billion and 1 billion
Friends per user300 on average
Posts viewed per user per day (outside the feed work)200, mostly from the feed
Photo uploads per day, original size100 million, 2 MB
Original plus resized copies2.5 MB per photo
Peak compared to average3 times
Cache hit rate for posts, CDN hit rate for photos95% and 95%
One counter row can take5,000 writes a second (illustrative)

The arithmetic, line by line

WhatMathsResult
Posts per second (average, peak)500M ÷ 86,400 ≈ 5,800, × 3about 5,800 and 17,400 a second
Likes per second (average, peak)10B ÷ 86,400 ≈ 115,700, × 3about 116,000 and 350,000 a second
Comments per second (average, peak)1B ÷ 86,400 ≈ 11,600, × 3about 11,600 and 35,000 a second
Post reads per second (average, peak)500M × 200 = 100B; 100B ÷ 86,400about 1.16 million and 3.5 million a second
Post reads that reach the store1.16M × 5% (after a 95% cache hit)about 58,000 a second
Post metadata per year, 3 copies500M × 1 KB × 365 = 182 TB; × 3about 550 TB
Like records per year, 3 copies10B × 24 bytes × 365 = 88 TB; × 3about 263 TB
Friend graph1B users × 300 friends × 16 bytes300 billion rows, 4.8 TB, 14.4 TB with 3 copies
Graph per shard (64 shards)4.8 TB ÷ 64about 75 GB per shard, per copy
Photo storage per day and per year100M × 2.5 MB = 250 TB; × 365250 TB a day, about 91 PB a year
Photo upload bandwidth100M × 2 MB ÷ 86,400 = 2.3 GB/sabout 18.5 Gbps average, 55 Gbps at peak
Photo views and CDN egress100B views × 30% photos × 100 KB = 3 PB a dayabout 280 Gbps average, about 14 Gbps reaches the origin
One viral post: counter rows needed100,000 likes/s ÷ 5,000 per rowat least 20 rows, so use 32 (about 3,100 per row)
Friend sets cached for permission checks100M recently active × 300 × 8 bytesabout 240 GB
What the numbers tell us about the design
  • •Likes are the loudest write: about 116,000 a second, 350,000 at peak. They are small, but a viral post puts 100,000 of them on one row. Counters need their own design.
  • •Post reads are 200 times the post writes (1.16 million against 5,800 a second). So the post path is a cache problem, and every one of those reads also needs a privacy check, so the check must be a memory lookup.
  • •The friend graph is 4.8 TB. It does not fit on one machine, but it shards cleanly by user ID, about 75 GB per shard. The hard cases are the celebrities, not the size.
  • •Photos dominate bytes: 250 TB a day in, 280 Gbps out. They never touch the app servers. Upload goes straight to object storage, and views come from a CDN.
  • •Post metadata and likes are small enough (550 TB and 263 TB a year, with copies) for a sharded key-value or SQL setup, which keeps the design simple.
🎤
Say it out loud
“Let me size it. 500 million posts a day is about 5,800 a second. Ten billion likes is about 116,000 a second and 350,000 at peak, so likes are the loudest write. Post reads are about 1.2 million a second, 200 times the writes, so reads are a cache problem and each one needs a privacy check. The friend graph is 300 billion rows, 4.8 terabytes, so it shards by user ID into about 75 gigabytes per shard. Photos are 250 terabytes a day, so they bypass the app servers and go to object storage and a CDN. And one viral post needs at least 20 counter rows.”

Step 3Define the API and the data modelabout 4 min

🤔
Pause. Try it yourself first
Write the calls for a post, a like, a comment and a friend request. Which of them must be safe to retry? Then ask: where does each piece of data live, and what is the key?

Endpoints

MethodPathRequestResponseNotes
POST/v1/posts{ text, mediaIds[], audience }201 { postId }Idempotency key in a header. Photos are uploaded first by a pre-signed URL. audience is public, friends, a list ID, or only me.
GET/v1/posts/{postId}none200 { post, author, counts, viewerState } or 404Permission checked for the viewer on every call. A hidden post answers 404, not 403, so its existence does not leak.
PUT/v1/posts/{postId}/likenone204Idempotent: liking twice is the same as once. DELETE removes the like. Returns fast, counts update asynchronously.
POST/v1/posts/{postId}/comments{ text, parentId? }201 { commentId }Idempotency key. GET with ?cursor= pages comments. Replies are limited to one or two levels.
POST/v1/friends/requests/{userId}none202PUT /v1/friends/{userId} accepts. Accepting is idempotent and writes both sides. DELETE unfriends.
PATCH/v1/me/privacy{ defaultAudience, lists, blocks }200Takes effect at once. Bumps a privacy version so caches of lists are dropped.

Data model

StoreKey and valueNotes
Usersuser_id → { name, photo, default_audience, home_region }Sharded by user_id. Cached. Small.
Friendships(user_id, friend_id) → { since, status }Two rows per friendship, one on each user's shard. 300B rows, 4.8 TB.
Follows (large accounts)(account_id, follower_id) and (follower_id, account_id)Kept apart from friends. Read in pages. Never loaded whole.
Postspost_id → { author_id, text, media_ids, audience, created_at, status }Sharded by post_id (time-ordered ID). Plus an index of (author_id, created_at) for the profile page.
Likes(post_id, user_id) → created_atUnique key. The exact record. 24 bytes a row. Sharded by post_id.
Like counters(post_id, shard 0..N-1) → countSharded counters, added on read, cached for 1 to 2 seconds.
Comments(post_id, comment_id) → { author_id, text, parent_id, status }Sharded by post_id. Cursor paging by comment_id.
Audience listslist_id → membersCustom lists such as Close friends, owned by one user. Small.
Photosmedia_id → { object keys, sizes, owner, status }Bytes in object storage. Metadata in the store. Served by a CDN.
Accepting a friendship, in one local transaction plus an outbox (sketch)
-- on user A's shard (A accepts B's request)
BEGIN;
  UPDATE friendships SET status='friends' WHERE user_id=A AND friend_id=B;   -- idempotent
  INSERT INTO outbox(event, key) VALUES ('FriendAccepted', 'A:B');
COMMIT;
-- a relay publishes FriendAccepted; the worker on B's shard runs the same UPDATE for (B, A).
-- retry-safe: the UPDATE sets a state, it does not add to a counter.
📝Which store, and why
Posts, comments, users and the friend graph are small records looked up by key, so a sharded key-value, wide-column or sharded SQL store fits. A friendship is stored twice (once on each user's shard) so each user's friend list is one shard read. Likes are an exact unique record plus a separate sharded counter, because the record must be correct and the counter must be fast. Photos go to object storage and a CDN. Caches in front hold users, posts and friend sets. A graph database is not needed for the main paths, since we mostly ask for one user's friends or one post, not long traversals.
🎤
Say it out loud
“There are six calls: create a post, read a post, like, comment, friend request and accept, and change privacy. Likes, accepts and posts carry idempotency, so a retry changes nothing. A hidden post returns 404 so nothing leaks. Storage: users and the friend graph sharded by user ID, with each friendship written on both users' shards through an outbox. Posts, likes and comments sharded by post ID. Like counts in separate sharded counters. Photos in object storage with a CDN.”

Step 4Draw the high-level designabout 7 min

🤔
Pause. Try it yourself first
Draw a post read and a like. Where is the privacy check, and what does it need to know? Where do photos go, and what stays out of the app servers?
Social platform core: high-level design
📱Clientsapp, web
→↓HTTPS
🚪API gatewayauth, rate limit
→↓
Core services
👤User and profilecached, sharded
🕸️Graph servicefriends, blocks, lists
📝Post serviceposts, comments
👍Interaction servicelikes, counters
→↓can viewer see it?
🛡️Permission checklibrary, memory sets
Media
⬆️Pre-signed uploadclient to storage
🪣Object storageoriginals, sizes
🌍CDNsigned URLs for private
Data and caches
⚡Cachesusers, posts, friend sets
🗄️Sharded storesgraph, posts, likes
Events (async)
📨Event busoutbox, Kafka
📰Feed, search, notifyother designs
Every read goes through one shared permission check. Photos bypass the app servers. Likes write an exact record and a sharded counter. Events feed the feed, search and notifications.
ComponentWhat it does
API gatewayAuthenticates the caller, rate-limits by user and action, and routes. Friend requests and posts have tight limits to slow spam.
Graph serviceOwns friendships, follows, blocks and custom lists. Answers: are A and B friends, is B blocked, who is on this list, who are my mutual friends. Sharded by user ID.
Permission checkA small library every read path calls. Input: viewer, post audience, author. Output: allow or deny, default deny. Runs on in-memory friend sets, not a network call per post.
Post serviceCreates, reads, edits and deletes posts and comments. Stores the audience on the post and never decides visibility by itself.
Interaction serviceWrites likes (exact, unique) and bumps sharded counters. Reads give the cached sum.
Media serviceHands out pre-signed upload URLs, runs processing (resize, scan), and gives out signed CDN URLs for private photos.
Event busReceives events from an outbox (PostCreated, FriendAccepted, LikeAdded) for the feed, search, notifications and counters. All consumers are idempotent.
CachesUser and post caches, plus a friend-set cache for the permission check. Content is cached. Decisions are not.
Write path (follow one request)
  1. The client uploads each photo straight to object storage with a pre-signed URL, so the bytes never pass through the app servers. The media service starts resizing and scanning.
  2. The client calls POST /v1/posts with the media IDs, the audience and an idempotency key. The gateway authenticates and rate-limits.
  3. The post service validates that the author owns those photos and that the audience refers to a list the author owns.
  4. It saves the post and writes a PostCreated row to the outbox in the same local transaction, then returns 201.
  5. A relay publishes the event. The feed, the search indexer and the notification service consume it asynchronously, and they are separate designs.
  6. A like follows a similar path: one idempotent insert of (post, user), then a counter bump on a random shard, and an event for notifications.
Read path (follow one request)
  1. The client asks for a post. The gateway authenticates and passes the viewer ID.
  2. The post service reads the post from its cache, and from the store on a miss. Content is cached, so most reads never reach the database.
  3. It runs the permission check: the viewer, the author, and the post's audience, against the viewer's friend set, blocks and lists, all in memory.
  4. If the check says no, it answers 404, and the cached content is never returned. If it says yes it continues.
  5. It adds the author summary, the cached like and comment counts, and whether the viewer has liked it.
  6. Photos are returned as CDN URLs. Public photos have long-lived URLs. Private photos get short-lived signed URLs.
🎤
Say it out loud
“Here is the picture. Clients go through a gateway to a few services: user, graph, post and interaction. Every read path calls one shared permission check that runs on in-memory friend sets, so privacy is enforced on every read, and a denied post looks like a 404. Writes save to a sharded store with an outbox, and events go on a bus for the feed, search and notifications, which are separate designs. Photos go straight to object storage with a pre-signed URL and come back through a CDN, with signed URLs for private ones. Likes are an exact unique record plus a sharded counter.”

Step 5Deep dive into the hard partsabout 17 min

🧠The pattern for every deep dive
Problem → options → pick one → say why → say what it costs. Interviewers score the reasoning more than the choice.
5.1

The social graph at scale, and the celebrity case

The problem: 300 billion friendship rows must live on many machines, a friendship is one fact that must appear on two users' lists, and a few accounts have millions of followers. Mutual friends and friends-of-friends must stay cheap.

OptionHow it worksGoodBad
A graph databaseStore people as nodes and friendships as edges in a graph engine, and walk them with graph queries.Natural for traversals such as friends of friends. Short, readable queries.Hard to shard at this size. Most of our reads are one user's list, which does not need traversal. Another system to run.
Sharded rows, both sides on each user's shardRow (user, friend) on the user's shard. A friendship is two rows on two shards.One user's friend list is one shard read. Scales by adding shards. Simple and predictable.Writing two shards means a cross-shard step. Needs an outbox and idempotent workers.
One row per friendship on one shardStore each friendship once, keyed by the lower user ID.One write. Never half-written.Half of the lists need a second lookup. A user's list is scattered across shards.
Separate follow model for big accountsKeep friends (symmetric, capped at a few thousand) apart from follows (one-sided, unlimited), and read the follow lists only in pages.Friend lists stay small and bounded. The unbounded case is isolated and paged.Two models in the product and in the code.
Pick
Sharded adjacency rows, written on both users' shards through an outbox, with a separate paged follow model for large accounts

Invariant: if A is a friend of B then B is a friend of A, and no one ever sees a one-sided friendship for long. Two shards cannot commit together without a distributed transaction (see Saga Pattern and Outbox Pattern), so the accepting shard commits its row and an outbox event in one local transaction, and a worker writes the other row. Both writes set a state, they do not add to anything, so a retry is harmless. For the short window the other side lags, the permission check treats the friendship as present only if both rows say so, which fails safe.

Sharding by user ID makes the common questions cheap: list a user's friends, test whether two users are friends, load a user's blocks. Mutual friends is a set intersection of two lists of about 300 IDs, done in memory. Friends-of-friends is bounded: a depth limit of two, and a cap on how many second-level IDs are read. Public pages and creators use the follow model, whose lists are never loaded whole.

QuestionHow it is answeredCost
List my friendsOne shard read by user ID, pagedOne lookup, about 300 rows
Are A and B friends?One row lookup on A's shard (cached friend set)A memory lookup
Mutual friends of A and BRead both lists, intersect in memoryTwo lookups and about 600 IDs
Friends of friends (depth 2)Read my list, then sample or cap their listsUp to 300 lookups, so cap and cache it
A page with 5M followersPaged follow list, never loaded wholeA page of 1,000 per call
Remove a friendDelete row on both shards, drop the cached setTwo writes via outbox
⚠️Where this breaks
If the outbox relay is down, accepts apply on one side only, and users see friends who are not friends yet. Monitor the outbox lag, and have a reconciliation job that finds friendships present on only one shard and repairs them. Also, never allow a list of unlimited size: cap friends, and force big accounts onto the follow model.
🎤
Say it out loud
“I would shard the graph by user ID so one user's friend list is one shard read, and store each friendship on both users' shards. Accepting commits one side plus an outbox event in a local transaction, and a worker writes the other side, idempotently, so a retry is safe, and until both sides exist the permission check says no. Mutual friends is an in-memory intersection of two lists of about 300. Accounts with millions of followers use a separate follow model that is only read in pages. The cost is a cross-shard step per friendship, which I accept for predictable scaling.”
5.2

Likes and comments at scale

The problem: A user must never like a post twice, the total must be right enough, and one viral post receives 100,000 likes a second on a single key. Comments need ordering, replies and pagination, and deleted ones must disappear.

OptionHow it worksGoodBad
UPDATE posts SET likes = likes + 1A counter column on the post row, updated on every like.Simplest thing that works.A row lock on every like. A viral post serialises 100,000 writes a second on one row. Retries double-count.
Exact like table plus a sharded counterInsert (post, user) with a unique key, and only on success add one to one of N counter rows chosen at random. Read by summing N rows and cache the sum.Exact per user, spread per post. Retries are harmless. A like can be undone.A sum of N rows on every read, so cache it. The two writes can drift apart.
Buffer in memory and flushCount likes in an in-memory aggregator per post and flush the total to the store every second.One write a second per post, however popular.A crash loses up to a second of counts, unless the stream is replayable. Needs a log.
Approximate countsShow “1.2M”, derive counts from a stream, and rebuild exact totals in a batch job.Cheap, no hot rows, no one cares about the last digit.The number can differ between screens, and a user sees their own like missing for a moment unless handled.
Pick
An exact unique like record, a sharded counter fed through a log, an approximate display, and an optimistic client

Invariant: one user, one like per post, and a retry never counts twice. The unique key on (post, user) enforces it: the insert either succeeds once or fails as a duplicate, and only a successful insert bumps the counter. The displayed number is a different thing, and it may lag: read the N counter rows, sum them, and cache the sum for a second or two.

For a viral post, split the counter into 32 rows so each takes about 3,100 writes a second against a limit of about 5,000, and for the very hottest posts add a buffering aggregator in front. The client shows the user's own like at once (optimistic), and the “liked by you” flag comes from the exact table, not the counter. Counts that drift are repaired by a periodic recount from the like table.

A like, in order (sketch)
ok = INSERT INTO likes(post_id, user_id) VALUES (?, ?) ON CONFLICT DO NOTHING   -- exact, idempotent
if ok:
    shard = hash(user_id) % 32                                                    -- or random
    INCR counter(post_id, shard)                                                  -- hot row spread over 32 rows
    publish LikeAdded(post_id, user_id)                                           -- for notifications and ranking
total(post_id) = cache.get(post_id) ?? SUM(counter(post_id, 0..31))              -- cache 1 to 2 seconds
Comment featureDesign
Storage and orderSharded by post_id, ordered by a time-ordered comment_id
PagingCursor of comment_id, never an offset
Repliesparent_id, with one or two levels shown and the rest loaded on demand
Delete or hideMark status, filter on read, clean up later
Hot postCache the first page for a few seconds, and write comments asynchronously if needed
🎤
Say it out loud
“A like has two parts. The exact part is a row of post and user with a unique key, so a retry or a double tap cannot count twice. The count is a separate counter split into 32 rows, because 100,000 likes a second on one row is a hot key. I add to one of the rows only when the insert is new, sum the rows on read, and cache the sum for a second or two. The total is allowed to lag, and the client shows your own like at once. Comments are sharded by post, ordered by ID, paged by cursor, and deletes are filtered on read.”
5.3

Privacy enforced on every read

The problem: Each post has an audience (public, friends, friends except someone, a custom list, only me). Friends change, people are blocked, lists are edited, and posts sit in caches and other systems. A single leak is a serious failure, and one slow check on 1.2 million reads a second is another.

OptionHow it worksGoodBad
Work out the audience list when the post is writtenCompute who may see it at posting time and store that list or use it for fan-out.Reads are a simple membership test. Fast.Stale the moment a friendship, block or list changes. A blocked person keeps access. Huge lists for popular authors.
Check at read time against current dataOn every read evaluate: viewer, author, audience, against the viewer's current friend set, blocks and lists.Always right. Changes apply at once. The audience is stored as a small rule, not a huge list.A check on every read, so it must be a cheap in-memory lookup.
Cache the allow decision per postRemember “this post was allowed” and serve it to the next viewer.Fastest.Wrong by design. A decision made for one viewer is served to another. This is the classic leak.
Cache content, check every readCache the post content, keyed by post. Never cache the decision. Run the check on each request, with the friend sets themselves cached.Fast and correct. Content caches are shared by everyone who may see it.The friend-set cache must be invalidated quickly on a change.
Pick
Cache the content, never the decision, and check on every read against current data, with default deny

Invariant: a viewer sees a post only if the audience rule, evaluated against current relationships, says yes. Everything else is a hint. So the stored thing is a small rule (public, friends, friends except Dana, list 17, only me), not a list of people. The check runs on every read, as a library call that uses the viewer's cached friend set (about 300 IDs), block set and list memberships. That is a few memory lookups, so it fits inside the 200 ms budget.

Invalidation is the hard part. When someone is unfriended, blocked or removed from a list, the graph service bumps a version for that user and drops the cached sets, so the next read sees the change within a second. Blocks win over everything. Default deny: an unknown audience or a failed lookup hides the post. Private photos use short-lived signed URLs, so a link copied out of the page stops working. Counts, search results, notifications and tags are leak paths too, so each of them calls the same check.

AudienceRuleNeeds
PublicAnyone, except people the author blockedBlock set
FriendsViewer is in the author's friendsFriend set
Friends except DanaFriends, and not DanaFriend set and an exclusion
Custom listViewer is in list 17List membership
Only meViewer is the authorNothing else
⚠️Where this breaks
If the friend-set cache is not invalidated, a blocked person keeps seeing posts until it expires. Keep the cache time short, bump a version on every relationship change, and test the leak paths: after an unfriend, a block and a list edit, no cache, search result, notification or CDN link may still allow access.
🎤
Say it out loud
“I treat privacy as an invariant: a viewer sees a post only if the audience rule, checked against current relationships, says yes. I store the audience as a small rule, not a list of people, and run the check on every read from in-memory friend, block and list sets, so it costs a few lookups. I cache the content, never the decision, because a decision cached for one viewer leaks to the next. When someone is unfriended or blocked, a version bump drops the cached sets, so it takes effect within a second. Default deny, and a denied post looks like a 404.”
5.4

Photos: upload, processing and delivery

The problem: 100 million photos a day, 250 TB a day stored, 280 Gbps out. App servers must not carry bytes. Photos need several sizes, scanning, privacy, and cheap storage as they age.

OptionHow it worksGoodBad
Upload through the app serverThe client posts the file to the post service, which stores it.Simple.App servers carry 18 Gbps of upload and hold connections open. Retries re-upload everything.
Pre-signed direct uploadThe service issues a short-lived URL, the client uploads straight to object storage, then confirms.Bytes skip the app tier. Multipart and resumable. Scales with the store.A confirm step, and cleanup for uploads never attached to a post.
Resize on every requestKeep only the original and make each size when requested.No wasted storage on unused sizes.CPU on the read path, and slow first views.
Resize once after upload, serve by CDNAn async job makes the standard sizes, scans for malware and policy issues, then marks the photo ready.Fast reads, a CDN hit rate of 95%, and clean immutability.A short delay before the photo is ready, and storage for each size.
Pick
Pre-signed direct upload, asynchronous processing into fixed sizes, and CDN delivery with content-addressed URLs

The client uploads straight to object storage, so the app tier never carries photo bytes. A queue triggers processing: scan for malware and policy violations, strip location data from metadata (a privacy default), and make a few standard sizes. Names are content-addressed or versioned, so a URL never changes and can be cached for a long time. A photo is only attached to a post when it is marked ready, and orphans are deleted after a day.

Public photos get long-lived URLs. Private photos get signed URLs that expire in minutes, so a copied link stops working, and the permission check is what decides to issue one. Old, rarely viewed photos move to cheaper storage tiers. Moderation is automated screening plus human review, and its rules are product decisions that are out of scope here.

🎤
Say it out loud
“Photos never touch the app servers. The client gets a pre-signed URL and uploads straight to object storage. A queue then scans the file, strips location data, and makes a few fixed sizes, and only then is the photo marked ready and attached to the post. Names are content-addressed so the CDN can cache them for a long time. Public photos get long URLs, private ones get signed URLs that expire in minutes, issued only after the permission check. Old photos move to cheaper storage.”
5.5

Running it at scale: hot posts, regions and abuse

The problem: One viral post turns every layer into a hot key. Users are worldwide. Fake accounts and spam arrive from day one. The design must keep working as each of these grows.

OptionHow it worksGoodBad
Scale everything uniformlyAdd more of everything when load grows.Nothing to design.Does not fix hot keys. One row or one cache key cannot be spread by adding machines.
Target the hot spotsSharded counters, replicated hot cache keys, in-process caches and request coalescing for viral posts.Cheap and effective. Fixes the actual bottleneck.Needs detection of hot keys and extra code paths.
One global deploymentA single copy of the graph and posts, read from everywhere.Strongly consistent. Simple.Slow for distant users, and one region failing takes everyone down.
Home region per userEach user lives in a home region. Reads and writes are local, data is replicated to others asynchronously.Fast and resilient. Matches data-residency rules.Cross-region friendships and privacy changes need care. Replication lag is visible.
Pick
Fix hot spots directly, start in one region, then give each user a home region with asynchronous replication

Hot posts are the first problem: spread the counter, cache the post in each app server for a second or two, replicate the hot cache key, and let one request refill a missing key while others wait (see Cache Stampede and Hot Keys). Everything beyond that is added when a metric asks for it.

For regions, a user's home region owns their writes, so a friend change is local. A friendship across regions writes both homes through the same outbox. Privacy changes are sent first and with priority, because stale access is worse than a stale like count. Abuse is a first-class load: limit friend requests and posts per account, detect bursts of new accounts, and put new accounts on stricter limits.

🎤
Say it out loud
“I would not scale everything evenly, I would fix the hot spots: split the counter, keep a short in-process cache for viral posts, and let only one request refill a missing key. Regions come later: each user gets a home region, writes stay local, and data replicates asynchronously, with privacy changes sent first because stale access is worse than a stale like count. Abuse is part of the design from day one: limits on friend requests and posts, stricter limits for new accounts, and detection of bursts of fake accounts.”
VisualizerWho can see Ana's posts, and how a viral like counter breaksPick a viewer, turn on Ana's changes, and try the four ways of enforcing privacy: watch where the leak appears. Then raise the likes per second and split the counter into more rows.
Part 1: who can see Ana's posts?
Who is looking?

Gus: was a friend, Ana blocked him.

Since the posts were written, Ana…
How is privacy enforced?
P1Holiday photoaudience: PublicLEAK: should be hiddenwas on the list made at posting time
P2Dinner with the familyaudience: FriendsLEAK: should be hiddenwas on the list made at posting time
P3Complaint about Dana's cookingaudience: Friends except DanaLEAK: should be hiddenwas on the list made at posting time
P4Hiddenaudience: Close friends listhidden, correctwas not on the list made at posting time
P5Hiddenaudience: Only mehidden, correctwas not on the list made at posting time
Posts shown
3 of 5
Leaks
3
shown but should be hidden
Wrongly hidden
0
allowed but not shown
Gus can still see 3 post(s) he or she should not. The audience list was worked out at posting time, and Ana has since unfriended, blocked or edited her list. A list made at write time goes stale the moment a relationship changes. Use it only as a hint, never as the answer.
Part 2: a viral post and its like counter
Writes per counter row vs what one row can take (5k a second)100k of 5k (2000%)
Per row = 100k likes/s ÷ 1 rows = 100k/s
Rows needed at the limit = 100k ÷ 5k = 20
One read = add up 1 row (then cache the total for a second or two)
Writes per row
100k
per second
Rows needed
20
at 5k each
Rows per read
1
added up
100k likes a second on 1 row(s) is 100k writes per row against a limit of 5k. The row is a hot key: writes queue up, time out, and the count falls behind. You need at least 20 rows.

A teaching model with fixed people, fixed posts and no random numbers. In mode C and D, Ben opens every post first, so the cache holds what Ben was allowed to see. The audience lists in mode A are worked out when the post is written. The 5k writes a second per counter row is an illustrative assumption, not a measurement. The exact like record, one row per (post, user), is a separate table and is not the thing being spread here.

Step 6Scale, bottlenecks and failuresabout 7 min

🤔
Pause. Try it yourself first
Which one post, one user and one table will go wrong first at 10 times the load? What do you turn off first if the database is struggling?

What breaks first, and the fix

BottleneckFix
Likes on a viral post (100,000 a second on one key)Sharded counters (32 rows), an in-process aggregator for the hottest posts, and a cached sum. The exact like record stays one row per user.
Post reads (1.2M a second, 3.5M at peak)Cache posts by ID with a 95% hit rate, in-process cache for hot posts, and coalesce misses so one request refills the key.
The permission check on every readCache each viewer's friend, block and list sets in memory, keep the audience as a small rule, and bump a version on change.
Celebrity and page follower listsA separate follow model read in pages, never loaded whole, and cached top pages.
Photo bytes (250 TB a day in, 280 Gbps out)Pre-signed direct upload, CDN for delivery, cheaper storage tiers for old photos.
Cross-shard friend writesOutbox plus idempotent workers, a reconciliation job for one-sided rows, and alerts on outbox lag.
Comment threads under a popular postCache the first page for a few seconds, page by cursor, and limit reply depth.

What if a part fails?

FailureHow the design copes
The friend-set cache is cold or lostRebuild from the graph shard on demand with a per-user lock. Until it is ready, fail safe: show only public posts.
The outbox relay stopsWrites still commit locally. Friendships stay one-sided and are treated as not friends. Alert on lag, replay when the relay is back.
A counter shard or the counter store is downShow the last cached count or hide it. Likes still record in the exact table, and a recount repairs the total.
Object storage or the CDN has an outagePosts still load with text and a placeholder for photos. Retries with backoff. Uploads are resumable.
A database shard is slow or downReplicas serve reads. Writes to that shard fail fast with a clear error, and other shards are unaffected.
A region goes downUsers fail over to another region with data a few seconds behind. Privacy changes replicate first so no one regains access.
What to monitor
  • •Permission check latency, and the rate of denials by reason (a sudden drop in denials can mean a leak)
  • •Cache hit rate for posts, users and friend sets, and the version-invalidation lag
  • •Outbox and event-bus lag, and the count of one-sided friendships found by the reconciler
  • •Hot keys: top posts by write rate on counters and on cache keys
  • •Like and comment write latency, duplicate-like rejections, and counter drift from the recount
  • •Upload to ready time for photos, the scan failure rate, and CDN hit rate
Security and abuse
  • •Default deny on every read path: posts, comments, counts, search results, tags and notifications all call the same permission check.
  • •Rate-limit friend requests, posts, likes and comments per account, with stricter limits for new accounts (see Design a Rate Limiter).
  • •Signed, short-lived URLs for private photos, and strip location data from photos by default.
  • •Detect fake and bulk-created accounts, and scan uploads for malware and policy violations.
  • •Support deletion and export requests across stores, caches, search indexes and backups (see Data Privacy and GDPR Basics), and audit who accessed private data.

Step 7Wrap upabout 3 min

We built the platform core of a social network. The friend graph is sharded by user, with each friendship written on both users' shards through an outbox. Posts and comments are sharded by post. Likes are an exact unique record plus a sharded counter, so a viral post is not a hot row. Privacy is enforced on every read from in-memory sets, with content cached and decisions never cached, and a denied post looks like a 404. Photos go straight to object storage and come back through a CDN with signed URLs for private ones. The feed, messaging, notifications, video and search are separate designs that plug in through events.

Trade-offs you made

DecisionWhat we gainWhat it costs
Friendship written on both users' shardsA friend list is one shard read, and the graph scales by adding shards.A cross-shard step through an outbox, plus a reconciler for one-sided rows.
Privacy check on every read, content cachedChanges apply within a second and caches cannot leak.A few memory lookups per read and a friend-set cache that must be invalidated fast.
Exact like record plus sharded approximate counterNo double likes, and no hot row on viral posts.Counts lag by a second or two, and a periodic recount is needed.
Direct upload and CDN for photosApp servers never carry photo bytes.A confirm step, orphan cleanup, and a short wait before a photo is ready.
Separate follow model for big accountsFriend lists stay small, and the unbounded case is paged.Two models to build, explain and keep consistent.
One region first, home regions laterA simple start, and a path to local speed and data residency.A migration later, and cross-region friendships need care.
If we had more time, we would…
  • •Hook up the feed, notifications and search to the event bus, as separate services (see the sibling case studies).
  • •Add a permission service for non-read paths such as tags, shares and mentions, and a leak-testing suite.
  • •Multi-region with home regions, and replication that sends privacy changes first.
  • •A moderation pipeline with automated screening, human review and an appeals path.
  • •A load test with a viral post, a lost friend-set cache and a stopped outbox relay.
🎤
Say it out loud
“To recap: the friend graph is sharded by user and each friendship is written on both shards through an outbox. Posts and comments are sharded by post. Likes are an exact unique record plus a sharded counter, so a viral post does not become one hot row. Privacy is checked on every read from in-memory sets, content is cached but decisions never are, and a hidden post looks like a 404. Photos go direct to object storage and come back through a CDN. The trade-offs are a cross-shard step per friendship, counts that lag by a second, and a friend-set cache that must invalidate fast. Next: events to the feed, search and notifications, and multiple regions.”

Q&ACross-questions (26)

💡How to practise
Cover the answer. Say yours out loud in 30 to 60 seconds. Then open the model answer, the follow-up, and the weak answer to see what to avoid. Use Open all at the top for a quick read.
Warm-upProbingCurveballWarm-up = basics. Probing = tests depth. Curveball = changes the problem.

Scoping and priorities

Umbrella prompts are scored on judgement first. Say what you would build, and what you would not.

The graph, likes and comments

Privacy, media and deletion

Where the leaks are. Interviewers want a single check, fast invalidation and a plan for deletion.

Failures, scale and curveballs

What ifIf the interviewer changes the problem

A change in requirements is a test of whether you understand why your design looks the way it does.

New requirementWhat changes in the design
Add a story that disappears after 24 hoursA short-lived post type with a TTL. Same permission check. Cleanup is by expiry, and views are counted with a small approximate counter.
Add groups and pages with their own privacyA new audience type: group members. The check reads group membership. Large groups behave like large follow lists, so they are paged.
Private accounts that approve followersA pending state on follow rows, and the audience of their posts is followers only. The approval write is idempotent and goes through the same outbox.
Edit posts and keep a historyVersioned post rows, with the latest pointer. Likes and comments stay attached to the post ID. Caches are invalidated on edit.
Tagging people in a photoA tag widens the audience to the tagged person unless they decline. The check gets one more rule, and tags need their own approval and removal path.
Legal hold or a takedown requestA status on the post that the check understands, which hides it without deleting it. Deletion pipelines skip held items. Audit every action.
Reactions beyond likes (love, laugh, etc.)The like key becomes (post, user) with a reaction type, so still one per user. Counters shard by type. The table grows only a little.
End-to-end encrypted private postsThe server cannot read content or evaluate the audience, so key management moves to clients, and search, moderation and recount features need rethinking.

ScoreHow answers are judged

AreaWeakGoodGreat
ScopingTries to design the whole company.Picks a few flows and states the rest are out.Names the siblings (feed, chat, notifications), links the boundaries by events, and says what to build first.
EstimationSkips numbers or counts only users.Posts, likes and reads per second, and storage.Finds that likes dominate writes, post reads are 200 times the writes, and sizes the graph per shard.
Graph designOne table and a join.Shards by user ID and stores both directions.Handles the two-shard write with an outbox, idempotent steps and a reconciler, and treats celebrities separately.
Counters and consistencylikes = likes + 1.Mentions sharded counters.Separates the exact like record from the approximate count, and shows the numbers for a viral post.
PrivacyA flag on the post, checked in one place.Checks on read.States the invariant, caches content but never decisions, handles invalidation, default deny, 404s and leak paths.
CommunicationSilent or jumps around.Follows the seven steps.Prioritises, names the costs of each choice, and says where it breaks at 10 times the load.

AvoidCommon mistakes on this question

MistakeDo this instead
Trying to design every feature of the productScope to three or four flows in the first minutes, and link the rest as separate systems.
Redesigning the feed and chat inside this answerSay they are separate designs, give the event they listen to, and move on.
Storing a friendship once and joining at read timeWrite it on both users' shards through an outbox, so a friend list is one shard read.
A single counter row for likesAn exact unique record plus a sharded counter, summed on read and cached briefly.
Caching an “allowed” decision per postCache content only, and run the permission check on every read.
Computing audience lists at write timeStore a small audience rule, and evaluate it against current relationships on read.
Sending photos through the app serversPre-signed direct upload, async processing, and a CDN with signed URLs for private photos.
Forgetting deletion and privacy changes in caches and searchA version bump on relationships, a deletion pipeline per system, and a shared check everywhere.

Revise60-second revision sheet

  • ✔Scope: profiles + friends, posts + photos, likes + comments, privacy. Feed, chat, notifications, video and search are separate designs.
  • ✔Numbers: 5,800 posts/s, 116,000 likes/s (350,000 peak), 1.2M post reads/s. Graph 300B rows, 4.8 TB, about 75 GB per shard.
  • ✔Graph: shard by user ID, store a friendship on both shards via an outbox, idempotent, reconciler for one-sided rows.
  • ✔Celebrities: a separate follow model, read in pages, never loaded whole.
  • ✔Likes: unique (post, user) row for exactness, a 32-row sharded counter for speed, cached sum, optimistic client.
  • ✔Privacy: audience is a small rule; check on every read from in-memory sets; cache content, never decisions; default deny; 404 for hidden.
  • ✔Changes: unfriend or block bumps a version and drops cached sets, so access ends within a second.
  • ✔Photos: pre-signed direct upload, async scan and resize, CDN, signed short-lived URLs for private.
  • ✔Consistency: strong for friends, blocks and privacy. Eventual for counts, feeds and search.
  • ✔Build first: users, friends, posts, likes on one sharded database with a cache. Harden privacy and counters next.

Read these topics next

Design a News Feed→

The ranked home timeline that consumes this platform's events.

Design a Chat App→

Messaging is a separate system with its own delivery design.

Design a Notification System→

Turns likes, comments and friend requests into pushes and emails.

Graph Databases→

When multi-hop queries on the live path justify a graph engine.

Sharding→

The graph, posts and likes are all sharded, each by its own key.

Hot Keys→

A viral post is a hot key in the counter, the cache and the post row.

Outbox Pattern→

How a friendship reaches both shards, and events reach the bus.

Data Privacy and GDPR Basics→

Deletion and export across stores, caches and backups.

← Previous
Design a Job Scheduler
Next →
Design Ride Sharing (Uber/Lyft)