Design a chat messaging app
The question
Design a chat messaging app for Android. Walk me through how the client handles real-time delivery, offline sending, message history, and notifications. Assume one-to-one and small-group conversations.
Clarify before you design:
- Is this one-to-one only, or do we need group chats with read receipts per member?
- What is the expected message volume per user per day, and do we need media (images, voice notes) or text-only for this round?
- Should I assume the backend already exists, or do I define the API contract the client needs?
- Is end-to-end encryption a hard requirement, or is it a discussion point for later?
- What is the minimum Android version we target, and do we need to support process-death recovery mid-conversation?
- Do we need to support multiple accounts on one device, or is a single account sufficient?
- What is the acceptable latency for a 'delivered' tick versus a 'read' tick?
Requirements
Functional
- Send a text message and show it in the conversation immediately, even when offline.
- Receive new messages in real time while the app is in the foreground (WebSocket) and while it is in the background (FCM high-priority data messages).
- Track four message states per message: sending, sent, delivered, read. Update the UI as each state arrives. A send that keeps failing is shown as failed with "tap to retry".
- Load conversation history with pagination (Room + Paging 3) so the user can scroll back through thousands of messages.
- Show one notification per conversation with
MessagingStyle, updated as more messages arrive while the app is backgrounded. - Retry unsent messages from the outbox when connectivity returns, using client-generated IDs so the server can deduplicate.
Non-functional
- The app must not hold a long-lived background socket. FCM handles background delivery; the WebSocket lives only while the app is in the foreground.
- Battery: no polling, no
AlarmManagerwake-ups for sync. Rely on FCM for background delivery andWorkManagerfor deferrable work such as draining the outbox. - Memory: conversation history uses Paging 3 so only loaded pages are in memory. No full-list loading.
- Latency: in the foreground a message should appear to the other user almost instantly; agree the target with the interviewer. Background delivery depends on FCM, which is best-effort and can be delayed.
- Privacy: message bodies can be encrypted at rest, for example with SQLCipher plugged into Room through its
SupportSQLiteOpenHelper.Factory. E2E encryption is a discussion point, not a hard requirement for this round. - Process-death safety: all in-flight state (outbox, auth token, last-seen server sequence) is persisted so a killed process resumes cleanly.
Out of scope
- Server-side architecture: sharding, fan-out, message broker internals. We only define the API contract the client calls.
- Media upload pipeline (image compression, resumable chunked upload). Mention it exists but do not design it here.
- Multi-account switching and per-account credential storage.
High-level architecture
The client has four layers, top to bottom.
UI layer. Compose screens for the conversation list and the message thread. Each screen collects a StateFlow<UiState> from its ViewModel with collectAsStateWithLifecycle. The thread screen collects a separate Flow<PagingData> with collectAsLazyPagingItems (PagingData is not put inside UiState). No UI code touches the network or Room directly.
Domain layer. Use-cases such as SendMessage, LoadConversation, MarkAsRead. They own the message-state machine: Sending -> Sent -> Delivered -> Read. The outbox is a domain concept: messages that have not yet received a server ack.
Data layer. A Repository that combines two sources. Local: a Room database with a messages table, a conversations table, and the outbox (a pending flag or a separate table). The DAO returns a PagingSource for history. Remote: a Retrofit (or Ktor) client for REST calls (send, fetch history, ack) and an OkHttp WebSocket (OkHttpClient.newWebSocket(request, listener) with a WebSocketListener) for the foreground real-time channel. A FirebaseMessagingService receives background pushes and writes them into Room.
Connection ownership. A single ConnectionManager, an application-scoped singleton (not a ViewModel), owns the WebSocket. It observes ProcessLifecycleOwner: it connects on ON_START (the app came to the foreground) and closes the socket on ON_STOP, perhaps after a short grace period. In the background, FCM takes over. It also owns reconnect with exponential backoff and jitter (OkHttp does not reconnect by itself), the client pingInterval that detects dead connections, and auth token refresh.
State ownership. Room is the single source of truth for message state on the device. The WebSocket, REST sync and FCM paths all write into Room. The UI reads only from Room (via Paging or a Flow query). This avoids dual-state bugs where the UI shows a message the database does not have.
Threading. Retrofit suspend calls and Room suspend/Flow queries are already main-safe, so they need no withContext. OkHttp calls WebSocketListener methods on its own threads; the listener hands frames to a coroutine scope owned by the ConnectionManager. CPU work such as parsing a large sync batch runs on an injected Dispatchers.Default. Structured concurrency ties child coroutines to the owning ViewModel or ConnectionManager.
| Component | Responsibility |
|---|---|
| ConnectionManager | Application-scoped. Opens the WebSocket on process ON_START, closes it on ON_STOP. Reconnects with exponential backoff and jitter, refreshes the token, and on every connect asks for everything after the last stored serverSeq. Emits a ConnectionState StateFlow. |
| MessageRepository | Single entry point for messages. Writes to Room first (optimistic), then sends. Reads come from Room. Enqueues the outbox drain. |
| OutboxProcessor | While the socket is up, resends pending rows on reconnect. As a backstop, unique WorkManager work with a NetworkType.CONNECTED constraint sends pending rows over REST, so sends survive the app leaving the foreground or being killed. On server ack, moves the row from SENDING to SENT. |
| FcmMessageHandler | A FirebaseMessagingService. onMessageReceived gets a data message, stores the message (or fetches what is missing after the last serverSeq), and posts or updates the conversation's notification. It must finish quickly; longer work goes to WorkManager. onNewToken sends the new token to the server. |
| MessageDao | Returns PagingSource<Int, MessageEntity> for a conversation, ordered by server sequence with pending messages last. Room invalidates it when the table changes. |
| MessageStateReducer | A pure function that takes a message state and an incoming event (SentAck, DeliveredAck, ReadAck) and returns the next state. States only move forward, so a late DeliveredAck after ReadAck is ignored. |
| NotificationBuilder | Builds one notification per conversation with NotificationCompat.MessagingStyle, linked to a conversation shortcut. Uses setGroup() plus a summary to bundle several conversations. Checks POST_NOTIFICATIONS on Android 13+. |
Data model and API
import androidx.room.Entity
import androidx.room.Index
import androidx.room.PrimaryKey
import kotlinx.serialization.Serializable
@Entity(
tableName = "messages",
indices = [Index(value = ["conversationId", "serverSeq"])]
)
data class MessageEntity(
@PrimaryKey val clientId: String, // UUID generated on the sender's device
val conversationId: String,
val senderId: String,
val body: String,
val localSeq: Long, // local counter, orders our own unsent messages
val serverSeq: Long?, // assigned by server, null until ack
val state: MessageState, // Room stores enums by name
val sentAt: Long, // device time, for display only
val attemptCount: Int = 0
)
enum class MessageState { SENDING, SENT, DELIVERED, READ, FAILED }
@Entity(tableName = "conversations")
data class ConversationEntity(
@PrimaryKey val id: String,
val participantIds: String, // JSON array, converted with a TypeConverter in practice
val lastMessageSeq: Long,
val lastMessagePreview: String,
val unreadCount: Int
)
@Serializable
data class SendMessageDto(
val clientId: String, // idempotency key
val conversationId: String,
val body: String
)
@Serializable
data class MessageAckDto(
val clientId: String,
val serverSeq: Long,
val state: String // "SENT", "DELIVERED", "READ"
)API the client needs: POST /messages (idempotent on clientId), GET /conversations/{id}/messages?before=<serverSeq>&limit=50 for older history, GET /sync?after=<serverSeq> to catch up after a push or reconnect, and WebSocket frames for new messages and state changes (sent, delivered, read).
Deep dives
Foreground WebSocket vs Background FCM
The interviewer will ask: "How does the client get a message when the app is not visible?"
Foreground path. While the app is in the foreground, the ConnectionManager holds an open WebSocket. Incoming frames are parsed and written to Room, and the Room-backed PagingSource is invalidated so the new row shows up. The socket follows the app's process lifecycle (ProcessLifecycleOwner): connect on ON_START, close on ON_STOP. No Service is started for the socket.
Background path. The socket is closed. The server sends an FCM data message with high priority. FirebaseMessagingService.onMessageReceived runs, the handler writes the message into Room (or fetches everything after the last serverSeq), and NotificationBuilder posts or updates the notification. The user taps it, the conversation opens, and Paging loads the message from Room.
Why a data message, not a notification message? A notification message sent to a backgrounded app is shown by the system tray without running your code, so Room is not updated and you cannot build a MessagingStyle notification. A data message always reaches onMessageReceived (unless the user force-stopped the app).
Why high priority only with a visible notification? High priority lets the message wake a dozing device and gives the app a short window to run. FCM expects high-priority messages to lead to a notification the user sees; if they often do not (for example, the user muted the chat or denied POST_NOTIFICATIONS on Android 13+), FCM may deprioritize the app's messages. Send read receipts and other silent updates as normal priority; those can wait for Doze maintenance windows or the next app open.
Why not a background socket? Since Android 8 a background service is stopped soon after the app leaves the foreground, Doze cuts network access, and the system can freeze or kill a cached process at any time. A foreground service would keep a permanent notification, no foreground service type is meant for holding a chat socket, and on Android 15 dataSync services are limited to 6 hours per 24 hours. FCM shares one system connection across apps, so it is the battery-friendly path. The trade-off: FCM is best-effort. Messages can be delayed, collapsed or dropped.
Reconnect and catch-up. When the app returns to the foreground, ConnectionManager opens a new WebSocket and asks for everything after the last stored serverSeq. Some of those messages may already be in Room from FCM. That is fine: inserts are upserts keyed by clientId, so writing the same message twice leaves one row. Treat the push as a hint and the sync as the truth.
Outbox and Idempotent Retries
The candidate must explain what happens when the user sends a message with no network.
Write path. The SendMessage use-case generates a clientId (a random UUID) on the device. It inserts a MessageEntity with state = SENDING and serverSeq = null into Room before any network call. The UI shows the message immediately with a "sending" indicator. The row is the outbox entry (a pending flag on the message, or a row in a separate outbox table).
Retry. If the socket is connected, the message is sent at once. The same write also enqueues unique work, for example enqueueUniqueWork("outbox", ExistingWorkPolicy.APPEND_OR_REPLACE, request) with a NetworkType.CONNECTED constraint and exponential backoff. The worker sends pending rows over REST in localSeq order. Each send includes the clientId as an idempotency key. The server remembers recent clientIds; if the same one arrives twice, it returns the original serverSeq instead of creating a duplicate.
State transition. When the ack arrives with a serverSeq, the reducer moves the row from SENDING to SENT and stores the serverSeq. The UI updates through the Room query. A message sent by both the socket and the worker is stored once on the server and once in Room.
Failure. Transient errors (no network, timeouts, 5xx) return Result.retry(), and WorkManager applies the backoff, which survives process death. After a few attempts, or on a permanent error such as 4xx, the row moves to FAILED and the user sees "tap to retry". Keep in mind a worker run has a time limit (around 10 minutes) and Doze defers it, so it is a backstop, not the real-time path.
Local Ordering vs Server Ordering
This is the question that separates mid from senior answers.
Local ordering. Each device gives its own new messages a localSeq from a local counter (not System.currentTimeMillis(), because the wall clock can jump). This gives the UI a stable order the instant a message is created, before any server round-trip.
Server ordering. The server assigns a serverSeq per conversation when it accepts the message. This is the canonical order for all participants. Device clocks differ and local counters on different devices mean nothing to each other, so never order a shared conversation by device time.
The rule. Sort by serverSeq when it is set. Messages still waiting for an ack (serverSeq is null) go after all acked messages, in localSeq order. When the ack arrives, the message takes its server position. Usually that is still the last position; if someone else's message was accepted first, ours moves up by one.
UI implication. The list should not jump. Use a stable key (clientId) for each item and Modifier.animateItem() in the LazyColumn, so a small move is animated instead of a flash. Room invalidates the PagingSource when the state changes and Paging diffs the result.
Discussion point. End-to-end encryption does not change ordering, because the server still assigns serverSeq from metadata it can see. It does change other things: the push payload must be decrypted on the device (another reason for data messages), the server cannot search message text, and keys must be stored and backed up safely. Mention it as a layer, not a design for this round.
Notification Grouping and MessagingStyle
The interviewer asks: "What does the user see when three messages arrive from the same chat while the app is backgrounded?"
One notification per conversation. Use a notification ID derived from the conversationId. Each new message updates the same notification: rebuild the NotificationCompat.MessagingStyle(me) with the recent messages (addMessage(text, timestamp, person)) and post it again. For a group chat, call setConversationTitle() and setGroupConversation(true). The user sees a chat-style view with sender names and avatars from Person.
Several conversations. Give each conversation's notification the same setGroup(key) and post a summary notification with setGroupSummary(true), so the system can bundle them on Android 7.0+.
Conversation features (Android 11+). Link the notification to a long-lived conversation shortcut (ShortcutInfoCompat with setLongLived(true), pushed with ShortcutManagerCompat.pushDynamicShortcut(), and setShortcutId() on the builder). Then it shows in the conversation section of the shade, and the user can mark the chat as priority or give it its own settings. Bubbles also need this shortcut.
Channel and permission. A single "Messages" channel is enough, because users can already set per-conversation options. Create it with an initial importance (high, for heads-up); after that the user owns it. On Android 13+ request POST_NOTIFICATIONS at a sensible moment; without it notify() silently posts nothing.
Tapping. The PendingIntent (with FLAG_IMMUTABLE) opens the conversation by conversationId. A direct reply action (RemoteInput) can write the reply straight into the outbox. When the user opens the conversation, cancel its notification.
Noise. Call setOnlyAlertOnce(true) so updating the notification for each new message does not sound or vibrate every time. Do not post at all for muted conversations, which also keeps high-priority pushes tied to visible notifications.
Trade-offs
| Decision | Options | What to pick and why |
|---|---|---|
| Real-time transport | WebSocket in foreground + FCM in background; pure FCM; long-polling; Server-Sent Events | WebSocket in foreground, FCM in background. Polling wastes battery and adds latency. Pure FCM is best-effort and adds a hop, so it is not great for a live conversation on screen. SSE only pushes server to client, so sends still need REST, and it has the same background limits as a WebSocket. |
| Message ordering | Sort by localSeq always; sort by serverSeq always; hybrid (server order, pending messages last) | Hybrid. Local counters give instant feedback but mean nothing across devices. Server order is consistent for everyone. The hybrid keeps the optimistic UI and moves a message at most a little when its ack arrives. |
| Outbox storage | A dedicated Outbox table; a pending state on MessageEntity | A pending state on the message row is simpler: one write, no join, and the UI already reads that row. A separate table makes sense when you also queue other operations (edits, deletes, reactions) or need per-attempt metadata. |
| Notification granularity | One per message; one per conversation; one global "new messages" | One per conversation with MessagingStyle, bundled with setGroup() and a summary. One per message spams the shade. A global notification loses the per-conversation context and the conversation features of Android 11+. |
| E2E encryption | Design the full crypto layer now; defer it as a discussion point | Defer it. The client architecture (Room, outbox, state machine) mostly stays the same whether the body is plaintext or encrypted. Name what it affects (push payloads, search, key storage) and move on. |
What breaks in production
- Users on a weak mobile connection saw some messages show "sending" forever.
- The retry loop lived in a coroutine started from a
ConnectivityManager.NetworkCallback. A short connectivity blip triggered a retry that failed, and the backoff state was only in memory. - After process death the loop was gone, so nothing retried until the user opened that chat again. When it did restart, it began from zero and hit the server repeatedly.
- Persist the attempt count on the message row, not in a coroutine variable.
- Enqueue unique
WorkManagerwork on every send (APPEND_OR_REPLACE,NetworkType.CONNECTED, exponential backoff). WorkManager keeps the work and its backoff across process death and runs it when a network is available. - Add random jitter to the foreground socket reconnect backoff, so many clients do not reconnect in the same second after a server restart.
- Users saw their own messages jump positions when the app reconnected after a background period.
- The DAO query used
ORDER BY serverSeq DESCwithreverseLayout = true. Messages still inSENDINGhadserverSeq = null; SQLite sorts NULL as the smallest value, so they sat at the far end, above older history. - When the acks arrived, the messages jumped back to the bottom. It looked like a bug.
- Change the sort to
ORDER BY CASE WHEN serverSeq IS NULL THEN 0 ELSE 1 END, serverSeq DESC, localSeq DESC, so pending messages stay newest (at the bottom withreverseLayout = true). - Give each item a stable key (
clientId) so Compose keeps the same item when its state changes. - Add
Modifier.animateItem()so any remaining small move is animated instead of a jump.
Common mistakes in this round
- Keeping the WebSocket alive in a background or foreground service. A background service is stopped soon after the app leaves the foreground, Doze cuts the network anyway, and a foreground service shows a permanent notification with no service type that fits. Close the socket in the background and rely on FCM data messages.
- Generating the message ID on the server. Without a client-generated ID, a retry after a lost response creates a duplicate message, because the server cannot tell it is the same send. Generate a UUID on the device and send it as an idempotency key.
- Loading the full conversation history into a List in the ViewModel. A conversation with thousands of messages wastes memory and makes every update slow. Use Paging 3 with a
PagingSourcefrom the Room DAO. - Using FCM notification messages. In the background they are shown by the system without running your code, so Room stays stale and you cannot use
MessagingStyle. Send data messages and build the notification yourself. - Posting a plain notification without MessagingStyle. The user sees a generic title/body pair, and the chat does not appear in the conversation section on Android 11+. Use
MessagingStylewith aPersonper sender and a conversation shortcut. - Trusting the push or the socket to deliver everything. Pushes can be dropped or collapsed, and the process can die with the socket. After every push, reconnect and app start, fetch everything after the last stored
serverSeq. - Treating E2E encryption as a hard requirement and designing the crypto layer in this round. It adds scope without changing the core client architecture. Mention what it affects and move on.
Follow-up questions
Answer out loud first. Then reveal the answer and compare it at each depth.
“How does the client handle a message that is delivered but the read receipt never arrives?”
“What happens to the outbox if the user deletes a conversation while messages are still in SENDING state?”
“How do you keep the conversation list (the list of chats) up to date?”
“How would you test the outbox retry logic without a real network?”
Self-review checklist
- The WebSocket follows the app's foreground lifecycle (
ProcessLifecycleOwnerON_START / ON_STOP). No background socket. FCM data messages handle background delivery. - High priority is used only for pushes that show a notification.
POST_NOTIFICATIONSis requested on Android 13+. - A client-generated UUID is the idempotency key for every send. Room upserts by the same key, so duplicates from push and sync collapse.
- Message states (SENDING, SENT, DELIVERED, READ, plus FAILED) are an enum. A reducer only moves them forward.
- Room is the single source of truth. WebSocket, sync and FCM paths write into Room. The UI reads only from Room.
- Paging 3 is used for history, with a
PagingSourcefrom the DAO. Order comes from the server sequence, with pending messages last. - The outbox is persisted in Room and drained by unique
WorkManagerwork with a network constraint. Retry state survives process death. - Notifications use one
MessagingStylenotification per conversation, a conversation shortcut,setGroup()with a summary, andsetOnlyAlertOnce(true). - E2E encryption is a discussion point, not designed in full. No specific protocol is named as a hard requirement.