/Interview
Interview room · Mobile system design · 45 minutes

Infinite feed with images and video

PracticeSystem designTier 3 · Edge casesCreate45 minMobile systems

You will be able to: design infinite feed with images and video in 45 minutes, and defend each trade-off.

Mobile engineeringAll mobile pages

Here reads dominate. Local truth now serves speed instead of signal, and the cursor from the sync run pages through the feed. Start from the basics in Day 12 →

Study with AI

Ready45:00
ClarifyEstimateHigh-level designDeep diveTrade-offs and wrap-up
Part 1 of 5

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

  1. She opens the app on the metro; yesterday’s feed appears instantly from the phone.
  2. A second later fresh posts load in above, without moving what she is looking at.
  3. She scrolls; the next page is already there before she reaches the end.
  4. A video starts only when it is fully on screen and is muted by default.
  5. Everything she sees and taps is reported in small batches to improve the ranking.

Why it is hard

Instant open

Users judge the app in the first second, before any network call returns.

Smooth scrolling on cheap phones

Each frame has 16 milliseconds; images and video fight for memory.

Huge accounts

A brand with five million followers makes naive timeline building explode.

Freshness without jumpiness

New content must arrive without yanking the scroll position.

Think of it like this

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.

01Fan-out on write vs read

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.

02Cursor pagination

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.

03Right-sized images on a CDN

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.

04List virtualisation

Only the rows on screen exist as views, and they are recycled as you scroll. RecyclerView, LazyColumn, UICollectionView and FlashList all work this way.

05Frame budget

At 60 fps each frame has about 16 ms. Decoding, layout and data work must stay off the main thread to fit inside it.

06Cache, then refresh

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:

Part 2 of 5

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.

Interviewer

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

  1. Clarify~5 minAsk questions, agree on scope and write down assumptions.
  2. Estimate~5 minRough numbers for users, data and traffic, and what they imply.
  3. High-level design~11 minComponents, data flow and the key API on the board.
  4. Deep dive~16 minThe two or three hardest parts, with real mechanisms.
  5. 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 askInterviewer 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.

MetricEstimateHow
Feed opens per day≈ 100M20M users × 5 sessions
Feed page requests≈ 3,500/s avg100M × 3 pages ÷ 86,400
Image egress≈ 2 PB/monthmostly CDN cache hits
Cold start budget< 1.5 s to first postcached page shown first
Part 3 of 5

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.

APPBACKENDFeed screenrecycled listLocal cachelast 3 pagesImage loadermemory + disk cacheVideo playerprefetch first 2 sEvent batcherimpressionsFeed APIcursor pagesRankermodel scoringCDNsized images · HLSTimeline storeprecomputed idsEvent pipelineKafka → lakeFan-out workerspush to timelinesfirstrefreshGET ?w=720HLSrankwrite idsbatchtraining
ClientServiceData storeQueue / streamAI component
Reference design. Boxes show components; arrows show who calls whom.
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.

UserAppLocal cacheFeed APICDNopen appread cached pageposts (yesterday)render < 1 sGET /feed?cursor=headfresh page + next cursorreplace cacheimages at 720 pxUser scrolls to item 15 of 20GET /feed?cursor=c2 (prefetch)preload next video segment
Solid arrows are requests; dashed arrows are responses.
  1. Show cached content first and swap in fresh content above the fold without jumping the scroll position.
  2. Prefetch the next page when the user is about three-quarters through the current one.
  3. 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 feedranked · cachedPost detailcomments · productsProduct pageprice · add to cartBrand profileposts gridFull-screen videoswipe nextNew posts pilltap to jump upShare sheetsystem shareSaved postsoffline listshoptap video
Client
Screens and how users move between them.
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

LayerTechnologyResponsibility
UICompose LazyColumn / SwiftUI List or UICollectionView / FlashListRender items with stable keys and content types
PagingPaging 3 RemoteMediator / custom cursor pagerLoad from DB, fetch next page, write to DB
ImagesCoil / Nuke or Kingfisher / expo-imageSized requests, memory + disk cache, downsampling
VideoMedia3 ExoPlayer / AVPlayerOne active player, preload first segment of the next
EventsBatched loggerImpressions, dwell, taps; flushed every 30 s or on background

Every state the user can see

StateWhat the user seesHow it works
First launchSkeleton cards with shimmerNo cache yet
CachedYesterday’s posts, subtle ‘Updating’Rendered from DB while fetching
Fresh content‘New posts’ pillHead page changed while user is scrolled
Loading moreFooter spinnerNext page request in flight
OfflineBanner; cached posts still scrollNetwork unavailable
End‘You’re all caught up’ with suggestionsCursor returned no more items

Code

Paging from the database with a RemoteMediator (Android)

paging-from-database.ktKotlin
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}
19 linesUTF-8Kotlin

One player for the whole feed (React Native, FlashList)

one-player-whole.tsxTypeScript JSX
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}
19 linesUTF-8TypeScript JSX

3.4Data model and APIs

The tables and contracts that make the design concrete.

Feed page contract

feed-page-contract.jsonJSON
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 }
7 linesUTF-8JSON

Image request sizing (Kotlin)

image-request-sizing.ktKotlin
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())
6 linesUTF-8Kotlin

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.

