Basics
Start with the product and the ideas it depends on. If these are clear, the design that follows will feel obvious rather than memorised.
1.1Product in plain words
Who uses it, what a normal day looks like, and why it is harder than it seems.
The home screen of a social shopping app: an endless scroll of posts from brands and people you follow plus recommendations, with photos and short videos. It is the first thing users see and the place they spend most time.
Who uses it
- Shoppers: open the app many times a day for a few minutes, mostly on mid-range Android phones.
- Brands: post several times a day to millions of followers.
- The ranking team: tunes what appears, using every impression and tap.
A day in the life
- She opens the app on the metro; yesterday’s feed appears instantly from the phone.
- A second later fresh posts load in above, without moving what she is looking at.
- She scrolls; the next page is already there before she reaches the end.
- A video starts only when it is fully on screen and is muted by default.
- Everything she sees and taps is reported in small batches to improve the ranking.
Why it is hard
Users judge the app in the first second, before any network call returns.
Each frame has 16 milliseconds; images and video fight for memory.
A brand with five million followers makes naive timeline building explode.
New content must arrive without yanking the scroll position.
Like a newspaper vendor who keeps yesterday’s paper on the counter so you can start reading immediately, while today’s edition is being fetched from the van.
1.2Key concepts
The building blocks this design uses. Each one appears again in the answer.
Either build each user's timeline when a post is created (fast reads, costly for very popular accounts) or assemble it when the user opens the app (cheap writes, slower reads). Most feeds mix both.
The server returns a page plus an opaque cursor for the next one. Unlike page numbers, cursors do not skip or repeat posts when new ones arrive at the top.
Serve each image at the size it is displayed, in a modern format, from a CDN close to the user. Oversized images being decoded cause most feed jank.
Only the rows on screen exist as views, and they are recycled as you scroll. RecyclerView, LazyColumn, UICollectionView and FlashList all work this way.
At 60 fps each frame has about 16 ms. Decoding, layout and data work must stay off the main thread to fit inside it.
Show the last saved feed instantly from disk, then fetch new items and merge them without moving what the user is looking at.
Learn them properly in the deep dives:
Question
Now read the question closely. Agree on what you are building, ask what is unclear, and work out the numbers before you draw anything.
2.1Brief and scope
The question exactly as the interviewer asks it, and what they want to learn from your answer.
Design the home feed for a social shopping app: an endless scroll of posts with photos and short videos. It must open instantly, scroll at 60 fps on mid-range Android phones, and feel fresh. 20 million daily users.
What it tests: Client performance, caching layers, pagination, media delivery and feed generation trade-offs.
The answer in one sentence. Cached first page, cursor-paged fresh content, sized images from a CDN, one active video, and hybrid fan-out on the backend.
How to spend the 45 minutes
- Clarify~5 minAsk questions, agree on scope and write down assumptions.
- Estimate~5 minRough numbers for users, data and traffic, and what they imply.
- High-level design~11 minComponents, data flow and the key API on the board.
- Deep dive~16 minThe two or three hardest parts, with real mechanisms.
- Trade-offs and wrap-up~9 minDecisions, failure modes, and what you would do next.
2.2Clarify the problem
The first five minutes. Each answer removes a guess from your design.
| You ask | Interviewer answers |
|---|---|
| Ranked or chronological? | Ranked, from people and brands the user follows plus recommendations. |
| What share of posts are video? | About 30%, mostly under 30 seconds. |
| Minimum device? | Android with 3 GB RAM, iPhone 11 and newer. |
| Do accounts with millions of followers exist? | Yes, a few thousand brands. |
2.3Estimate the scale
Say the arithmetic out loud. What matters is the order of magnitude and what it forces you to do.
| Metric | Estimate | How |
|---|---|---|
| Feed opens per day | ≈ 100M | 20M users × 5 sessions |
| Feed page requests | ≈ 3,500/s avg | 100M × 3 pages ÷ 86,400 |
| Image egress | ≈ 2 PB/month | mostly CDN cache hits |
| Cold start budget | < 1.5 s to first post | cached page shown first |
Detailed answer
The design itself, from the big picture down to the code: components first, then one request end to end, then the parts interviewers push hardest on.
3.1Architecture
The app renders a cached page instantly, then refreshes from a feed service that merges precomputed timelines with recommendations. Media comes from a CDN in sizes chosen for the device.
- Local cache
- The app stores the last few pages of posts, so it opens on yesterday’s feed in under a second while the fresh page loads.
- Image loader
- Requests the exact width the screen needs from the CDN, decodes off the main thread, and keeps memory and disk caches with size limits.
- Video
- Only the visible video plays. The next one or two preload their first segment so they start instantly, and nothing autoplays on metered networks unless the user allows it.
- Feed API
- Returns pages by opaque cursor. It merges a precomputed timeline for normal accounts with on-demand posts from huge accounts, then ranks.
- Event batcher
- The app buffers impressions and dwell times and sends them in batches, feeding ranking without costing battery.
3.2Key flow, step by step
Opening the app and scrolling.
- Show cached content first and swap in fresh content above the fold without jumping the scroll position.
- Prefetch the next page when the user is about three-quarters through the current one.
- Only one video decodes at a time; others show a poster frame.
3.3Front end
For a feed, front-end engineering is the product. The client owns perceived speed, scroll smoothness, media memory and data use, and it produces the event stream that ranking depends on.
Screen map
- Home feed
- A paged list backed by the local database: Paging 3 with a RemoteMediator on Android, a cursor-paged store on iOS, FlashList in React Native.
- Media
- Images come from the CDN at one of four width buckets. Video uses one shared player instance attached to the most visible item.
- New posts pill
- Fresh items that arrive during reading go above the fold only when the user taps the pill.
Client layers
| Layer | Technology | Responsibility |
|---|---|---|
| UI | Compose LazyColumn / SwiftUI List or UICollectionView / FlashList | Render items with stable keys and content types |
| Paging | Paging 3 RemoteMediator / custom cursor pager | Load from DB, fetch next page, write to DB |
| Images | Coil / Nuke or Kingfisher / expo-image | Sized requests, memory + disk cache, downsampling |
| Video | Media3 ExoPlayer / AVPlayer | One active player, preload first segment of the next |
| Events | Batched logger | Impressions, dwell, taps; flushed every 30 s or on background |
Every state the user can see
| State | What the user sees | How it works |
|---|---|---|
| First launch | Skeleton cards with shimmer | No cache yet |
| Cached | Yesterday’s posts, subtle ‘Updating’ | Rendered from DB while fetching |
| Fresh content | ‘New posts’ pill | Head page changed while user is scrolled |
| Loading more | Footer spinner | Next page request in flight |
| Offline | Banner; cached posts still scroll | Network unavailable |
| End | ‘You’re all caught up’ with suggestions | Cursor returned no more items |
Code
Paging from the database with a RemoteMediator (Android)
1@OptIn(ExperimentalPagingApi::class)2class FeedMediator(private val api: FeedApi, private val db: AppDb) : RemoteMediator<Int, PostEntity>() {3 override suspend fun load(type: LoadType, state: PagingState<Int, PostEntity>): MediatorResult {4 val cursor = when (type) {5 LoadType.REFRESH -> null6 LoadType.PREPEND -> return MediatorResult.Success(endOfPaginationReached = true)7 LoadType.APPEND -> db.feedMeta().nextCursor() ?: return MediatorResult.Success(true)8 }9 return try {10 val page = api.feed(cursor, limit = 20)11 db.withTransaction {12 if (type == LoadType.REFRESH) db.posts().clearFeed()13 db.posts().insertAll(page.items.map { it.toEntity() })14 db.feedMeta().setNextCursor(page.nextCursor)15 }16 MediatorResult.Success(endOfPaginationReached = page.nextCursor == null)17 } catch (e: IOException) { MediatorResult.Error(e) }18 }19}One player for the whole feed (React Native, FlashList)
1export function Feed({ posts }: { posts: Post[] }) {2 const [activeId, setActiveId] = useState<string | null>(null);3 const onViewable = useRef(({ viewableItems }: any) => {4 const v = viewableItems.find((i: any) => i.item.kind === 'video' && i.isViewable);5 setActiveId(v ? v.item.id : null); // only the fully visible video plays6 }).current;7 8 return (9 <FlashList10 data={posts}11 keyExtractor={p => p.id}12 getItemType={p => p.kind} // separate recycling pools13 estimatedItemSize={420}14 onViewableItemsChanged={onViewable}15 viewabilityConfig={{ itemVisiblePercentThreshold: 80 }}16 renderItem={({ item }) => <PostCard post={item} playing={item.id === activeId} />}17 />18 );19}3.4Data model and APIs
The tables and contracts that make the design concrete.
Feed page contract
1GET /v1/feed?cursor=eyJ0IjoxNzMwNjUw…&limit=202{ "items": [3 { "id": "p-91", "kind": "video", "author": {...},4 "media": { "poster": "https://cdn…/p-91.jpg?w={w}",5 "hls": "https://cdn…/p-91/master.m3u8", "aspect": 0.5625 },6 "rank_reason": "followed" } ],7 "next_cursor": "eyJ0IjoxNzMwNjQ…", "ttl_s": 300 }Image request sizing (Kotlin)
1val px = (view.width * resources.displayMetrics.density).roundToInt()2val bucket = listOf(360, 540, 720, 1080).first { it >= px } // few sizes = high CDN hit rate3imageLoader.enqueue(ImageRequest.Builder(ctx)4 .data(post.media.poster.replace("{w}", bucket.toString()))5 .memoryCacheKey("p-" + post.id + "-" + bucket)6 .target(view).build())3.5Tested code, explained
The core of this design as working code, with what each part does and why.
Merging pages without jumps
New posts shift the feed while someone scrolls, so the same post can land on two pages.
1data class Post(val id: String, val createdAtMs: Long)2data class Feed(val posts: List<Post> = emptyList(), val cursor: String? = null)3 4/** A post can slide onto two pages as new ones arrive, so duplicates are normal. Drop them by ID. */5fun Feed.append(page: List<Post>, next: String?): Feed {6 val seen = posts.mapTo(HashSet()) { it.id }7 return Feed(posts + page.filter { seen.add(it.id) }, next)8}9 10/** Fresh posts wait behind a pill unless the reader is at the top, so the list never jumps. */11fun Feed.onFresh(fresh: List<Post>, atTop: Boolean): Pair<Feed, Int> {12 val seen = posts.mapTo(HashSet()) { it.id }13 val new = fresh.filter { it.id !in seen }14 return if (atTop) copy(posts = new + posts) to 0 else this to new.size15}page.filter { seen.add(it.id) }- add returns false for a repeat, so duplicates simply drop out.
fun Feed.onFresh- Fresh posts wait behind a pill while reading, so the list never moves under the reader's thumb.
Compiled and tested by npm run test:mobile.
Decoding images at the right size
Memory is the first thing a feed runs out of. Decoding at screen size is the biggest single saving.
1/** Decode a 4000 px photo for a 400 px row at 1/8 size: 64 times less memory, same look. */2fun inSampleSize(width: Int, height: Int, targetW: Int, targetH: Int): Int {3 var sample = 14 while (width / (sample * 2) >= targetW && height / (sample * 2) >= targetH) sample *= 25 return sample6}7 8fun bitmapBytes(width: Int, height: Int, sample: Int): Long =9 (width / sample).toLong() * (height / sample) * 4 // 4 bytes per pixelsample *= 2- Android's decoder works in powers of two.
bitmapBytes- Width times height times 4 bytes. A 12-megapixel photo costs 48 MB decoded, whatever its file size.
Compiled and tested by npm run test:mobile.
Redrawing only what changed
140 pulled changes may touch three rows on screen. Compose and RecyclerView do this for you, and this is the idea underneath.
1/** Which rows must redraw. 140 pulled changes may touch only a few rows on screen. */2fun changedRows(old: List<JobRow>, new: List<JobRow>): Set<String> {3 val before = old.associateBy { it.id }4 return new.filter { before[it.id] != it }.map { it.id }.toSet()5}old.associateBy { it.id }- Looks up each row's previous state in constant time.
before[it.id] != it- Data classes compare by value, so an unchanged row doesn't redraw.
Compiled and tested by npm run test:mobile.
3.6Hard parts, in depth
Where interviewers spend the second half of the round.
Fan-out on write, read, or both
Writing each new post into every follower’s timeline makes reads cheap, but a brand with five million followers would trigger five million writes per post. Reading every followed account at request time is cheap to write but slow to read.
The hybrid used by large networks: fan out on write for normal accounts, and merge posts from a small set of huge accounts at read time. The cutoff is a follower-count threshold you tune with data.
Scrolling at 60 fps
Each frame has 16 ms. Keep item layouts flat, give every item a stable key and fixed aspect ratio so nothing reflows when images arrive, and decode images to the displayed size on a background thread.
Measure with frame metrics in production, not just on a flagship phone, and treat dropped frames on a 3 GB device as a release blocker.
Freshness without jank
When new posts arrive while the user is reading, show a ‘new posts’ pill instead of inserting above them. The cursor contract lets you prepend a page without breaking the next-page cursor.
Q&A
The questions that come after the design, with model answers. Answer each one out loud before opening it.
4.1Follow-up questions
What the interviewer asks once the main design is on the board.
How do you measure ‘opens instantly’?
How would you personalise for a new user?
How do you stop ads or posts the user hid from coming back?
4.2Front-end follow-ups
Questions aimed at the client: rendering, state and devices.
How do you insert fresh posts without moving the user?
How do you limit data use?
4.3Incidents, probes and traps
Realistic production incidents and pointed probes, grouped by topic.
The product 1
ProbeIsn’t showing yesterday’s feed first a bad experience?
Requirements 1
TrapWhich clarifying answer most changes the backend design?
Scale 1
ProbeHow did you get 3,500 page requests per second, and what is the peak?
Architecture 2
IncidentA celebrity brand posts and timeline-write lag jumps to 40 minutes.
ProbeHow do you avoid repeating a post the user saw on the previous page?
The key flow 1
IncidentAfter pull-to-refresh the feed shows duplicates and skips posts.
Front end 2
IncidentAndroid ANRs spike after enabling autoplay video.
ProbeHow do you measure and reduce time to first post?
Data and APIs 1
TrapWhy does the image URL contain a width placeholder instead of fixed sizes?
The hard parts 2
IncidentThe CDN bill doubles after a redesign.
ProbeThe ranking service has an 800 ms p99. What do you do?
Trade-offs 1
ProbeWhy HLS instead of plain MP4 for short videos?
Failures 2
IncidentOn launch day, impression events overwhelm the pipeline and users complain about battery.
IncidentA violating post kept appearing for hours after it was removed.
Extra depth
What turns a good answer into a strong one: the decisions you rejected, how the system fails, and the signals of seniority.
5.1Trade-offs and decisions
Every choice has a cost. Naming it is what interviewers listen for.
Show detailsHide details
| Decision | Chosen | Rejected | Why |
|---|---|---|---|
| Timeline build | Hybrid fan-out | Pure push or pure pull | Balances cheap reads with bounded write amplification from huge accounts. |
| Image sizing | Fixed width buckets | Exact pixel sizes | A handful of sizes keeps CDN hit rates high. |
| Video format | HLS with short segments | Progressive MP4 | Fast start, adaptive bitrate on weak networks. |
| Pagination | Opaque cursor | Offset | Offsets shift as new posts arrive and cause duplicates. |
5.2Failure modes
What breaks in production, and how the design keeps working when it does.
Show detailsHide details
| What breaks | How the design copes |
|---|---|
| Ranker slow or down | Serve the precomputed timeline in recency order; feeds degrade, never fail. |
| CDN region outage | Multi-CDN with DNS failover for media hosts. |
| Memory pressure on low-end phones | Lower cache sizes by device class, trim on onTrimMemory. |
| Duplicate posts across pages | Cursor encodes position in a snapshot of the ranked list, not an offset. |
5.3Performance and accessibility
The client-side details that separate a demo from a product.
Performance
- Baseline Profiles on Android and pre-warming on iOS cut cold start; measure time to first post per device class.
- Stable keys, content types and immutable models keep recomposition and recycling cheap.
- Decode images to displayed size; cap memory caches by device RAM.
- Track dropped frames in production (JankStats, MetricKit) and fail releases that regress them.
Accessibility and localisation
- Every image has alt text from the post or generated captions.
- Autoplay respects the system’s reduce-motion setting.
- Video captions on by default when the device is muted.
5.4Senior versus principal
The same design, answered at two levels. Use the rubric to score yourself.
A senior answer paginates, caches images and lazy-loads.
A principal answer sets performance budgets, explains hybrid fan-out with numbers, designs media for the device and network, and keeps the feed working when ranking fails.
Score yourself
5.5Whiteboard
Draw the design here, in this order. It stays in this browser.
- App with local cache in front of the feed API
- Image loader asking the CDN for sized images
- Feed API merging timeline store and ranker
- Fan-out workers writing timelines, with the huge-account exception
- Event batcher feeding training data