Design a news feed

Learn how to design an Android news feed for interviews with Paging 3, RemoteMediator, Room as source of truth, cursor pagination, and prefetching. About 25 minutes.

Why it matters

  • "Design a news feed" is one of the most common mobile system design interview questions, because infinite scrolling is the standard UX for social and news apps.
  • Naive pagination shows duplicate or missing posts when new content arrives, and holding every loaded post in a ViewModel list wastes memory in long sessions.
  • Interviewers test how you handle flaky networks, offline reading, and process death, which is where Paging 3 with RemoteMediator and Room comes in.
  • Deciding what the client owns (caching, paging, prefetching, images) and what the server owns (ranking) is the senior-level part of the answer.

The simple explanation

  • A library with infinite shelves.
  • You cannot carry all books at once.
  • You ask the librarian for 'the next 20 books after book ID 500'.
  • You keep a small cart (cache) of books to read immediately.

How do you design a news feed on Android? Fetch the feed from a cursor-paginated API, store each page in Room, and let the UI read only from Room through Jetpack Paging 3. A RemoteMediator sits between the two: when the list nears the end of what is stored, Paging calls its load() with LoadType.APPEND, it fetches the next page with the saved cursor and writes it to the database. Room's generated PagingSource is invalidated and the new items appear. On refresh (LoadType.REFRESH) it fetches the first page and replaces the cached feed in one transaction.

Because the database is the single source of truth, the feed opens instantly from cache, works offline, and survives process death. The UI collects PagingData from a Pager, cached in the ViewModel with cachedIn(viewModelScope).

Key components include:

ComponentResponsibility
Cursor-based APIReturns a next_cursor string to fetch the next page
Room databaseStores the feed items in server order and a remote-key row with the next cursor
RemoteMediatorFetches the next page on REFRESH or APPEND and writes it to Room
PagingSourceGenerated by Room from a DAO query; pages the stored items to the UI
Pager + PagingDataBuilds the stream the UI collects with collectAsLazyPagingItems()

Ranking happens on the server. The client stores items in the order the server returned them (a position column) and never re-sorts by its own idea of relevance. Paging handles prefetching through PagingConfig.prefetchDistance (by default equal to pageSize), so the next page loads before the user reaches the bottom. Errors surface through LoadState, so the list can show a retry row. Images in each card go through Coil or Glide, which downsample to the view size and cancel requests for cards that scroll off screen.

Notes

  • Use cursor-based pagination instead of offset/limit, so new posts at the top do not shift pages and cause duplicates or gaps.
  • Room is the single source of truth: the feed opens from cache, works offline, and the UI never mixes network and database results.
  • Store the next cursor in a remote-keys table, written in the same withTransaction block as the items, so APPEND can resume after an app restart.
  • On REFRESH, clear the old feed and its cursor and insert the first page inside one transaction, so the user never sees an empty or mixed list.
  • Store the server's order in a position column and ORDER BY position. Ranking is the server's job.
  • Override initialize() to return SKIP_INITIAL_REFRESH when the cache is fresh enough, so opening the app does not always hit the network.
  • Tune PagingConfig(pageSize, prefetchDistance) instead of writing your own scroll listener; Paging prefetches for you.
  • Handle LoadState (refresh, append) to show loading, error and retry rows.
  • Let Coil or Glide load card images: they downsample to the view size and cancel off-screen requests.
  • Room's generated PagingSource invalidates itself when the table changes; a hand-written one must call invalidate() yourself.

Code example

A cursor-based RemoteMediator for the feed. The API returns nextCursor, which is saved in a one-row remote-keys table in the same transaction as the posts.

import androidx.paging.ExperimentalPagingApi
import androidx.paging.LoadType
import androidx.paging.PagingSource
import androidx.paging.PagingState
import androidx.paging.RemoteMediator
import androidx.room.Dao
import androidx.room.Entity
import androidx.room.PrimaryKey
import androidx.room.Query
import androidx.room.Upsert
import androidx.room.withTransaction
import java.io.IOException
import retrofit2.HttpException
import retrofit2.http.GET
import retrofit2.http.Query as ApiQuery
 
@Entity(tableName = "feed_posts")
data class PostEntity(
    @PrimaryKey val id: String,
    val title: String,
    val imageUrl: String?,
    val position: Long, // server order; the client never re-ranks
)
 
@Entity(tableName = "feed_remote_key")
data class FeedRemoteKey(@PrimaryKey val id: Int = 0, val nextCursor: String?)
 
