Mobile Design Rounds
Build guideAndroidiOS14 min read

Build it: a chat app on Android and iOS

Last reviewed . Drafted with AI assistance. Checked against official documentation where noted (how this is checked). Part of: Design a chat app (Android and iOS): outbox, idempotent sends and sync · Offline and sync · The five-step method.

This is the implementation material behind the chat app interview case. It covers:

  • schema, REST and events
  • the send worker and the receive path
  • history, receipts, platform limits and the iOS version

None of it belongs in the 45 minutes. I draw it only if asked. The snippets use Room 3.0 (androidx.room3, current stable 3.0.3, from the Room guide and the 2.x to 3.0 migration guide). Room 3 needs KSP (no KAPT) and a SQLiteDriver on the builder. In Room 3 the Paging query in section 6 also needs @DaoReturnTypeConverters(PagingSourceDaoReturnTypeConverter::class) on the DAO (artifact room3-paging). I did not compile these snippets against Room 3. The architecture is the same in Room 2.x (androidx.room).

1. Local schema (Room)

@Entity(
    tableName = "messages",
    indices = [
        Index(value = ["clientId"], unique = true),
        Index(value = ["conversationId", "seq"]),
    ],
)
data class MessageEntity(
    @PrimaryKey(autoGenerate = true) val localId: Long = 0,
    val clientId: String,          // UUID generated on device; the idempotency key
    val serverId: String? = null,  // null until acked
    val conversationId: String,
    val senderId: String,
    val body: String,
    val seq: Long? = null,         // per-conversation sequence assigned by server; gaps are allowed
    val createdAt: Long,           // device clock; used only for ordering pending messages
    val status: Status,
) {
    enum class Status { PENDING, SENT, DELIVERED, READ, FAILED }
}
  • clientId is how the app removes duplicates. The same message may arrive by WebSocket, by an FCM-triggered sync, and in the REST response to our own send. The unique index stops a second row from being inserted. The DAO (the class that holds the database queries) below turns the collision into an update of the first row. All three copies become one row.
  • seq comes from the server and gives one fixed order inside a conversation. It does not have to be contiguous (without gaps). A cursor sync repairs a gap, so a gap is not an error (the live ticker uses a stricter seq that detects gaps). Never order by device timestamps alone, because device clocks are not exact.
  • I do not use Room's @Upsert (insert, or update if the row exists) for this. It falls back to an update only when the primary key (localId) matches. An incoming copy has no localId. So a clientId collision would update nothing, and the ack data would be lost. Instead I insert with IGNORE. If the insert was ignored, I update by clientId:
@Dao interface MsgDao {
    @Insert(onConflict = OnConflictStrategy.IGNORE) suspend fun insertIgnore(m: MessageEntity): Long
    // the server copy fills in serverId and seq; a PENDING row becomes the server's status, any later status stays
    @Query("""UPDATE messages SET serverId = :serverId, seq = :seq,
        status = CASE WHEN status = 'PENDING' THEN :status ELSE status END
        WHERE clientId = :clientId""")
    suspend fun applyServerCopy(clientId: String, serverId: String, seq: Long, status: String)

    @Transaction suspend fun upsertByClientId(m: MessageEntity) {
        if (insertIgnore(m) == -1L) applyServerCopy(m.clientId, m.serverId!!, m.seq!!, m.status.name)
    }
}
  • In this design, the sync cursor is simply the last seq the device has seen. I call it after_seq here. Other cases use an opaque cursor (a value the app does not read) for the same idea.

2. REST

POST /v1/conversations/{id}/messages      body: { clientId, body }
     → 200 { serverId, seq, createdAt }   (idempotent on clientId)
GET  /v1/conversations/{id}/messages?after_seq=123&limit=50
GET  /v1/sync?since=<cursor>              (conversation list changes; used on cold start)

How to read the snippet. Each block is one call: the method and path, then the headers, then the JSON body (the data the app sends) in braces. A line that starts with → is a reply from the server. Text after // is a comment. These are sketches for this guide, not a vendor API.

CallWhat it is forWhen the app makes it
POST /v1/conversations/{id}/messagesSend a message. The server answers with its own serverId, a seq (the order number) and a time.When the user taps send, from a background worker. The clientId is made once and reused on every retry, so a lost reply cannot create a second message.
GET …/messages?after_seq=…Get messages after a known seq.When a conversation opens and after a reconnect, to fill gaps.
GET /v1/sync?since=…Which conversations changed since the saved cursor.On a cold start, before the socket is open.

