Mobile system design cheat sheet

Revise mobile system design for Android interviews: Room, RemoteMediator, WorkManager, cursor pagination, outbox pattern, and idempotency keys.

Key ideas

  1. Room is the source of truth; the UI reads via Flow, and the network is only a cache refresher through RemoteMediator.
  2. Use cursor-based pagination (nextCursor: String?) for feeds and chat history; offset breaks when rows are inserted or deleted mid-scroll.
  3. Every non-idempotent mutation (typically a POST that creates something) needs a client-generated UUID as an Idempotency-Key header so retries cannot create duplicates.
  4. The outbox pattern stores pending mutations in a Room table with a state machine (PENDING → IN_FLIGHT → done/FAILED); WorkManager drains it in order.
  5. The five design phases are sequential and time-boxed; skipping Phase 1 (clarify) is the fastest way to lose the round.
  6. In Phase 5 pick two or three deep-dive areas and go deep; a shallow list of six reads as surface-level.
  7. For real-time chat, use a WebSocket with exponential backoff and jitter in the foreground; rely on FCM data messages in the background.
  8. Size the in-memory image LRU cache as a fraction of the app's memory budget (ActivityManager.getMemoryClass() or Runtime.getRuntime().maxMemory()), not a hard-coded value.
  9. On Android 14+ a foreground service needs a ForegroundInfo with dataSync type; on Android 15 that type is capped at 6 hours per 24 hours.
  10. Mention the server only as the interface contract (status codes, payload shape, sequence numbers); you are designing the client.

APIs at a glance

API or termUse it for
Room / RemoteMediatorClient data layer: Room is the source of truth; RemoteMediator fetches pages and upserts.
CursorPage<T> / nextCursorCursor-based pagination response; store nextCursor in a remote-keys table so APPEND resumes after a crash.
OutboxEntry / OutboxStateLocal Room table that queues pending mutations; state machine PENDING → IN_FLIGHT → FAILED.
WorkManager / CoroutineWorkerBackground sync and file upload with constraints, backoff, and process-death survival.
ExistingWorkPolicy.APPEND_OR_REPLACEEnqueue sync so a write during a running sync gets its own run; never use REPLACE for uploads.
ForegroundInfo + FOREGROUND_SERVICE_TYPE_DATA_SYNCLong uploads on Android 14+; declare dataSync on SystemForegroundService in the manifest.
LruCache with sizeOfIn-memory image cache sized in bytes via bitmap.allocationByteCount, not entry count.
Bitmap.Config.HARDWAREAPI 26+ hardware bitmaps save memory; pixels cannot be read or drawn on a software Canvas.
Idempotency-Key headerClient-generated UUID sent with every non-idempotent request (such as POST) so the server deduplicates retried requests.
serverSeqServer-assigned sequence number for total message ordering; never sort by local System.currentTimeMillis().
withTransactionWrap the notes-table write and the outbox insert in one atomic block so they stay consistent.
setBackoffCriteria(BackoffPolicy.EXPONENTIAL, 30, SECONDS)WorkManager retry policy; minimum 10 s, default 30 s; check runAttemptCount for a cap.

Snippets

Idempotent message-state advance (chat outbox)

enum class MsgState { SENDING, SENT, DELIVERED, READ }
 
data class ChatMessage(val localId: String, val text: String, val state: MsgState)
 
class MessageStore {
    private val confirmed = mutableListOf<ChatMessage>()
 
    fun advance(localId: String, next: MsgState) {
        val idx = confirmed.indexOfFirst { it.localId == localId }
        if (idx >= 0) {
            val current = confirmed[idx]
            // Guard: only advance, never regress
            if (current.state.ordinal < next.ordinal) {
                confirmed[idx] = current.copy(state = next)
            }
        }
    }
}

FeedRemoteMediator: refresh vs append in one transaction

@Entity(tableName = "posts")
data class PostEntity(@PrimaryKey val id: String, val title: String, val imageUrl: String, val position: Int)
 
@Entity(tableName = "feed_remote_key")
data class FeedRemoteKey(@PrimaryKey val id: Int = 0, val nextCursor: String?)
 
data class PostDto(val id: String, val title: String, val imageUrl: String)
data class CursorPage<T>(val items: List<T>, val nextCursor: String?)
 