data class FeedPageDto(val items: List<PostDto>, val nextCursor: String?)
data class PostDto(val id: String, val title: String, val imageUrl: String?)
 
interface FeedApi {
    @GET("feed")
    suspend fun feed(@ApiQuery("cursor") cursor: String?, @ApiQuery("limit") limit: Int): FeedPageDto
}
 
@Dao
interface FeedDao {
    @Query("SELECT * FROM feed_posts ORDER BY position ASC")
    fun pagingSource(): PagingSource<Int, PostEntity>
 
    @Upsert
    suspend fun upsertAll(posts: List<PostEntity>)
 
    @Query("SELECT MAX(position) FROM feed_posts")
    suspend fun maxPosition(): Long?
 
    @Query("DELETE FROM feed_posts")
    suspend fun clearPosts()
 
    @Upsert
    suspend fun saveKey(key: FeedRemoteKey)
 
    @Query("SELECT * FROM feed_remote_key WHERE id = 0")
    suspend fun key(): FeedRemoteKey?
}
 
@OptIn(ExperimentalPagingApi::class)
class FeedRemoteMediator(
    private val db: FeedDatabase, // RoomDatabase with feedDao(): FeedDao
    private val api: FeedApi,
) : RemoteMediator<Int, PostEntity>() {
 
    override suspend fun load(loadType: LoadType, state: PagingState<Int, PostEntity>): MediatorResult {
        val dao = db.feedDao()
        val cursor: String? = when (loadType) {
            LoadType.REFRESH -> null
            LoadType.PREPEND -> return MediatorResult.Success(endOfPaginationReached = true)
            LoadType.APPEND -> {
                val key = dao.key()
                    ?: return MediatorResult.Success(endOfPaginationReached = false) // refresh not done yet
                key.nextCursor ?: return MediatorResult.Success(endOfPaginationReached = true)
            }
        }
        return try {
            val page = api.feed(cursor = cursor, limit = state.config.pageSize)
            db.withTransaction {
                if (loadType == LoadType.REFRESH) dao.clearPosts()
                val start = (dao.maxPosition() ?: -1L) + 1
                dao.upsertAll(page.items.mapIndexed { i, dto ->
                    PostEntity(dto.id, dto.title, dto.imageUrl, position = start + i)
                })
                dao.saveKey(FeedRemoteKey(nextCursor = page.nextCursor))
            }
            MediatorResult.Success(endOfPaginationReached = page.nextCursor == null)
        } catch (e: IOException) {
            MediatorResult.Error(e)
        } catch (e: HttpException) {
            MediatorResult.Error(e)
        }
    }
}
  • PREPEND returns at once: the feed only grows downward, and new posts arrive through a refresh.
  • An APPEND before the first refresh has written a key returns endOfPaginationReached = false, so Paging asks again after the refresh instead of treating the feed as finished.
  • Clearing old posts, inserting the page and saving the cursor happen in one withTransaction block, so the stored cursor always matches the stored items.
  • Only IOException and HttpException become MediatorResult.Error; anything else (including CancellationException) propagates.
  • The repository builds Pager(config = PagingConfig(pageSize = 20), remoteMediator = FeedRemoteMediator(db, api)) { db.feedDao().pagingSource() }.flow, and the ViewModel applies cachedIn(viewModelScope).

Run the idea in plain Kotlin

enum class LoadType { REFRESH, APPEND }

data class Page(val items: List<String>, val nextCursor: String?)

// Server: newest-first, cursor = id of the last post returned
class FakeFeedApi {
  val ids = ArrayDeque((12 downTo 1).toList())

  fun feed(cursor: String?, limit: Int): Page {
      val after = cursor?.toInt() ?: Int.MAX_VALUE
      val page = ids.filter { it < after }.take(limit)
      val more = page.isNotEmpty() && ids.any { it < page.last() }
      return Page(page.map { "post-" + it }, if (more) page.last().toString() else null)
  }
}

// Stands in for Room: the feed table plus the remote-key row
class LocalDb {
  val posts = mutableListOf<String>()
  var nextCursor: String? = null
}

class FeedMediator(private val api: FakeFeedApi, private val db: LocalDb) {
  // Returns true when the end of the feed is reached
  fun load(type: LoadType, pageSize: Int): Boolean {
      val cursor = if (type == LoadType.REFRESH) null else (db.nextCursor ?: return true)
      val page = api.feed(cursor, pageSize)
      // In Room this block is one withTransaction
      if (type == LoadType.REFRESH) db.posts.clear()
      db.posts.addAll(page.items)
      db.nextCursor = page.nextCursor
      return page.nextCursor == null
  }
}