FeedCache.ktKotlin
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}
15 linesUTF-8Kotlin
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.

FeedCache.ktKotlin
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 pixel
9 linesUTF-8Kotlin
sample *= 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.

RowUi.ktKotlin
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}
5 linesUTF-8Kotlin
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.

Part 4 of 5

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’?
Time to first post rendered, from process start, as p50 and p90 by device class, in production telemetry.
How would you personalise for a new user?
Cold-start with popular and category-based items, then switch weighting as impressions accumulate.
How do you stop ads or posts the user hid from coming back?
A per-user exclusion set checked in the feed API before ranking, cached in Redis.

4.2Front-end follow-ups

Questions aimed at the client: rendering, state and devices.

How do you insert fresh posts without moving the user?
Hold them in a pending list and show a pill. On tap, scroll to top and prepend; otherwise insert only when the user is already at the top.
How do you limit data use?
Width-bucketed images, HLS with adaptive bitrate, no video preloading on metered networks unless the user opts in.

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?
It is stale-while-revalidate: users see content in under a second while fresh posts load, and fresh content arrives without moving what they are reading. An empty spinner is worse for engagement than slightly old posts.

Requirements 1

TrapWhich clarifying answer most changes the backend design?
Whether accounts with millions of followers exist. If they do, pure fan-out on write breaks, and you need the hybrid model that merges big accounts at read time.

Scale 1

ProbeHow did you get 3,500 page requests per second, and what is the peak?
100 million opens a day times 3 pages, divided by 86,400 seconds. Evening peaks run 3 to 5 times higher, so plan for 10,000 to 15,000 per second, much of it absorbed by cached head pages.

Architecture 2

IncidentA celebrity brand posts and timeline-write lag jumps to 40 minutes.
The brand went through fan-out on write, creating millions of writes. Lower the follower threshold for read-time merging, give normal accounts their own queue, and alert on fan-out lag.
ProbeHow do you avoid repeating a post the user saw on the previous page?
Rank once per session into a snapshot and encode position in that snapshot in the cursor, rather than re-ranking per page. The client also dedupes by post ID.

The key flow 1

IncidentAfter pull-to-refresh the feed shows duplicates and skips posts.
Offset pagination shifted as new posts arrived, or the client appended a refreshed first page to old pages. Use opaque cursors, clear and replace on refresh in one transaction, and dedupe by ID.

Front end 2

IncidentAndroid ANRs spike after enabling autoplay video.
The main thread created and released several player instances during scrolling. Use one shared player attached to the most visible item, prepare off the main thread, and release resources when items leave the screen.
ProbeHow do you measure and reduce time to first post?
Measure from process start to first post rendered, per device class, in production. Ship Baseline Profiles, defer SDK initialisation, render the cached page before any network call, and keep dependency injection graphs light at start-up.

Data and APIs 1

TrapWhy does the image URL contain a width placeholder instead of fixed sizes?
The client picks one of a few width buckets for its layout and density. A small set of sizes keeps CDN hit rates high while never downloading more pixels than the screen shows.

The hard parts 2

IncidentThe CDN bill doubles after a redesign.
The new layout requested exact pixel widths, fragmenting the cache, and images grew. Return to width buckets, serve WebP or AVIF, and watch cache hit ratio and bytes per session as release metrics.
ProbeThe ranking service has an 800 ms p99. What do you do?
Give ranking a strict budget, for example 150 ms, and fall back to the precomputed timeline in recency order when it is exceeded. Cache candidates, precompute features, and serve the first page from a lighter model.

Trade-offs 1

ProbeWhy HLS instead of plain MP4 for short videos?
HLS starts fast with small segments and adapts bitrate to weak networks. For clips of a few seconds, progressive MP4 can be simpler; choose by length and network mix.

Failures 2

IncidentOn launch day, impression events overwhelm the pipeline and users complain about battery.
Events were sent too often. Batch by count and time, compress, sample low-value events, flush through WorkManager when backgrounded, and apply server backpressure.
IncidentA violating post kept appearing for hours after it was removed.
Clients and CDNs cached it. Send removals as tombstones in the feed, check a removed-flag on render, purge CDN paths, and track takedown time as an SLA.
Part 5 of 5

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
DecisionChosenRejectedWhy
Timeline buildHybrid fan-outPure push or pure pullBalances cheap reads with bounded write amplification from huge accounts.
Image sizingFixed width bucketsExact pixel sizesA handful of sizes keeps CDN hit rates high.
Video formatHLS with short segmentsProgressive MP4Fast start, adaptive bitrate on weak networks.
PaginationOpaque cursorOffsetOffsets 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 breaksHow the design copes
Ranker slow or downServe the precomputed timeline in recency order; feeds degrade, never fail.
CDN region outageMulti-CDN with DNS failover for media hosts.
Memory pressure on low-end phonesLower cache sizes by device class, trim on onTrimMemory.
Duplicate posts across pagesCursor 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.

Senior answer

A senior answer paginates, caches images and lazy-loads.

Principal answer

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.

  1. App with local cache in front of the feed API
  2. Image loader asking the CDN for sized images
  3. Feed API merging timeline store and ranker
  4. Fan-out workers writing timelines, with the huge-account exception
  5. Event batcher feeding training data
Tip: draw boxes first, then arrows, then label them with Text.
AI Engineer · interview room