3. WebSocket events

server → client:  message.new, message.status, conversation.updated
client → server:  ack(seq), typing   (send itself goes via REST/Worker for retry guarantees)

ack(seq) tells the server how far this device has received events, so it can stop holding older ones for it. It is not a read receipt.

I send through REST plus WorkManager, not the socket, on purpose. The worker (the class that WorkManager runs) gives retries, constraints (rules such as needing a network) and survival across process death without extra work.

4. The send worker

I write to the local database first and send later, so for a moment two versions of the truth exist. The server's seq decides which message comes first. A last-write-wins rule (the newest write replaces the older one) does not decide it. The send has to survive the app being stopped, so it runs in WorkManager, not in viewModelScope.

  1. The user taps send. The ViewModel calls repository.send(...). It inserts a row with status = PENDING and a new clientId in one Room transaction (all steps succeed or none do). The screen shows the row at once, because it observes Room.
  2. The repository enqueues (adds to the work queue) a unique SendMessageWorker per message, or per conversation to keep the order.
  3. The worker calls repository.sendPending(clientId). This reads the pending row and calls POST /messages.
  4. On success, the worker updates the row with serverId, seq and status = SENT.
  5. On a temporary failure (IOException, 5xx), the worker returns Result.retry(), and WorkManager applies backoff (a longer wait after each failure). After 8 attempts (my own limit), the worker gives up and marks the row FAILED. Then one message that always gets a 5xx cannot hold up the rest of the conversation's chain.
  6. On a permanent failure, the worker marks the row FAILED and the screen shows "Tap to retry". My rule across these cases: IOException, 408, 429 and 5xx are temporary. Any other 4xx is permanent, except 401: refresh the token once, then retry. To honour Retry-After, I would have to enqueue the work again with an initial delay, because the backoff policy is fixed. The worker below does not do that.

The define-work page describes no jitter in WorkManager's backoff, so I assume none. That is fine for the sends of one device. Jitter (a random change in each delay) matters for socket reconnects (section 5). There, millions of clients can retry at once.

With the 10 s base, the delays double (10, 20, 40 ... 1,280 s). The worker below checks runAttemptCount >= 8 at the start of a run. This gives, as my worked example:

  • Eight sends over about 21 minutes.
  • A ninth run, which marks the row FAILED, about 42 minutes after the first failure.
  • No effect from the cap. The androidx source caps backoff at 5 hours (the define-work page does not state a cap).

This is my arithmetic from the library's documented defaults and its source. It is not a measurement. Real delays differ by several seconds.

@HiltWorker
class SendMessageWorker @AssistedInject constructor(
    @Assisted ctx: Context, @Assisted params: WorkerParameters,
    private val repository: ChatRepository,   // workers go through the repository, never the DAO or API
): CoroutineWorker(ctx, params) {

    override suspend fun doWork(): Result {
        val id = inputData.getString("clientId") ?: return Result.failure()
        if (runAttemptCount >= 8) { repository.markFailed(id); return Result.success() }   // stop retrying; the row shows "Tap to retry"
        return when (repository.sendPending(id)) {
            SendOutcome.Done, SendOutcome.NothingToSend -> Result.success()
            SendOutcome.Retry -> Result.retry()   // IOException, 5xx, 429
            // permanent 4xx: the row is already FAILED in Room, so end this work as success().
            // (With APPEND a failed parent would cancel later sends; APPEND_OR_REPLACE avoids that, and success() keeps WorkInfo clean.)
            SendOutcome.PermanentFailure -> Result.success()
        }
    }
}

// enqueue
WorkManager.getInstance(ctx).enqueueUniqueWork(
    "send-${conversationId}",            // one chain per conversation keeps order
    ExistingWorkPolicy.APPEND_OR_REPLACE,
    OneTimeWorkRequestBuilder<SendMessageWorker>()
        .setInputData(workDataOf("clientId" to clientId))
        .setConstraints(
            Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build()
        )
        .setBackoffCriteria(BackoffPolicy.EXPONENTIAL, 10, TimeUnit.SECONDS)   // 10 s is the minimum; the default is 30 s
        .build(),
)

Why this is safe against duplicates: if the request reaches the server but the response is lost, the retry sends the same clientId. The server returns the original serverId and seq. It does not create a second message.

This is idempotency (doing it twice has the same result as doing it once) in practice. The booking app uses the same pattern for the payment. The staff guide walks through this exact lost-acknowledgement case at staff depth.