fun main() {
  val api = FakeFeedApi()
  val db = LocalDb()
  val mediator = FeedMediator(api, db)

  mediator.load(LoadType.REFRESH, 5)
  println("After refresh: " + db.posts.size + " posts, cursor=" + db.nextCursor)

  api.ids.addFirst(13) // a new post is published while the user scrolls

  var end = mediator.load(LoadType.APPEND, 5)
  println("After append: " + db.posts.size + " posts, duplicates=" + (db.posts.size - db.posts.toSet().size))
  end = mediator.load(LoadType.APPEND, 5)
  println("After append: " + db.posts.size + " posts, end=" + end)

  mediator.load(LoadType.REFRESH, 5)
  println("Pull to refresh: " + db.posts.joinToString(", "))
}

Expected output:

After refresh: 5 posts, cursor=8
After append: 10 posts, duplicates=0
After append: 12 posts, end=true
Pull to refresh: post-13, post-12, post-11, post-10, post-9

In production

Duplicate items on scroll
  • Users reported seeing the same news article twice while scrolling.
  • The app used offset-based pagination (LIMIT/OFFSET).
  • New articles were being inserted at the top of the feed, shifting indices.
The fix
  • Switched from offset-based pagination to cursor-based pagination.
  • The API now returns an opaque nextCursor (for example an encoded id of the last item), and the client sends it back for the next page.
  • The RemoteMediator saves the cursor in a remote-keys table in the same transaction as the items, so paging resumes correctly after process death.
Memory exhaustion during long sessions
  • App crashed with OutOfMemoryError after a long period of scrolling.
  • The entire list of news objects was being held in a simple Kotlin List in a ViewModel.
  • The list grew indefinitely as the user scrolled.
The fix
  • Moved the feed to Jetpack Paging 3 with Room as the source of truth, so items live in the database instead of a growing ViewModel list.
  • Set PagingConfig(pageSize = 20, maxSize = 200) so Paging drops pages far from the viewport (by default maxSize is unbounded and nothing is dropped). Dropped pages reload from Room when the user scrolls back.
  • Let Coil load card images at view size, since decoded bitmaps were a large part of the memory growth.

Common mistakes

  • Using Offset/Limit pagination. New items inserted at the top cause items to shift, leading to duplicates in the client view.
  • Fetching directly to UI. Without a local database, the app cannot handle offline viewing or survive process death gracefully.
  • Ignoring LoadState. Users won't know if the app is loading or if a network error occurred, leading to a 'frozen' feel.
  • Not clearing the cache on refresh. If you insert a fresh first page without deleting the old feed and cursor, posts the server removed or re-ranked stay mixed in with the new ones. Clear and insert inside one withTransaction so the UI never sees an empty list in between.
  • Re-sorting on the client. Sorting the feed by a local timestamp or score fights the server's ranking. Store the server order in a position column and query by it.

Interview questions

Answer out loud first. Then reveal the answer and compare it at each depth.

“How would you implement an infinite scroll feature in an Android app?”

“What is the difference between offset-based and cursor-based pagination?”

“How do you handle network errors during a pagination fetch?”

“How do you ensure the app doesn't crash from memory issues when scrolling a long feed?”

Quiz

Which component in Paging 3 is responsible for coordinating network and database loads?

Why is cursor-based pagination preferred for news feeds?

A RemoteMediator handles LoadType.REFRESH by inserting the new first page without deleting the old feed. What goes wrong?

In a Paging 3 architecture, what should the UI observe?

0 of 4 answered

Mini task

Task: Implement a Mock Cursor Paging Logic

  1. Create a Kotlin class NewsApi with a function fetchNews(cursor: String?): NewsResponse.
  2. The NewsResponse should contain a list of strings (e.g., "Article 1", "Article 2") and a nextCursor.
  3. Implement the logic so that if the nextCursor is null, the pagination stops (simulate reaching the end of the feed).
  4. Create a NewsRepository that calls this API, stores the results in a MutableList (simulating the Room table) and keeps the latest nextCursor in a separate field (simulating the remote-keys table).
  5. In your main function, simulate a user scrolling by calling the repository's fetch method 3 times.
  6. Print the total number of items collected in the repository after the 3 calls.

Done condition: The program prints a list of items and stops correctly when the cursor becomes null or the loop ends, without throwing an error.

Next: Design a chat app