Mobile Design Rounds
Case studyAndroidiOS15 min read

Design a pagination library (Android and iOS): API, state model and caching

Last reviewed . Drafted with AI assistance. Checked against official documentation where noted (how this is checked). Part of: The five-step method · Staff-level guide.

Build it. The database schema, API, code and platform limits for a pagination library are on a separate page: Build it: a pagination library on Android and iOS (20 min read).

Try it. Change one thing and watch a list repeat or miss posts, in the pagination race.

How to read this. This page is a 45-minute round (the length I assume), in the order I would spend it. API sketches, config rules, threading, iOS code and platform limits are in the build guide. The follow-up questions are my reconstruction of challenges that public prep material reports, not transcripts of real rounds.

TL;DR. Ask why not Paging 3 (Google's Android paging library) first. Build only for one contract shared with iOS. Keep the public core small: a page source, a config, a state per direction and a stream. A private engine owns generations (each refresh starts a new numbered one, and late results from an old one are dropped), one load at a time per direction, and prefetch (loading ahead). Every default is API. On iOS the same contract is an async page source and an actor-owned engine with one stream per subscriber.

Patterns in this round.

  • State machine (each direction has its own load state)
  • Repository (an optional mediator, code that saves network pages into a local database that is the source of truth)
  • Observer (the library gives the caller a stream of states)
  • Facade and adapter (a small public core hides a private engine)
  • Strategy (the caller supplies the page source)

More in design patterns in mobile rounds.

Free: one follow-up round a week. A short interview question with a weak and a strong answer, by email. You also get the cheat sheet.

1. Scope and constraints (minutes 0 to 4)

In short: Ask why not Paging 3, set the scope, and park placeholders, two-way lists and telemetry.

A prompt I would expect: "Design a pagination library for our mobile apps." My users are engineers; my product is the API. I ask five things:

  • Who uses it? Five app teams, different backends.
  • Which key styles? Page number, offset and cursor (a server token that points to the next page), with cursor steered.
  • A database too? Network by default. A database is optional, through a mediator (code that writes fetched pages into it).
  • Which UI toolkits? None in the core.
  • The server? A page, and maybe a next key.
In scopeOut of scopeParked until you ask
Page source contract and configImage loadingPlaceholders (empty rows for items not loaded yet) and jumping
Load state and a result streamList renderingTwo-way lists
Optional database mediator, test toolsThe network stackTelemetry hooks

The phone does four things:

What the phone doesRequirement at riskDeep dive
Destroys the screen, or kills the processList and scroll position surviveClient structure (3)
Changes the data while the user scrollsNo jump, no repeated rowsData changes underneath (4.1)
Scrolls fast (a fling) over a slow or unstable networkFew requests, no wasted dataLoad engine and state (4.2)
Runs low on memoryA bounded cacheLoad engine and state (4.2)

Your decision. The scope follow-up question I expect: "Paging 3 already exists, and the same library must serve iOS." Do you adopt it, wrap it, or build?

First idea, and why it fails. Start drawing classes, or say "use Paging 3" and stop. Both fail when the exercise is the library: one shows no judgment, the other no design.

What I would say.

Say this. "On Android, I would adopt Paging behind a thin module unless someone can name what it cannot do. A contract shared with iOS is a reason to build, so I will design that. I am parking placeholders, two-way lists and telemetry."

I reject a hand-built engine on both platforms from day one: two codebases before anyone names a gap.

The follow-up question I expect:

"Paging compiles for iOS now. Why build?"

The release notes list iOS targets for the common modules, so I claim no unchecked gap. I would test three guesses:

  • Swift ergonomics (how natural the API feels)
  • House rules
  • Binary size

45-minute plan

MinutesStepDraw or say by the endCut if behind
0 to 4Scope and constraintsAdopt or build, scopeFewer questions
4 to 14Data and contractsGeneric key, four-line contractThe numbers
14 to 22Client structureLayers, who owns the streamOne line per layer
22 to 40Make the hard part workGenerations, one load per direction, load stateState in brief
40 to 45Break it, ship it, roll it backTop failures, the flag, deprecationTwo failures and the flag

2. Data and contracts (minutes 4 to 14)

In short: Keys are generic, docs steer people to cursors, and the source says where to restart.

Your decision. The host app's backend pages by number, offset or cursor, and rows change underneath. Which key type does the library accept, and what do you steer people toward?

First idea, and why it fails. Put an integer page number in the API. When a row is inserted during a scroll, every later page moves: a row is skipped or shown twice. Deep offsets slow the server.

What I would say. The key is a generic type, so all three styles fit, and the docs steer people to cursors. I do not forbid offset; I will not control every backend. I reject a fixed integer key.

The follow-up question I expect:

"The backend returns the same cursor twice. And what about one that has expired?"

The engine compares the next key with the current one. Each case has a defined result:

  • Same key twice, or several empty pages in a row: paging ends with an error, not a loop.
  • Expired cursor: a typed error, then a refresh from the restart key.

The contract has four lines:

  • Load: parameters in (a key, a size, a direction); a page, an error or an invalid result (a signal that the source is out of date and must be replaced) out.
  • Restart: given what is on screen, return the key to restart from.
  • Size is a hint. The source may return a short or long page.
  • The library never removes repeated items by item ID. The app or its database does.

Paging documents both a refresh key and an invalid result (load and display). The sketch has no invalid result. Add one.

My own assumptions, not measurements:

AssumptionArithmeticWhat it settles
A row is 2 KB of JSON, a page is 20 rows, the first load is three pages40 KB a page, 120 KB firstThe source treats size as a hint
A fling passes 30 rows a second, a load takes 400 ms, prefetch is 20 rows12 rows pass per load; 20 rows is 0.67 s of leadOne page of prefetch is enough
A row is 3 KB in memory200 rows is 0.6 MB; the rule needs max size (the cap on loaded rows) at least 20 + 2 x 20 = 60Memory is not why I cap text rows. The cap stays optional, with a check

3. Client structure (minutes 14 to 22)

In short: A state holder that outlives the screen owns the stream. The database keeps rows after a kill.

Your decision. Who owns the paged stream and its cache: the screen, one object for the whole app, or a state holder that outlives the screen?

First idea, and why it fails. The screen builds the pager and collects it. But rotation rebuilds the screen, and a new collection starts from the first page. A PagingData (a snapshot of the paged list) can be collected only once unless cached (transform).

What I would say. The ViewModel (Android's state holder for a screen) builds the Pager and caches the stream in its scope, as the Paging docs do (load and display). A repository can build it if two screens share a list. On iOS: an @Observable model (or an object with @Published state) that the screen owns, or a shared store for two screens, holds the pager. Rotation does not rebuild it.

I reject a singleton, which outlives every screen, and a service. When the list must survive a killed process, the database holds the rows. To return to the exact scroll spot, I need a saved anchor key (the key of an item near the visible rows). That is my design, not in the Paging docs.

  • On iOS, rows after a kill: the Core Data or SwiftData store holds them, the same as Room.
  • On iOS, scroll spot: save the anchor key with @SceneStorage (or an NSUserActivity), then restart the load from that key.

The follow-up after that: "The app is killed on page 3. Where does the next key come from on relaunch?"

  • With a database mediator, it comes from the database. I would save the next key in the same transaction as the page rows, so rows and key never disagree.
  • Keep the key per list and per account. A key for one user's list must never load another's.
  • On relaunch, show the saved rows and refresh in the background. If the saved key is rejected as expired, the typed error leads to a restart-key refresh.
  • Do not build a key again, such as "last page number plus one". A guessed key can skip or repeat rows.
  • With no database, nothing is saved. The list starts from page one unless the host saves the anchor key.

The follow-up question I expect:

"Two screens show the same list."

Caching shares the stream between collectors. One owner scope builds the pager; each screen only collects.

streamcallsfetchoptionalwritesApp codeViewModel / presenterPublic APIPager, Config, LoadStateInternal enginededupe, cache, prefetchPageSourceapp-supplied: one pageMediatoroptional: network + DBNetwork APIcursor or page keyLocal databasesource of truthApp codeViewModel / presenterstreamPublic APIPager, Config, LoadStateInternal enginededupe, cache, prefetchcallsPageSourceapp-supplied: one pageMediatoroptional: network + DBNetwork APIcursor or page keyLocal databasesource of truth

More links

  • PageSource to Network API: fetch
  • Internal engine to Mediator: optional
  • Mediator to Local database: writes
Pagination library architecture: app code uses a small public API; an internal engine calls the app-supplied page source and optional mediator.

The Paging overview places the layers:

  • Source and mediator: the repository layer.
  • Pager and PagingData: the ViewModel layer.
  • LazyPagingItems: the UI.

The app supplies how to fetch a page; the library decides when. Three rules:

  • Nothing from a UI toolkit in the core.
  • Everything is internal until a user needs it.
  • A pager owns its state, so two lists never share a cache.

4. Make the hard part work (minutes 22 to 40)

In short: Each refresh starts a new generation, one load runs per direction, and state is per direction.

4.1 Data changes underneath (minutes 22 to 31)

Your decision. A row above the visible rows is deleted, or an old response arrives after a newer refresh. What does the list do?

First idea, and why it fails. On any change, reload from the top. The user loses their place, and a late old response replaces fresh rows with old ones.

What I would say.

Say this. "Every refresh starts a new generation. A result from an older generation is thrown away, even if the network call finished. The source tells me where to restart, from the item nearest the visible rows. With a database, the mediator writes in one transaction, and the database source marks itself out of date."

Paging can find the loaded item closest to a target position. This suits restart keys. I reject patching the list in memory, which works until a second writer appears.

The follow-up question I expect:

"Who starts the new generation if there is no Room?"

Room is Android's database library. Without it, nothing tells the source its data is out of date. The app must call invalidate, and the contract says so.

  • On iOS: Core Data reports changes through NSFetchedResultsController (SwiftData through @Query or its model context notifications). The mediator writes the page. That change marks the source out of date and starts a new generation, the same as Room does.
  • If the deleted row was the anchor, the anchor moves to its neighbor, and the restart key follows.

4.2 Load engine and state (minutes 31 to 40)

Your decision. The user scrolls fast, a load is running, and the next append fails. What does the engine do, and what does the UI see?

First idea, and why it fails. Load when the last row appears, with one loading flag. A fast scroll fires several calls for the same key. And one flag cannot say "keep the list, show a retry row" when an append fails, so the whole screen shows an error.

What I would say.

Say this. "Prefetch is a distance in items, and at most one load runs per direction. A refresh outranks an append and cancels it. State is kept per direction. The end of the list is a state, not an error. Retry repeats only the failed load. Refresh starts over."

I reject one boolean. Two verbs, retry and refresh, are my design. The load-state page shows only retry. It also says footers need placeholders off, which I would name if placeholders come up.

The follow-up question I expect:

"A host app sets max size 30 with page size 20 and prefetch 20."

Creating the config fails with a clear message, as in Paging (source).

  • The rule: max size is at least page size plus twice prefetch.
  • Here that is 20 + 2 x 20 = 60, so 30 fails.

If the interviewer cuts in, I answer first:

Say this. "Yes, two quick refreshes are harmless. The second cancels the first, and a late result is dropped. I was on load state, so I will finish that."

Each load type has its own state:RefreshNotLoadingPrependNotLoadingend reachedAppendErrorA failed append: the list staysa retry row shows at the endretry()repeats onlythe failed loadrefresh()starts over witha new generation
Refresh, prepend and append each keep their own state, so a failed append leaves the list on screen with a retry row.

4.3 Where iOS changes the design

The engine is the same. Apple has no official paging library, so the iOS version is yours to build and own. Swift code is in the build guide.

  • UIKit does not call its prefetch callback for every cell (Apple). Table views have a matching protocol, UITableViewDataSourcePrefetching. So a row appearing must also be able to start the load.
  • In SwiftUI, call the load from onAppear on the last few rows of a List or LazyVStack. Lazy containers only build rows near the screen, so this works in practice. Apple does not document it as a prefetch API.
  • A Swift stream is meant for one consumer, so each subscriber gets its own. The proposal that added it calls concurrent iteration a programmer error (SE-0314).
  • Key and item types must cross an actor boundary (a limit on which code may touch the data), so the requirement shows in the public signature.
  • Scroll position: keep an item ID as the anchor. UIKit can use a diffable data source. SwiftUI can use scrollPosition(id:) (iOS 17 and later).

5. Break it, ship it, roll it back (minutes 40 to 45)

In short: Each failure has a recovery. Rollback is the host app's flag plus a patch.

FailureUser seesData holdsRecovery
Duplicate deliveryAn error row, not a loopPages loaded so farThe same-key guard ends paging with an error
Out-of-order deliveryNothing oddCurrent generation onlyLate result from an old generation dropped
Long offline gapOld rows, then a refreshStale rows, the anchorTyped error, then a restart-key refresh
Process dies mid-writeOld or new first page, never halfLast committed transactionNext launch reads it
Sign-in expires during an appendThe list stays, with a retry rowLoaded pages and keysA typed auth error, not the end of the list. The host renews the token, then retry repeats only that load
Sign-in expires while a refresh and an append both runThe list staysLoaded pages and keysThe host renews the token once. The refresh retries first and the append is dropped, because a refresh outranks it
Permanent rejectionAn error with no retry buttonLoaded pagesSurface the error; retry only transient ones
Low storage or evictionA short reload on scroll backPages near the visible rowsFar pages dropped
Old app version meets new server contractNothing, if the server keeps bothOld cursors in host appsServer accepts old and new cursors

Rows without a source link are my design choices. Sources are in Further reading.

At release:

  • A Play staged rollout can be halted, and users who already have the build keep it (Play help). My library lives inside host apps, so halting is their decision.
  • Old library versions stay in host apps for months, so the server accepts old cursors.
  • The host app's off switch reaches installed apps: a remote flag around behavior such as prefetch distance.
  • A flag cannot undo a public signature or schema change. That waits for a major version and a deprecation window.

Say this. "A release already inside host apps cannot be recalled, so rollback is the flag plus a patch. I would watch request counts, memory and jank (visible stutter). Left out: placeholders, two-way lists, telemetry."

6. Follow-ups that change a constraint

In short: Each follow-up changes one constraint and has a strong and a weak answer.

Practice prompts, not a claim about what interviewers ask.

  1. A list of a million items, and the user jumps to the middle. Strong: I say what breaks: placeholders need a known total, and a jump needs a restart key near the target and a threshold for dropping loaded pages. Weak: load them all in the background.
  2. Open a chat at a search hit and scroll both ways. Strong: the first load is a refresh at the hit's key. Then prepend and append run alone, each with its own state. Weak: a second pager glued on top.
  3. Another device edits the list while this one scrolls. Strong: a push or sync marks the source out of date, a new generation reads the changed rows, and the anchor keeps the user in place. Weak: refresh from the top every time.
  4. The user logs out and someone else logs in. Strong: the cache belongs to the old account, so I tear down the pager with its owner. A telemetry hook carries a kind of key, not the key, since a cursor can hold user data. Weak: clearing the list, keeping the cache.
  5. After a library release, host apps report scroll jank. Strong: defaults are API, so I compare page size and prefetch first, then main-thread work, then request counts. Flip the flag, ship a patch. Weak: "roll back the release."
  6. The server changes its cursor encoding while three old versions are in the field. Strong: the library treats cursors as opaque, but old apps still send theirs. The server accepts both; stored cursors are dropped on upgrade. Weak: assuming everyone updates.

7. What changes by level

In short: Mid builds the basics, senior adds the split, staff adds the decision and rollout.

These levels are my own reading of vendor and prep material, not any company's rubric.

  • Mid-level: a generic page source, a pager that loads near the end, loading and error state, retry.
  • Senior: a public and internal split, per-direction state, generations, a written threading contract.
  • Staff: adopt-or-build with a revisit trigger, a deprecation plan, a multi-team rollout.

Common weak answers. These repeat across public prep material. This is not a dataset.

  • Ten minutes on the backend, happy path only.
  • Naming Paging 3 without saying what it covers.
  • The UI calling the network.
  • No restart key, so every change jumps to the top.
  • No versioning story.
  • Designing the list view, not the library.

Staff answer: the decision and the rollout

Decision: on Android, adopt Paging 3 behind a thin module unless I can name what it cannot do. For a contract shared with iOS, first test whether the Kotlin-compiled common modules meet it. Build only if Swift ergonomics, house rules or binary size fail.

Alternative: a hand-built core on both platforms: full control, larger cost. Revisit trigger: two or more teams work around the same limit, or the wrapper becomes the thing teams fight.

Rollout: a release goes to a sample app, one host app, then the rest, with defaults behind a flag. Guardrail: no rise in request counts or memory. A deprecated API is removed only when adoption telemetry shows the old version below a threshold agreed in advance.

What I read and what is my view: the Paging components were read on developer.android.com, the halting behavior on the Play help page. The shared-core reasons, telemetry, thresholds and policy are my opinion. The native vs cross-platform guide covers shared against separate code.

Test yourself

In short: Seven questions from this case. Answer each one out loud first, then open the answer.

1. Why not put an integer page number in the API?

When a row is inserted during a scroll, every later page moves, so a row is skipped or shown twice. Deep offsets also slow the server. The key is a generic type so all three styles fit, and the docs steer people to cursors.

2. The backend returns the same cursor twice, or an expired one. What happens?

The engine compares the next key with the current one. The same key twice ends paging with an error, not a loop. An expired cursor gives a typed error, then a refresh from the restart key.

3. Who owns the paged stream and its cache?

A state holder that outlives the screen, such as the ViewModel, builds the Pager and caches the stream in its scope. A screen alone would restart from the first page on rotation. A singleton outlives every screen.

4. A row above the visible rows is deleted, or an old response arrives after a refresh. What does the list do?

Every refresh starts a new generation. A result from an older generation is thrown away, even if the network call finished. The source says where to restart, from the item nearest the visible rows.

5. The user scrolls fast and the next append fails. What does the UI see?

State is kept per direction. The list stays on screen with a retry row, and the end of the list is a state, not an error. At most one load runs per direction, and a refresh outranks and cancels an append.

6. A host app sets max size 30 with page size 20 and prefetch 20. What happens?

Creating the config fails with a clear message. The rule is that max size must be at least page size plus twice prefetch, here 20 + 2 x 20 = 60.

7. On iOS, Apple's prefetch callback is not called for every cell. What do you do?

I do not rely on it alone. A row appearing must also be able to start the load. In SwiftUI I call the load from onAppear on the last few rows of a List or LazyVStack. Apple does not document that as a prefetch API, but lazy containers only build rows near the screen, so it works in practice.

Further reading (official docs)

Further reading (other, not official)

Prep material that shaped the questions I asked. These are references, not sources of wording. I read only the public parts of the commercial ones.

  • The library chapter of the ByteByteGo mobile system design book
  • The library-prompt article and pagination lesson from DesignGurus
  • The weeeBox mobile design repository
  • The Educative mobile course
Words on this page (14)
Actor
A Swift type that runs one task at a time. This keeps its data safe when many tasks use it.
Cursor
A saved place in a list. The server gives it to the app, and the app sends it back to get the next part.
Dedupe
To keep only one copy of the same item. For example, a message that arrives twice is stored once.
Host app
The app that contains an SDK. You write the SDK, and another team writes the host app.
Paging
Loading a long list in small parts. The app asks for one page at a time.
Prefetch
Loading data before the user asks for it. It makes scrolling smooth, but it can waste data.
Remote flag
A setting that the server can change. It can turn a feature on or off without a new release.
Repository
The class that reads and writes data for the rest of the app. It hides whether the data comes from the network or the database.
Rollback
Going back to the old behavior after a problem. A build on a user's phone cannot be taken back, so teams use a kill switch.
Room
Android's library for the database on the phone. You use a DAO to read and write the data.
Snapshot
A copy of the data as it was at one moment. It is not a list of changes.
Staged rollout
A release to a growing share of users, not to everyone at once. It limits the harm of a bad release.
Stale data
Saved data that may be out of date. The app should show how old it is, or refresh it.
ViewModel
A class that holds the state of one screen. It survives a screen rotation.

Read the whole glossary

Verification notes (last reviewed 14 Oct 2026)
  • I read 10 official pages: the Paging guides, the Paging release notes, the PagingConfig source, Apple's prefetching page, SE-0314 and the Play staged-rollout help.
  • Documented: the max size rule (at least page size plus twice prefetch, else an exception), the defaults, the refresh key, the invalid result, caching with cachedIn, and one transaction for a refresh.
  • Documented: Apple says the prefetch callback is not called for every cell. SE-0314 says concurrent iteration of an AsyncStream is a programmer error.
  • Documented: a halted Play rollout leaves the build on devices that already have it. The page does not say anything can be recalled.
  • My design, not from docs: generations, one load per direction, separate retry and refresh verbs, the saved anchor key, and all the rollout and level advice.
  • My assumptions, not measurements: the sizes in section 2. The arithmetic is checked: 20 x 2 KB is 40 KB, 30 rows a second x 0.4 s is 12 rows, and 20 + 2 x 20 is 60.
  • Not verified: SwiftUI row appearance as a prefetch signal, and my guess that Kotlin-built Paging could fail the iOS ergonomics tests.
  • Not verified: the ViewModel and process-lifetime statements (standard lifecycle behavior, not quoted), and the 408 retry rule.
  • The follow-up questions are my reconstruction of challenges that public prep material reports. They are not transcripts of real rounds.

Questions or corrections?

Add them to the discussion thread for this case on GitHub. To post, you need a free GitHub account. What you write there is public and follows GitHub's terms. Good answers are added to this page.

Keep reading

Get the free one-page cheat sheet

One page: the five steps, a 45-minute time plan and two checklists. Print it or keep it on your phone.

We email you the cheat sheet after you confirm your address. You can also open it now from the Start here page. You also get a short email each week with a follow-up round, and a note when a new case is published. Unsubscribe any time. Privacy.