interface FeedApi {
    @GET("feed")
    suspend fun feed(@Query("cursor") cursor: String?, @Query("limit") limit: Int): CursorPage<PostDto>
}
 
@Dao
interface FeedDao {
    @Query("SELECT * FROM feed_remote_key WHERE id = 0") suspend fun key(): FeedRemoteKey?
    @Upsert suspend fun saveKey(key: FeedRemoteKey)
    @Upsert suspend fun upsertAll(posts: List<PostEntity>)
    @Query("DELETE FROM posts") suspend fun clearPosts()
    @Query("SELECT COUNT(*) FROM posts") suspend fun count(): Int
}
 
@OptIn(ExperimentalPagingApi::class)
class FeedRemoteMediator(
    private val db: RoomDatabase,
    private val dao: FeedDao,
    private val api: FeedApi,
) : RemoteMediator<Int, PostEntity>() {
    override suspend fun load(loadType: LoadType, state: PagingState<Int, PostEntity>): MediatorResult {
        val cursor: String? = when (loadType) {
            LoadType.REFRESH -> null
            LoadType.PREPEND -> return MediatorResult.Success(endOfPaginationReached = true)
            LoadType.APPEND -> dao.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.count()
                dao.upsertAll(page.items.mapIndexed { i, d -> PostEntity(d.id, d.title, d.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)
        }
    }
}

Image loader: LRU cache + in-flight dedup

class ImageLoader(
    private val scope: CoroutineScope,
    private val fetchBytes: suspend (String) -> ByteArray,
) {
    private val memoryCache = object : LruCache<String, Bitmap>((Runtime.getRuntime().maxMemory() / 8).toInt()) {
        override fun sizeOf(key: String, value: Bitmap) = value.allocationByteCount
    }
    private val inFlight = mutableMapOf<String, Deferred<Bitmap>>() // only touched on the main thread
 
    @MainThread
    suspend fun load(url: String, reqWidth: Int, reqHeight: Int): Bitmap {
        val key = "$url@${reqWidth}x$reqHeight"
        memoryCache.get(key)?.let { return it }
        val deferred = inFlight.getOrPut(key) {
            scope.async(Dispatchers.IO) {
                decodeSampled(fetchBytes(url), reqWidth, reqHeight).also { memoryCache.put(key, it) }
            }
        }
        try { return deferred.await() }
        finally { if (deferred.isCompleted && inFlight[key] === deferred) inFlight.remove(key) }
    }
 
    private fun decodeSampled(bytes: ByteArray, reqWidth: Int, reqHeight: Int): Bitmap {
        val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
        BitmapFactory.decodeByteArray(bytes, 0, bytes.size, bounds)
        var sample = 1
        while (bounds.outWidth / (sample * 2) >= reqWidth && bounds.outHeight / (sample * 2) >= reqHeight) sample *= 2
        val options = BitmapFactory.Options().apply { inSampleSize = sample }
        return BitmapFactory.decodeByteArray(bytes, 0, bytes.size, options) ?: error("Cannot decode image")
    }
}

Resumable upload: ask the server for its offset

interface UploadApi {
    @HEAD suspend fun offset(@Url uploadUrl: String): Response<Void>
    @PATCH suspend fun patch(
        @Url uploadUrl: String,
        @Header("Upload-Offset") offset: Long,
        @Body chunk: RequestBody,
    ): Response<Unit>
}
 
@HiltWorker
class UploadWorker @AssistedInject constructor(
    @Assisted context: Context,
    @Assisted params: WorkerParameters,
    private val api: UploadApi,
) : CoroutineWorker(context, params) {
    override suspend fun doWork(): Result = try {
        upload()
    } catch (e: IOException) {
        Result.retry()
    }
 
    private suspend fun upload(): Result {
        val uploadUrl = inputData.getString("upload_url") ?: return Result.failure()
        val file = File(inputData.getString("file_path") ?: return Result.failure())
        val head = api.offset(uploadUrl)
        if (!head.isSuccessful) return if (head.code() >= 500) Result.retry() else Result.failure()
        var offset = head.headers()["Upload-Offset"]?.toLongOrNull() ?: return Result.retry()
        val total = file.length()
        val buffer = ByteArray(CHUNK_SIZE)
        RandomAccessFile(file, "r").use { raf ->
            while (offset < total) {
                val n = minOf(CHUNK_SIZE.toLong(), total - offset).toInt()
                raf.seek(offset); raf.readFully(buffer, 0, n)
                val resp = api.patch(uploadUrl, offset, buffer.toRequestBody(OFFSET_STREAM, 0, n))
                if (!resp.isSuccessful) return if (resp.code() >= 500) Result.retry() else Result.failure()
                offset = resp.headers()["Upload-Offset"]?.toLongOrNull() ?: return Result.retry()
            }
        }
        return Result.success()
    }
 
    private companion object {
        const val CHUNK_SIZE = 1024 * 1024
        val OFFSET_STREAM = "application/offset+octet-stream".toMediaType()
    }
}

Rules of thumb

  • Prefer cursor-based pagination (nextCursor) over offset/limit for any list that can change while the user scrolls.
  • Never read the UI from a raw Retrofit response; expose a Flow from Room so the screen renders instantly and works offline.
  • Never skip Phase 1 (clarify); spend the first five minutes writing functional scope, non-functional limits, and offline needs before drawing.
  • Prefer ExistingWorkPolicy.APPEND_OR_REPLACE for sync and KEEP for per-file uploads; never use REPLACE when a run may already be in flight.
  • Prefer two or three deep-dive topics in Phase 5 with concrete APIs over a shallow mention of six.
  • Never keep a WebSocket alive in a foreground service; close it in the background and rely on FCM data messages.

Gotchas

  • Using offset-based pagination for feeds or chat history. Rows inserted or deleted between page requests shift the offset, so the user sees duplicates or gaps. Store an opaque nextCursor token in Room or DataStore and resume from it.
  • Omitting the Idempotency-Key header on POST mutations. A retried request (timeout, double-tap, WorkManager retry) creates a duplicate server record. Generate a UUID per mutation, store it in the outbox row, and send it as the header so the server deduplicates.
  • Sorting chat messages by System.currentTimeMillis(). Device clocks drift and are user-set, so two devices disagree on order. Sort by the server-assigned serverSeq, the only total order.
  • Resuming a file upload from a local byte counter or from setProgress() data. A chunk can reach the server even though the response was lost, and setProgress() is not saved across attempts. Ask the server for its offset at the start of every run, or store the position in Room.
  • Setting message state unconditionally (e.g. DELIVERED after READ). A late ack downgrades the state and confuses the UI. Guard each transition: only advance to a later ordinal, never regress.
  • Calling File.readBytes() on a large file for upload. It allocates the entire file in memory at once and can throw OutOfMemoryError. Read one chunk at a time with RandomAccessFile.seek() and readFully() into a reused buffer.

Quick interview answers

Why is cursor-based pagination preferred over offset/limit for a news feed?

Offset shifts when new rows are inserted at the top, so the client sees duplicates or gaps on the next page. A cursor is an opaque server token that points to a stable position, so the server can resume from the exact spot regardless of inserts or deletes.

What is the outbox pattern and why is it needed?

The outbox is a local Room table that stores pending mutations with a state machine (PENDING → IN_FLIGHT → done/FAILED). It survives process death, and a WorkManager worker drains it in creation order when the network returns, so no local write is lost.

How do you handle a WebSocket reconnect for a chat app?

OkHttp's WebSocket has no built-in reconnect, so wrap it in a connection manager that calls newWebSocket again after onFailure or onClosed, using exponential backoff with jitter to avoid a thundering herd. In the background, close the socket and rely on FCM data messages, which are best-effort.

Why is Room the source of truth instead of the network?

The UI must render instantly and work offline, so it reads from Room via Flow and RemoteMediator upserts pages into the database. If the UI reads directly from a Retrofit call, every screen needs a loading state and the app breaks the moment Wi-Fi drops.

How do you make a file upload resumable across process death?

WorkManager stores the request and its input Data in its own database and reruns the worker after a crash or Result.retry(). At the start of each run, ask the server for its current offset via a HEAD request, then read the file with RandomAccessFile.seek() and readFully() into a reused buffer.

What should you do in Phase 5 of the design interview?

Pick two or three deep-dive areas (battery, memory, security, observability) and go deep with concrete APIs such as WorkManager, encrypted storage, or Android vitals for ANRs and wake locks. Interviewers reward a thorough trade-off analysis on two topics over a shallow mention of six.

Go deeper