The mobile system design framework
Why it matters
- Most senior Android interview loops include a mobile system design round. Without a fixed structure you ramble, skip offline handling, and run out of time.
- The framework forces you to separate client concerns (Room, RemoteMediator, WorkManager) from server concerns, which is where most candidates lose points.
- Cursor-based pagination, idempotency keys, and the outbox pattern come up in almost every client design; knowing them cold is a clear mid-to-senior signal.
- The same structure applies to the later lessons in this module (news feed, chat, offline notes, image loading, file upload), so learning it once saves you from re-deriving it each time.
The simple explanation
- You are the architect of a single building, not the whole city.
- Phase 1 is the client meeting: how many floors, who lives here, do they need a basement for storage?
- Phase 2 is the floor plan: rooms, doors, which way the water flows.
- Phase 3 is the plumbing spec: pipe sizes, pressure, what happens when the main is shut off.
- Phase 4 is the storage system: what is kept in the house vs. the warehouse, and how they stay in sync.
- Phase 5 is the stress test: what breaks at 3 a.m. when the power flickers.
How do you answer a mobile system design interview? Work through five phases in order: clarify requirements, sketch the client components, define the API contract, design the client data layer, then go deep on two or three trade-offs. You design the Android client; the server appears only as the API you call. You do not start coding. You start by asking questions.
Phase 1 – Clarify (5 min). Functional scope (screens, user actions), non-functional constraints (latency, offline, battery, memory, low-end devices), scale (users, items per screen, image and file sizes), and offline needs (which features must work with zero network). Any numbers you use are assumptions you state out loud. Write the answers on the whiteboard.
Phase 2 – High-level client diagram (5 min). Components: Compose or XML UI, ViewModel + StateFlow, repository, Room database, network layer (Retrofit/OkHttp or Ktor), and a sync coordinator. Draw data-flow arrows. Mention server only as the interface boundary.
Phase 3 – API design (5 min). Choose REST, GraphQL, WebSocket, or SSE. Define cursor-based pagination (not offset). Add idempotency keys for mutations. Specify error codes and retry semantics.
Phase 4 – Client data layer (5 min). Room is the source of truth. RemoteMediator pulls pages and upserts. An outbox table queues mutations while offline, drained by WorkManager. Caching: an in-memory LRU sized as a fraction of the app's memory budget, plus a disk cache for images.
Phase 5 – Deep dives and trade-offs (10 min). Pick 2–3 areas: battery (WorkManager vs foreground service, push vs polling), network (connection reuse, compression, retries with backoff), memory (downsampling, LRU eviction), security (token refresh, encrypted storage), accessibility, observability (crash and ANR reporting, sync metrics).
| Phase | Time | Output |
|---|---|---|
| Clarify | 5 min | Requirements list |
| High-level | 5 min | Component diagram |
| API | 5 min | Endpoint contracts |
| Data layer | 5 min | Sync + cache model |
| Deep dives | 10 min | 2–3 trade-off analyses |
That is about 30 minutes; the rest of the round usually goes to introductions, follow-up questions and your own questions. Ask the interviewer how long the round is and treat these times as a guide, not a rule. The later lessons in this module (news feed, chat, offline notes, image loading, file upload) are each one full pass through this structure with a concrete problem.
Notes
- The five phases are sequential and time-boxed. Skipping Phase 1 (clarify) is a common way to lose the round, because you end up designing for the wrong problem.
- Prefer cursor-based pagination (
nextCursor: String?) over offset for feeds and lists that change. Offset breaks when rows are inserted or deleted mid-scroll; a cursor is a stable pointer the server resolves. - Every non-idempotent mutation (typically POST) needs an idempotency key: a client-generated UUID created with the local write. Without it, a retried POST can create duplicate records on the server.
- In the client data layer,
Roomis the source of truth. The UI reads fromRoomviaFlow.RemoteMediatorfetches pages and upserts. The network is a cache refresher, not the primary store. - The outbox pattern stores pending mutations in a local table with a small state machine (
PENDING → IN_FLIGHT → done, orFAILEDafter a permanent error). AWorkManagerworker drains it in order when the network returns. Chat adds its own delivery states (SENT,DELIVERED,READ) on the message row, which are separate from the outbox. This is the backbone of the chat and offline-notes lessons. - For image loading, size the in-memory LRU cache as a fraction of the app's memory budget (
ActivityManager.getMemoryClass()orRuntime.getRuntime().maxMemory()), not a hard-coded value. Downsample to the view size while decoding. See the image-loading lesson for the full pipeline. - For real-time features (chat), use a WebSocket while the app is in the foreground and reconnect with exponential backoff and jitter. When the app is in the background, rely on FCM push, which is best-effort: delivery is not guaranteed and high-priority messages are rationed. See the chat lesson.
- For background work (file upload, sync), prefer
WorkManagerwith constraints. For long transfers a worker can callsetForeground()with aForegroundInfoof typedataSync(required from Android 14). On Android 15,dataSyncforeground services get 6 hours per 24 hours, so a foreground service is not the default answer. - In Phase 5, pick two or three deep-dive areas and go deep. Interviewers reward a thorough trade-off analysis on two topics over a shallow mention of six.
- Mention server behaviour only as the interface contract (status codes, payload shape, sequence numbers). You are designing the client, not the backend.
Code example
This Kotlin model shows the client data-layer output of Phase 4: a cursor-paged response, an outbox entry with a state machine, and a sync coordinator that ties them together. It is the shape you sketch on the whiteboard before any framework code.
// Phase 4 output: client data-layer model
// Room is source of truth; RemoteMediator upserts pages;
// outbox queues mutations while offline.
enum class SyncState { IDLE, SYNCING, FAILED, UP_TO_DATE }
// Cursor-paged response from the server (REST or GraphQL)
data class CursorPage<T>(
val items: List<T>,
val nextCursor: String?, // null = last page
val hasMore: Boolean
)
// One row in the local outbox table (Room entity)
data class OutboxEntry(
val id: String, // client UUID = idempotency key
val endpoint: String, // e.g. "POST /messages"
val payload: String,
val state: OutboxState,
val attempts: Int = 0
)
// Rows are deleted once the server accepts them
enum class OutboxState { PENDING, IN_FLIGHT, FAILED }
class SyncCoordinator {
var state: SyncState = SyncState.IDLE
private set
// Called from RemoteMediator.load() or a WorkManager worker
fun start(cursor: String?) {
state = SyncState.SYNCING
// 1. fetch CursorPage via Retrofit/Ktor
// 2. upsert items into Room
// 3. store nextCursor in a prefs/Room meta row
// 4. drain outbox: send PENDING entries in creation order
}
fun onNetworkLost() {
state = SyncState.FAILED
// mutations stay in outbox; UI shows stale data + "retry" chip
}
fun onNetworkRestored() {
// WorkManager's network constraint and backoff decide when this runs
start(cursor = null) // or the last saved cursor
}
}nextCursoris aString?(opaque token the server generates), not an integer offset. This keeps pagination stable under inserts and deletes.OutboxEntry.iddoubles as the idempotency key sent in theIdempotency-Keyheader, so a retried POST does not create a duplicate server record.SyncCoordinatoris the single place that transitionsSyncState; in a real app it exposes it as aStateFlowso the UI can show a progress bar or a "retry" chip.
Run the idea in plain Kotlin
data class Post(val id: Int)
data class CursorResult(val items: List<Post>, val nextCursor: String?)
// Newest-first feed. The cursor is the id of the last item the client saw.
class FakeServer {
val posts = ArrayDeque((25 downTo 1).map { Post(it) })
fun pageByCursor(cursor: String?, limit: Int): CursorResult {
val after = cursor?.toInt() ?: Int.MAX_VALUE
val items = posts.filter { it.id < after }.take(limit)
val hasMore = posts.any { it.id < (items.lastOrNull()?.id ?: 0) }
return CursorResult(items, if (hasMore) items.last().id.toString() else null)
}
fun pageByOffset(offset: Int, limit: Int): List<Post> =
posts.drop(offset).take(limit)
}
fun ids(items: List<Post>) = items.joinToString(", ") { it.id.toString() }
fun main() {
val server = FakeServer()
val first = server.pageByCursor(null, 5)
val firstByOffset = server.pageByOffset(0, 5)
println("Page 1: " + ids(first.items) + " nextCursor=" + first.nextCursor)
// Two new posts arrive at the top while the user is reading page 1
server.posts.addFirst(Post(26))
server.posts.addFirst(Post(27))
val second = server.pageByCursor(first.nextCursor, 5)
println("Page 2 by cursor: " + ids(second.items))
val secondByOffset = server.pageByOffset(5, 5)
val repeated = secondByOffset.filter { it in firstByOffset }
println("Page 2 by offset: " + ids(secondByOffset) + " repeated=" + ids(repeated))
}Expected output:
Page 1: 25, 24, 23, 22, 21 nextCursor=21
Page 2 by cursor: 20, 19, 18, 17, 16
Page 2 by offset: 22, 21, 20, 19, 18 repeated=22, 21
In production
- Users reported that in a chat screen, older messages appeared below newer ones after the app reconnected from a network drop.
- The client sorted the local
Roomtable bycreatedAt(a client-side timestamp). Two devices with clock skew produced interleaved timestamps. - The outbox drained in insertion order, but the server had already assigned a monotonic
seqnumber to each message.
- Added a
seq: Longcolumn to the message entity, populated from the server response. - Changed the
Roomquery toORDER BY seq ASCinstead ofcreatedAt. - Messages not yet acknowledged (no
seq) sort after acknowledged ones, in local creation order, so the user still sees their pending sends at the bottom. - The outbox drain sends an
Idempotency-Keyheader, so a retried send returns the originalseqinstead of creating a duplicate. - Added a unit test that simulates clock skew and asserts ordering by
seq.
- Crash reports showed
OutOfMemoryErroron low-RAM devices when scrolling a large image grid. - The in-memory LRU cache was hard-coded to a fixed size, which was too large for low-memory devices.
- Bitmaps were decoded at full resolution before being shrunk to the view size.
- Replaced the fixed size with a fraction of
ActivityManager.getMemoryClass(), which is how Coil and Glide size their default memory caches. - Added
inSampleSizedownsampling so the decoded bitmap is close to theImageViewor composable size instead of the full image. - Enabled request deduplication so two grid cells showing the same URL share one decode.
- Checked the fix by scrolling the grid on a low-RAM test device with the Android Studio memory profiler open, and kept LeakCanary in debug builds to catch retained views.
Common mistakes
- Starting to draw the diagram before clarifying requirements. You will design for the wrong scale or miss the offline constraint. Spend the first five minutes writing down functional scope, non-functional limits, and offline needs. Interviewers watch this phase to judge whether you think before you draw.
- Using offset-based pagination. Offset shifts when rows are inserted or deleted, so the user sees duplicates or gaps. Use a cursor (opaque server token) and store
nextCursorinRoomorDataStoresoRemoteMediatorcan resume after a crash. - Treating the network as the source of truth. The UI must render instantly and work offline.
Roomis the source of truth; the network is a refresher. If the UI reads directly from aRetrofitcall, every screen needs a loading state and the app breaks the moment Wi-Fi drops. - Omitting idempotency keys on mutations. A retried POST (timeout, user double-tap, WorkManager retry) creates duplicate server records. Generate a UUID per mutation, store it in the outbox, and send it as the
Idempotency-Keyheader so the server deduplicates. - Designing the server instead of the client. The round is a mobile design round. Mention the server only as the interface contract (status codes, payload shape, sequence numbers). Spending ten minutes on sharding or database indexing signals that you are not thinking about the client.
- Trying to cover every trade-off in Phase 5. You have about ten minutes. Pick two or three areas (battery, memory, security, observability) and go deep with concrete APIs (
WorkManager, encrypted storage, Android vitals for ANRs and wake locks). A shallow list of six topics reads as surface-level.
Interview questions
Answer out loud first. Then reveal the answer and compare it at each depth.
“Walk me through how you would approach a mobile system design interview.”
“How do you decide between REST, GraphQL, and WebSocket for a mobile app?”
“What does 'local database as source of truth' mean in practice?”
“How do you handle the trade-off between battery and real-time updates?”
Quiz
In a mobile system design interview, what should you do in the first five minutes?
Why is cursor-based pagination preferred over offset-based pagination on the client?
What is the role of the outbox table in the client data layer?
What is the recommended way to schedule a periodic background sync on modern Android?
0 of 4 answered
Mini task
15-minute exercise: sketch a mobile design on paper
-
Pick a problem. Choose one of the later lessons in this module: news feed, chat, offline notes, image loading, or file upload. Write the problem name at the top of a blank page.
-
Phase 1 – Clarify (3 min). Write three functional requirements (what the user does), two non-functional constraints (latency, battery, memory, or offline), and one scale number (DAU or items per page). Do not look anything up; use your best estimate.
-
Phase 2 – Diagram (3 min). Draw five boxes: UI, ViewModel, Repository, Room, Network. Draw arrows for data flow. Add a sixth box for the sync coordinator (outbox +
RemoteMediator). Label which box is the source of truth. -
Phase 3 – API (3 min). Write two or three endpoint contracts. For each, note: method, path, request body, response shape, pagination style (cursor), and whether it needs an idempotency key. Choose REST, GraphQL, or WebSocket and write one sentence justifying the choice.
-
Phase 4 – Data layer (3 min). Write the
Roomentity fields. Write the outbox state machine as a list of states and transitions. Note what happens ononNetworkLost()andonNetworkRestored(). -
Phase 5 – Two deep dives (3 min). Pick two trade-off areas relevant to your problem (for chat: WebSocket backoff + message ordering; for feed: paging + prefetching; for image loading: LRU sizing + downsampling). For each, write the mechanism, the cost, and how you would verify it in a real codebase.
Done condition: You have a single page with all five phases filled in, a clear source-of-truth label, a cursor-paged API contract, an outbox state machine, and two deep-dive paragraphs. Time yourself; the total should be under 15 minutes.