Design an infinite image feed
The question
Design an infinite image feed for an Android app. Users scroll down and new images load automatically. The app must work offline, survive process death, and scroll smoothly.
Clarify before you design:
- Is the feed a single flat list, or are there multiple tabs or categories the user switches between?
- Does the user interact with images (like, comment, save), or is it read-only scrolling?
- Does the server give image dimensions and a separate thumbnail URL, or only one full-size URL?
- Should the feed support pull-to-refresh, or only auto-load on scroll?
- Is there a login requirement, or is the feed public?
- How fresh must the feed be when the app opens: show the cache first, or always fetch?
- What is the acceptable latency for the first screen of images on a cold start?
Requirements
Functional
- Render a vertically scrolling list of images that loads the next page automatically when the user approaches the bottom.
- Persist fetched pages in Room so the feed is available offline and after process death.
- Support pull-to-refresh to fetch the newest items from the top of the feed.
- Show a placeholder while an image is loading, and an error state if the image fails to load.
- Restore the scroll position after the system kills and recreates the process.
- Expose a retry action when a network page load fails mid-scroll.
Non-functional
- Smooth scrolling: frames finish within the display's frame deadline (about 16 ms at 60 Hz). No heavy work on the main thread.
- Bounded memory: Coil's memory cache has a size limit, and Paging keeps loaded pages unless
maxSizeis set, so decide whether you need it. - Battery and data: avoid redundant network calls; serve cached rows from Room and images from Coil's disk cache.
- Poor connectivity: show cached data, show that it may be stale, and let the user retry.
- Images load over HTTPS. Cleartext traffic is blocked by default on Android 9 (API 28) and higher.
- No leaks: nothing holds the Activity or composables after the screen is gone.
Out of scope
- Server-side ranking, recommendation algorithms, or content moderation.
- User-generated content upload, image editing, or a photo gallery.
- Cross-device sync of saved or liked images.
High-level architecture
The client has three layers. The UI layer is a Compose screen with a LazyColumn that renders items from collectAsLazyPagingItems(). Each item loads its image with Coil's AsyncImage. The ViewModel exposes the feed as a Flow<PagingData<ImageEntity>> with cachedIn(viewModelScope), and a separate StateFlow<UiState> for things Paging does not cover, such as a "last updated" time or a stale banner. PagingData stays out of the UiState class. The data layer has a FeedRepository that builds the Pager from Room's generated PagingSource (from the ImageDao) and a RemoteMediator.
Room is the single source of truth. The UI only ever reads from Room. When the list reaches the end of the cached rows, Paging calls the RemoteMediator, which calls the Retrofit FeedApi with the stored cursor. On success it writes the items and the new cursor to Room in one transaction, Room invalidates its PagingSource, and the list updates from the database. On failure it returns MediatorResult.Error, and the error shows up in loadState while the cached items stay on screen.
Coil lives in the UI layer. Each AsyncImage gets the thumbnail URL and loads it at the size of its layout constraints. One ImageLoader is configured for the whole app and owns the memory and disk caches. Scroll position belongs to LazyListState, created with rememberLazyListState(), which saves its index and offset in saved instance state.
| Component | Responsibility |
|---|---|
| FeedScreen (Compose) | Collects LazyPagingItems, renders the LazyColumn with item keys, maps each item to AsyncImage, shows load states, and wraps the list in Material 3 PullToRefreshBox. |
| FeedViewModel | Exposes the repository's paging flow with cachedIn(viewModelScope) and a StateFlow<UiState> for non-paging state. |
| FeedRepository | Builds the Pager with PagingConfig, the RemoteMediator, and Room's PagingSource factory. Returns Flow<PagingData<ImageEntity>>. |
| FeedRemoteMediator | Implements initialize() and load(loadType, state). Calls FeedApi with the stored cursor, writes items and cursor to Room in a transaction, and returns MediatorResult.Success or MediatorResult.Error. |
| ImageDao and RemoteKeyDao (Room) | PagingSource query ordered by feed position, upsert and clear operations, and a small table holding the next cursor and last sync time. |
| FeedApi (Retrofit) | Suspend function fetchPage(cursor, limit). Returns FeedResponse with items and nextCursor. Retrofit suspend calls are main-safe. |
| Coil ImageLoader | Configured once through SingletonImageLoader.Factory on the Application. Owns the memory cache and the disk cache, and decodes off the main thread. |
| LazyListState | Holds the scroll index and offset. rememberLazyListState() saves them, so they come back after configuration changes and process death. |
Data model and API
@Entity(tableName = "images")
data class ImageEntity(
@PrimaryKey val id: String,
val url: String,
val thumbnailUrl: String,
val width: Int,
val height: Int,
val author: String,
val caption: String,
val createdAt: Long,
val feedOrder: Int // position in the feed, so Room returns rows in server order
)
@Entity(tableName = "feed_remote_key")
data class FeedRemoteKey(
@PrimaryKey val feedId: String = "home",
val nextCursor: String?,
val lastSyncedAt: Long
)
@Dao
interface ImageDao {
@Query("SELECT * FROM images ORDER BY feedOrder ASC")
fun pagingSource(): PagingSource<Int, ImageEntity>
@Upsert
suspend fun upsertAll(images: List<ImageEntity>)
@Query("DELETE FROM images")
suspend fun clearAll()
@Query("SELECT COALESCE(MAX(feedOrder), -1) FROM images")
suspend fun maxFeedOrder(): Int
}
@Dao
interface RemoteKeyDao {
@Query("SELECT * FROM feed_remote_key WHERE feedId = 'home'")
suspend fun get(): FeedRemoteKey?
@Upsert
suspend fun upsert(key: FeedRemoteKey)
}
data class ImageDto(
val id: String,
val url: String,
val thumbnailUrl: String,
val width: Int,
val height: Int,
val author: String,
val caption: String,
val createdAt: Long
)
data class FeedResponse(
val items: List<ImageDto>,
val nextCursor: String?
)
interface FeedApi {
@GET("feed")
suspend fun fetchPage(
@Query("cursor") cursor: String?,
@Query("limit") limit: Int
): FeedResponse
}The PagingSource return type needs the room-paging artifact. Room generates the source and runs its queries off the main thread.
Deep dives
Paging 3, RemoteMediator, and Room
The Pager gets Room's PagingSource as its factory and a RemoteMediator for the network. load(loadType, state) receives no key. It is called with LoadType.REFRESH (first load or user refresh), APPEND (reached the end of the cached rows) or PREPEND (reached the start). For a newest-first feed, newer items come from a refresh, so PREPEND returns endOfPaginationReached = true. The cursor lives in a Room table written in the same transaction as the items, so they can never disagree.
@OptIn(ExperimentalPagingApi::class)
class FeedRemoteMediator(
private val db: FeedDatabase,
private val api: FeedApi,
private val cacheTtlMillis: Long
) : RemoteMediator<Int, ImageEntity>() {
override suspend fun initialize(): InitializeAction {
val lastSync = db.remoteKeyDao().get()?.lastSyncedAt ?: 0L
return if (System.currentTimeMillis() - lastSync < cacheTtlMillis) {
InitializeAction.SKIP_INITIAL_REFRESH
} else {
InitializeAction.LAUNCH_INITIAL_REFRESH
}
}
override suspend fun load(
loadType: LoadType,
state: PagingState<Int, ImageEntity>
): MediatorResult {
val cursor = when (loadType) {
LoadType.REFRESH -> null
LoadType.PREPEND -> return MediatorResult.Success(endOfPaginationReached = true)
LoadType.APPEND -> db.remoteKeyDao().get()?.nextCursor
?: return MediatorResult.Success(endOfPaginationReached = true)
}
return try {
val page = api.fetchPage(cursor, state.config.pageSize)
db.withTransaction {
if (loadType == LoadType.REFRESH) db.imageDao().clearAll()
val start = db.imageDao().maxFeedOrder() + 1
db.imageDao().upsertAll(
page.items.mapIndexed { i, dto -> dto.toEntity(feedOrder = start + i) }
)
db.remoteKeyDao().upsert(
FeedRemoteKey(nextCursor = page.nextCursor, lastSyncedAt = System.currentTimeMillis())
)
}
MediatorResult.Success(endOfPaginationReached = page.nextCursor == null)
} catch (e: IOException) {
MediatorResult.Error(e)
} catch (e: HttpException) {
MediatorResult.Error(e)
}
}
}The repository builds Pager(config = PagingConfig(pageSize = 30), remoteMediator = mediator, pagingSourceFactory = { db.imageDao().pagingSource() }).flow (the page size is only an example), and the ViewModel applies cachedIn(viewModelScope). Only IOException and HttpException are caught, so CancellationException still propagates. prefetchDistance defaults to pageSize. It controls how close to the end of the loaded items the user gets before the next load starts.
In the UI, collectAsLazyPagingItems() turns the flow into LazyPagingItems. The list uses items(count = items.itemCount, key = items.itemKey { it.id }, contentType = items.itemContentType { "image" }). Stable keys keep item state and the scroll position with the right item when rows are inserted or removed. contentType matters once the list mixes kinds of rows (images, ads, a loading footer), because Compose only reuses compositions between items of the same type. loadState.append drives the footer: a spinner while loading, a retry button that calls items.retry() on error.
Coil image loading: cache, sizing, and placeholders
Each item calls Coil 3's AsyncImage (package coil3.compose, with the coil-network-okhttp artifact for HTTP). The model is the thumbnail URL, not the full-size URL. AsyncImage resolves the request size from its layout constraints, so give the item a bounded size. The simplest way is Modifier.fillMaxWidth().aspectRatio(image.width.toFloat() / image.height) from the server's dimensions. That also reserves the space before the image arrives, so items do not jump when images load. If a dimension is unbounded, Coil can end up decoding far more pixels than the screen shows.
placeholder and error take a Painter (for example a ColorPainter or painterResource(...)). A crossfade is optional; turn it on with crossfade(true) on the ImageRequest.Builder or the ImageLoader.Builder.
Coil keeps two caches. The memory cache holds decoded images, and its default size is a percentage of the app's available memory. The disk cache holds downloaded files in the app's cache directory, also with a bounded size. When the user scrolls back, an image comes from memory or disk without a network call. To tune them, implement SingletonImageLoader.Factory on your Application and return an ImageLoader.Builder(context) with memoryCache { MemoryCache.Builder().maxSizePercent(context, ...).build() } and diskCache { DiskCache.Builder().directory(...).maxSizePercent(...).build() }. Choose the values from measurements, not habit. Coil fetches and decodes on background dispatchers, so a correctly sized image does not block the main thread.
Process death and scroll position recovery
When the system kills the process in the background, everything in memory is gone. On return, a new Activity, ViewModel and Pager are created. Three things make the feed come back where the user left it:
- Scroll state.
rememberLazyListState()stores the first visible index and offset withrememberSaveable, which survives process death. You do not need to copy it intoSavedStateHandleby hand. Do not createLazyListStatein the ViewModel; it is UI state that belongs to the composition. - Data. Room still has the rows, so the new
PagingSourceloads them without the network. Room's generated source supports placeholders, so the item count is known once the first load finishes. - No surprise refresh. By default
initialize()returnsLAUNCH_INITIAL_REFRESH, so the mediator refreshes on start, clears the table and replaces the rows. The restored index then points at different items. ReturnSKIP_INITIAL_REFRESHwhile the cache is fresh enough, as in the code above.
One more trap: right after recreation, LazyPagingItems is empty until the first load arrives. If the LazyColumn is laid out with zero items, the restored position can be clamped to the top. Show a loading state until items.itemCount > 0 (or the refresh load state is no longer loading), then show the list. Test this path with adb shell am kill <package> while the app is in the background. Rotation does not test it, because the ViewModel survives a configuration change.
Baseline profiles and scroll jank
Image feed jank usually comes from work on the main thread during scroll: composing complex items, decoding oversized images, and running code that is still interpreted or JIT-compiled. A Baseline Profile lists classes and methods that ART compiles ahead of time. You generate it with the Baseline Profile Gradle plugin (androidx.baselineprofile) and a Macrobenchmark test that uses BaselineProfileRule.collect() to start the app and fling the feed. Google Play delivers the profile with the APK, so ART compiles that code at install time. For other installs, androidx.profileinstaller installs it on first run.
Beyond the profile: keep item composables simple, give images a bounded size, use stable keys, and keep reads of the scroll offset out of composition (use derivedStateOf or lambda modifiers). Measure with a Macrobenchmark FrameTimingMetric and Perfetto traces on a mid-range device, and look for long frames on the main thread.
Trade-offs
| Decision | Options | What to pick and why |
|---|---|---|
| Cursor-based vs offset-based pagination | Cursor (opaque token from the server), offset + limit | Cursor-based. It stays stable when new items are inserted at the top, so pages do not duplicate or skip items, and the server can seek on an indexed column. The cost is no random access to page N, which a feed does not need. |
| Room + RemoteMediator vs network-only PagingSource | Room as the source of truth, a PagingSource that calls the API directly | Room. It works offline, survives process death, and gives instant starts from the cache. A network-only source is simpler and fine for search results, but loses everything on process death and needs the network to show anything. |
| Coil vs Glide | Coil (Kotlin-first, coroutines, Compose AsyncImage), Glide (mature, View-first, has a Compose integration) | Coil for a Compose app built on coroutines. Glide is a solid choice too, especially in a codebase that already uses it with Views. The bigger wins come from sizing and caching, not from the library choice. |
| Prefetch distance | Default (pageSize), smaller, larger | Start with the default and adjust after watching real scrolling. Too small and the user reaches the footer spinner during a fast fling; too large and you fetch pages the user never sees, costing data and battery. |
| Refresh on start vs show cache first | LAUNCH_INITIAL_REFRESH, SKIP_INITIAL_REFRESH with a freshness check | Show the cache first and refresh only when it is older than a product-chosen limit. It gives instant starts and keeps scroll position after process death. Always refreshing is simpler but slower, and it replaces the rows the user was looking at. |
| Pull-to-refresh vs background refresh | User pull-to-refresh, periodic WorkManager sync, both | Pull-to-refresh plus a refresh when stale on open covers most feeds. A periodic WorkManager job keeps the cache warm for offline use, but it spends battery and data on content the user may never open, so only add it if offline freshness really matters. |
What breaks in production
- Users return to the app after a while in the background and the feed is back at the first item, showing different images.
- The
RemoteMediatorused the defaultinitialize(), so every cold start ranREFRESH, cleared the table and inserted a new first page. - The screen also laid out the
LazyColumnbefore the first page loaded, so the restored index was clamped to zero.
- Override
initialize()to returnSKIP_INITIAL_REFRESHwhile the cache is fresh, using a last-sync time stored in Room with the cursor. - Show a loading state until
LazyPagingItemshas items, then lay out the list, sorememberLazyListState()can restore its index. - When a refresh does happen, tell the user (for example a "New posts" chip) instead of silently replacing the rows under them.
- Add a manual or scripted test that backgrounds the app, runs
adb shell am kill, reopens it and checks the position.
- Users on mid-range devices saw stutter, blank image slots, and items jumping as images arrived.
- The feed loaded the full-size URL, and the item height was wrap-content, so Coil decoded much larger bitmaps than the screen showed. Memory and garbage collection pressure went up.
- Item heights changed when each image arrived, so the list kept re-measuring and the content shifted.
- Load the thumbnail URL and give each item a bounded size with
aspectRatiofrom the server's width and height, so Coil decodes at the displayed size and the layout does not shift. - Use
itemKey { it.id }and keep item composables simple. - Ship a Baseline Profile generated from a scroll journey.
- Measure with Macrobenchmark
FrameTimingMetricand Perfetto before and after, on a mid-range device.
Common mistakes in this round
- Using offset-based pagination (page number + limit). New items inserted at the top shift every offset, so the next page repeats or skips items. Large offsets also get slower on the server. Use cursor-based pagination with an opaque token.
- Omitting stable keys in the LazyColumn. Without keys, items are identified by position. After an insert or refresh, remembered item state stays with the position, and the scroll position cannot follow the item the user was looking at. Use
itemKey { it.id }withLazyPagingItems, anditemContentTypewhen the list mixes kinds of rows. - Loading full-size images in the feed. Decoding far more pixels than the screen shows wastes memory and CPU and causes GC pauses. Request a thumbnail and give
AsyncImagea bounded size. - Refreshing on every start. The default
initialize()runs aREFRESHthat clears the cached rows, which breaks instant offline starts and scroll restoration. Skip the initial refresh while the cache is fresh. - Treating Paging as automatically memory-bounded. Paging keeps loaded pages unless you set
PagingConfig.maxSize. Coil's caches have size limits by default; Paging's in-memory pages do not. - Building the Pager or skipping cachedIn in the wrong place. Creating the
Pagerin a composable, or exposing it withoutcachedIn(viewModelScope), reloads from scratch after rotation. Build it in the repository, cache it in the ViewModel, and collect it in the UI withcollectAsLazyPagingItems(). - Two sources of truth. Showing network results directly while also writing them to Room leads to duplicates and flicker. The UI reads only from Room; the mediator only writes to Room.
Follow-up questions
Answer out loud first. Then reveal the answer and compare it at each depth.
“How do new items at the top of the feed reach the user, and what about scrolling up?”
“What happens when the network is unavailable and the user scrolls past the last cached page?”
“How do you keep memory usage bounded when the user scrolls through thousands of images?”
“How would you test the feed end-to-end, including process death?”
Self-review checklist
- Paging 3
Pagerwith Room's generatedPagingSourceand aRemoteMediatorthat handlesREFRESH,APPENDandPREPENDwith a cursor stored in Room in the same transaction as the items. cachedIn(viewModelScope)in the ViewModel,collectAsLazyPagingItems()in the UI, andPagingDatakept out of theUiStateclass.initialize()returnsSKIP_INITIAL_REFRESHwhile the cache is fresh, so starts are instant and scroll position survives process death.LazyColumnwithitemKey { it.id },itemContentTypewhen row kinds mix, and footer states fromloadState.appendwithretry().- Coil
AsyncImagewith the thumbnail URL, a bounded size from the image's aspect ratio, andplaceholderanderrorpainters. Caches configured once throughSingletonImageLoader.Factory. rememberLazyListState()for scroll, with the list shown only once items have loaded.- Pull-to-refresh with Material 3
PullToRefreshBox, callingrefresh()and reading the mediator's refresh load state. - Baseline Profile generated with the
androidx.baselineprofileplugin andBaselineProfileRule; scrolling measured withFrameTimingMetricand Perfetto.