Tap to retry. A manual retry sends the same clientId, because the first try may have reached the server. Only a message that the server rejected for its content gets a new ID. On logout, keep or clear the outbox for that account. Never send it with the next user's token.

Ordering note: pending messages have no seq yet. The screen shows confirmed messages by seq, then pending ones by createdAt at the bottom. When an ack gives a row its seq, the row moves to its place.

5. The receive path in detail

The socket and FCM only tell the device that something changed. The data always comes from a cursor fetch.

Foreground (the app is on screen): hold one OkHttp WebSocket while the app is visible (tie it to the process lifecycle with ProcessLifecycleOwner). Each incoming message.new is upserted (inserted, or updated if it exists) into Room by clientId. The screen updates by itself.

Background: do not keep the socket open. Doze (the deep-sleep mode of an idle phone) suspends network access. App Standby delays background network activity (Doze and App Standby). So an idle socket stops being useful. A foreground service kept only to hold the socket costs battery. It may also break Play rules for foreground services, so check the current policy. Instead:

  1. The server sends a high-priority FCM data message that contains only a hint (conversationId, maybe the seq), not the full content.
  2. FirebaseMessagingService.onMessageReceived enqueues a SyncWorker as expedited work (short, important work that the system runs soon). Expedited work has a quota (a usage limit). I set RUN_AS_NON_EXPEDITED_WORK_REQUEST, so ordinary work runs when the quota is used up. The worker must implement getForegroundInfo(), or setExpedited can crash on devices below Android 12 (WorkManager docs). Enqueue it directly from onMessageReceived, because FCM's exemption for expedited work after a high-priority message is brief.
  3. The worker calls GET /messages?after_seq=<last seq in Room>, upserts the results, then posts a notification. On a cold start (the app starts fresh), I call /sync first for the conversation list, then after_seq for each open thread.

A hint plus a sync is the pattern, for the reasons in the push SDK case. That case goes deeper on the push side.

Why not put the message in the push?

  • FCM caps a payload at 4 KB (message types).
  • FCM can collapse or drop queued messages (delivery) and documents no ordering.
  • A sync by cursor repairs itself. If you missed three pushes, one sync still fetches all three.

One catch: if high-priority FCM messages repeatedly do not produce a visible notification, FCM may downgrade them to normal priority. So post the notification from the worker.

Reconnect: when the socket drops, reconnect with exponential backoff plus jitter (for example 1 s, 2 s, 4 s up to about 30 s, each randomized by ±50%). Always run a cursor sync (after_seq) after a reconnect to fill gaps. Jitter matters: without it, a server restart makes millions of clients reconnect at the same moment.

6. Reading history efficiently

Use Paging 3 (Android's library for loading lists in pages) with a Room PagingSource. Add a RemoteMediator that fetches older pages from the API when the user scrolls past the cached range. The conversation list is also a Room query. It shows at once from cache on cold start and refreshes in the background.

The snippet exposes the Room entity to keep it short. In a larger app, map it to a UI model in the repository.

@Query("SELECT * FROM messages WHERE conversationId = :id ORDER BY COALESCE(seq, 9223372036854775807), createdAt")
fun pagingSource(id: String): PagingSource<Int, MessageEntity>

7. Delivery and read receipts

  • Server to sender: message.status events (DELIVERED, READ) update the row's status. Statuses only move forward. Ignore a late event that would move a status back.
  • Receiver to server: batch read receipts (for example, send the highest seq read, not one call per message) and debounce them (wait a short time, then send once). If READ arrives before DELIVERED, keep READ. The forward-only rule makes the late DELIVERED change nothing.
  • Groups: store counts or a per-user map on the server. The client mostly needs "delivered to all" or "read by N".

8. Battery, data and platform limits

The limits that shaped the design, side by side. Each fact is already used elsewhere in this guide or on the interview page.

LimitAndroidiOSSo the design changes by
Background socketDoze suspends network access and App Standby defers background network activity; a foreground service just to hold it costs batteryNo socket in the background; close it when the app leaves the foregroundPush becomes a hint and a cursor sync fills the gap
Waking the app for a messageHigh-priority FCM data message; expedited work has a quota, so fall back to ordinary workSilent push is low priority, not guaranteed, throttled (Apple advises no more than two or three an hour) and discarded after a force-quit; an alert push with mutable-content: 1 and a Notification Service Extension (about 30 seconds to modify the payload) is what I use for chatiOS chat sends a visible push; both platforms sync by cursor
Notification after a hintFCM may downgrade high-priority messages that do not produce a visible notificationIf time runs out, the expiry callback must return what it has; if the handler is never called the system shows the original content. I return generic textOn Android the worker posts the notification, not the push
Catch-up work laterWorkManager; backoff default 30 s, minimum 10 sBGAppRefreshTask and BGProcessingTask are system-scheduled, not guaranteedNever promise a delivery time
Durable pending sendsPENDING rows plus WorkManager unique work survive process deathYour own outbox table; nothing runs after a force-quit until the next launchiOS pending messages may wait, and I say so
  • No polling loops. Use the socket only in the foreground. Otherwise use FCM plus sync.
  • Limit sync work to times with a network connection. For large media, also require an unmetered network or a battery that is not low.
  • Respect Android's background execution limits. I avoid foreground services here. If you need one, check the type and timeout rules for your target SDK.
  • Compress the payload (gzip), and fetch changes by cursor instead of full lists.

9. How to build a chat app on iOS (Swift)

The design carries over: local database as the source of truth, an outbox, a client-generated clientId for idempotency, server seq for ordering, and cursor-based sync. Only the platform tools change.

ConcernAndroidiOS
Local DBRoomSwiftData or Core Data (or GRDB)
Reactive UIFlow + Compose@Query (SwiftData) or @FetchRequest (Core Data) with SwiftUI; NSFetchedResultsController with UIKit
Outbox (durable pending sends)PENDING rows plus WorkManager unique workYour own outbox table and sender; there is no WorkManager equivalent
Foreground socketOkHttp WebSocketURLSessionWebSocketTask
Background wakeFCM high-priority data messageAPNs silent push (best effort), or an alert push with a Notification Service Extension
Background syncExpedited workerBGAppRefreshTask / BGProcessingTask (system-scheduled, not guaranteed)
PaginationPaging 3 + RemoteMediatorCursor-based loading with a fetch limit; no official paging library

What really changes:

  • The outbox is a table that you drain yourself (send every waiting message). Start a drain on send, on app foreground, on network recovery (NWPathMonitor), and on push.

- Those triggers overlap. An actor (a Swift type that guards its own data) lets another call start whenever it waits at an await. A second drain would send every message twice. - The sketch keeps one drain running and a flag that makes it do one more pass. A message saved during a drain then does not wait for the next trigger. - If the user force-quits the app, nothing runs in the background until the next launch, so pending messages may wait. Say so in the interview. It is a weaker guarantee than WorkManager gives.

  • Silent pushes are unreliable. Apple documents them as low priority, not guaranteed, and throttled (it advises no more than two or three per hour). The system discards a held one if the app is force-quit.

- For chat, send a visible alert push with mutable-content: 1. Let a Notification Service Extension (code iOS runs to change a push before it shows) fetch or decrypt the message. It must finish within its time limit, and fall back to generic text. - Apple's guide says the limit is about 30 seconds. When time is nearly up, the expiry callback must hand back whatever it has. The system shows the original content only if the handler is never called. - The rule "the push is a hint, and sync fills the gap" still applies.

  • No socket in the background. Close the WebSocket when the app leaves the foreground. Use beginBackgroundTask to finish a send in progress.
  • Dedupe is the same. A unique clientId constraint turns duplicate inserts into one row.
  • Retries need a count. Android has WorkManager backoff. On iOS, keep an attemptCount on the row. After 8 failed tries, mark it FAILED so it cannot block the queue.
  • Send from a file when you can. A background URLSession upload task must read its body from a file. The system can finish it while the app is suspended. A force-quit cancels it, so the next launch drains the outbox again.
  • Push headers. An alert push uses apns-push-type: alert and apns-priority: 10. A silent push uses apns-push-type: background, content-available: 1 and apns-priority: 5.

- In SwiftData, @Attribute(.unique) upserts on save for primitive-typed properties, per WWDC23 session 10195. - Adding it to an existing store needs a custom migration stage that removes duplicates first. - I would check CloudKit support before relying on it. Test on your target OS.

// Sketch: outbox drain on iOS (trigger it from send, foreground, reachability, push)
actor Outbox {
    private var draining = false, rerun = false     // reentrancy guard: triggers overlap
    // `store` is a @ModelActor (or a GRDB/Core Data actor); do not share a ModelContext across isolation domains.
    func drain() async {
        if draining { rerun = true; return }        // a trigger during a drain asks for one more pass
        draining = true
        defer { draining = false }
        repeat {
            rerun = false
            for msg in await store.pending() {      // ordered by createdAt
                do {
                    let ack = try await api.send(msg.conversationId, clientId: msg.clientId, body: msg.body)
                    await store.markSent(msg.clientId, serverId: ack.serverId, seq: ack.seq)
                } catch where error.isTransient {
                    return                          // keep order; retry on the next trigger
                } catch {
                    await store.markFailed(msg.clientId)
                }
            }
        } while rerun
    }
}

10. More practice prompts

  1. How do you test this? (Fake API plus in-memory Room. Test the worker with TestListenableWorkerBuilder. Simulate duplicate and out-of-order events.)
  2. How would you tell a broken socket from a quiet one? (A heartbeat ping, which is a small message sent on a timer, a read timeout, and a token refresh before the long-lived connection expires.)

Further reading (official docs)

Words on this page (32)
Acknowledgement
A short reply that says the server got a message. If this reply is lost, the app does not know, so it sends the message again.
Actor
A Swift type that runs one task at a time. This keeps its data safe when many tasks use it.
APNs
Apple Push Notification service, the push service from Apple. Every push to an iPhone goes through it.
BGProcessingTask
A kind of iOS background task for long work. The system decides when it runs, often when the phone is idle.
Cold start
A start of the app when it was not running. It is slower than a start from the background.
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.
DAO
A class that holds the database queries. DAO means data access object.
Debounce
To wait a short time and then act once. For example, send one request after the user stops typing.
Dedupe
To keep only one copy of the same item. For example, a message that arrives twice is stored once.
Doze
The deep-sleep mode of an idle Android phone. It pauses network access and delays background work.
Exponential backoff
Waiting longer after each failure. For example, wait 1 second, then 2, then 4.
FCM
Firebase Cloud Messaging, the push service from Google. On iOS it passes the push to APNs.
Foreground service
An Android service that shows a notification while it works. The system is less likely to stop it.
Heartbeat
A small message that is sent on a timer. If the messages stop, the app knows the connection is broken.
Idempotent
Doing it twice has the same result as doing it once. This makes a retry safe.
Jitter
A random change in each wait time. It stops many apps from trying again at the same moment.
Outbox
A saved list of changes that the server has not confirmed yet. The app sends them later, even after it restarts.
Paging
Loading a long list in small parts. The app asks for one page at a time.
Polling
Asking the server again and again if there is news. It costs battery and data.
Process death
The system ends the process of your app to free memory. Anything that is only in memory is lost.
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.
Room
Android's library for the database on the phone. You use a DAO to read and write the data.
SDK
Software development kit. Code that other developers add to their own apps.
Sequence number
A number from the server that only goes up in each conversation. It sets the order. Here a gap is allowed, because a sync by cursor fills it.
Silent push
A push with no visible alert. The system can delay it or drop it, so treat it only as a hint.
Source of truth
The one copy of the data that the app trusts. In these cases it is the database on the phone, and the screen only reads it.
SwiftData
Apple's library for saving data on an iPhone. It has the same role as Room on Android.
Unique index
A database rule that refuses a repeated value. It stops a second copy of a row from being saved.
Upsert
A database step that inserts a row, or updates it if it already exists.
ViewModel
A class that holds the state of one screen. It survives a screen rotation.
WebSocket
A two-way connection that stays open. The server can send data to the app at any time.
WorkManager
Android's tool for background work that must run later. The work survives when the app closes or the phone restarts.

Read the whole glossary

What I checked and what I did not
  • I checked the Android pages for WorkManager (defaults, backoff, unique work, expedited work), Doze, FCM priority and payload limits, and Paging.
  • I checked the Apple pages for background updates (silent push limits, force-quit) and for modifying notifications (mutable content, about 30 seconds).
  • The SwiftData unique-attribute upsert comes from WWDC23 session 10195. Test it on your target OS, and check CloudKit support.
  • The Kotlin snippets compiled in a test project. The Room DAO was accepted by Room's compiler, but I did not run it against a real database.
  • I type-checked the Swift outbox and ran the same logic once in a small test program.
  • The 5-hour backoff cap comes from the androidx source, not the docs page. The no-jitter note and the plus or minus 50 percent reconnect jitter are my assumptions.
  • I did not verify NWPathMonitor behavior or how often BGAppRefreshTask really runs.
  • No iOS engineer has reviewed section 9 yet. Treat it as unreviewed.

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.