Design a chat app

Learn how to design an Android chat app: WebSocket reconnect with backoff, message states, a Room outbox, FCM push, and cursor-paginated history. About 30 minutes.

Why it matters

  • Chat is a common real-time feature in Android apps. Interviewers use it to test whether you can reason about WebSocket lifecycle, offline send, and message ordering without hand-waving.
  • A broken reconnect strategy or a missing outbox causes duplicate messages, lost sends, and out-of-order bubbles. These are the bugs that show up in production crash reports and user complaints.
  • A socket cannot be relied on in the background: Doze cuts network access, and the system can freeze or kill a cached app process at any time. Knowing when to rely on FCM push and when a WebSocket is worth keeping open is a senior-level decision that affects battery and latency.
  • The same patterns (outbox, state machine, cursor paging, sync engine) recur in the news feed, offline notes, and file upload lessons in this module. Mastering chat makes those designs faster.

The simple explanation

  • You send a letter by hand (WebSocket) while standing at the post office window.
  • If the window closes (server restart), you put the letter in a drop box (local outbox) and come back later.
  • The post office stamps each letter with a sequence number (serverSeq) so the recipient reads them in order, not in the order they arrived.
  • If you leave the building (app backgrounded), a courier (FCM push) knocks on your door to tell you to come back and pick up replies.
  • You never sort letters by the time you wrote them; you sort by the post office stamp.

How do you design a chat app on Android? Keep a WebSocket open while the chat is on screen, write every outgoing message to a Room outbox before sending it, order messages by a server-assigned sequence number, page older history over REST with cursors, and rely on FCM push when the app is in the background. A chat client has four moving parts: a WebSocket connection, a local outbox, a Room database, and a sync engine that ties them together.

Transport choice. For live messages, use a WebSocket (OkHttp's WebSocket in practice). Polling REST adds latency and wastes requests when nothing changed; SSE only pushes server to client, so sends would still need REST. REST still handles history: GET /messages?cursor=…&limit=50 with opaque cursor tokens, not offset paging.

Message state machine. Each message moves through fixed states. The client shows the bubble immediately (optimistic UI) and updates the state as acknowledgements arrive.

StateTriggerUI cue
DRAFTUser typesNo bubble yet
SENDINGTap send, row inserted in Room outboxClock icon
SENTServer ack with serverSeqSingle check
DELIVEREDRecipient device ackDouble check
READRecipient opens conversationHighlighted double check

Local outbox. Every outgoing message is written to Room with state = SENDING before the WebSocket send. While the app is open, the connection manager resends pending rows as soon as the socket reconnects. As a backstop, the write also enqueues unique WorkManager work (APPEND_OR_REPLACE, network constraint) that sends pending rows over REST if the app goes away first. The localId is the idempotency key, so a message sent by both paths is stored once.

Ordering. The server assigns a monotonically increasing serverSeq. The client sorts by serverSeq, never by local timestamp. After a reconnect, the client requests GET /messages?afterSeq=<lastSeq> to fill gaps.

Reconnect. OkHttp's WebSocket does not reconnect by itself. A connection manager coroutine reconnects after onFailure or onClosed with exponential backoff plus random jitter (for example a 1 s base and a 30 s cap) to avoid a thundering herd after a server restart, and reconnects at once when the network comes back (ConnectivityManager.NetworkCallback).

Background. Close the socket when the app leaves the foreground (for example on ProcessLifecycleOwner ON_STOP, perhaps after a short grace period). New messages then arrive as FCM data messages: onMessageReceived stores the message (or fetches what is missing) and posts a notification. Use high priority only for messages that show a notification; FCM can deprioritize apps whose high-priority messages do not lead to one, and delivery is never guaranteed. A foreground service is not a fit for keeping a chat socket open: no service type covers it, and dataSync is limited to 6 hours per 24 hours on Android 15.

Security. TLS (wss://) on the WebSocket, short-lived access tokens refreshed over REST, and optional end-to-end encryption (for example the Signal protocol) for message bodies. Never log message text.

Sending one chat message
Sending one chat message The user taps send. The client inserts the message into Room with a localId and state SENDING, so the bubble shows at once. It sends the message over the WebSocket. The server acknowledges with a serverSeq and the row becomes SENT. The server delivers it to the recipient, and when the recipient's device confirms, the row becomes DELIVERED. The bubble shows at once INSERT, SENDING SEND WITH localId ACK, serverSeq MARK SENT DELIVER DELIVERY ACK DELIVERED MARK DELIVERED Client sender's app Room local messages Server over WebSocket Recipient other device
The bubble appears at once from Room; the WebSocket acknowledgements then move it from SENDING to SENT to DELIVERED.

Notes

  • OkHttp's WebSocket has no built-in reconnect. Wrap it in a connection manager that calls OkHttpClient.newWebSocket again after onFailure or onClosed, and set pingInterval on the client so dead connections are detected.
  • Use exponential backoff with jitter: delay = min(cap, base * 2^attempt) + random(0, jitter). Without jitter, thousands of clients reconnect at the same instant after a server restart.
  • The local outbox is a Room table, not an in-memory list. If the process dies, the outbox survives. Each row carries a localId (UUID) used as an idempotency key so the server ignores duplicate sends.
  • Sort the conversation by serverSeq, not by System.currentTimeMillis(). Two devices on different clocks will disagree on local timestamps; the server sequence is the only total order.
  • FCM data messages reach FirebaseMessagingService.onMessageReceived even in the background, so the app can store the message and build its own notification. A notification message sent to a backgrounded app is shown by the system tray without calling your code, so the local database is not updated.
  • FCM is best-effort. Send high priority only for messages that produce a visible notification, and after a push always fetch from the last known serverSeq instead of trusting the payload to be complete.
  • Do not keep a WebSocket alive in a foreground service. It shows a permanent notification, no service type fits it, and on Android 15 a dataSync service is limited to 6 hours per 24 hours.
  • History pagination uses opaque cursor tokens (for example an encoded serverSeq), not integer offsets. Offsets break when rows are inserted or deleted between pages.
  • Message state transitions must be idempotent: receiving a DELIVERED ack for a message already in READ state is a no-op, not a crash.
  • Accessibility: give each bubble one merged description for TalkBack (for example "You sent: Hello, delivered"). Do not rely on colour alone for read vs unread; add a shape or icon difference.
  • In the interview, state your assumptions first: 1-to-1 vs group, media support, read receipts, typing indicators. Each adds a design branch.

Code example

This plain Kotlin model shows the outbox pattern: messages enter as SENDING, move to SENT when the server acknowledges with a sequence number, and are sorted by that sequence. On the device the two lists are one Room table, and ordered() is a query such as ORDER BY serverSeq IS NULL, serverSeq, createdAt.

// Outbox + message state machine for a chat client
enum class MsgState { DRAFT, SENDING, SENT, DELIVERED, READ }
 
data class ChatMessage(
    val localId: String,          // UUID, used as idempotency key
    val text: String,
    val serverSeq: Long? = null,  // assigned by server on ack
    val state: MsgState = MsgState.DRAFT
)
 
class Outbox {
    private val pending = mutableListOf<ChatMessage>()
    private val confirmed = mutableListOf<ChatMessage>()
 
    // Optimistic send: row written to Room before WebSocket send
    fun enqueue(msg: ChatMessage) {
        pending.add(msg.copy(state = MsgState.SENDING))
    }
 
    // Server ack: move from pending to confirmed with serverSeq
    fun onServerAck(localId: String, serverSeq: Long) {
        val idx = pending.indexOfFirst { it.localId == localId }
        if (idx >= 0) {
            val msg = pending.removeAt(idx)
            confirmed.add(msg.copy(serverSeq = serverSeq, state = MsgState.SENT))
        }
    }
 
    // Recipient device ack / read receipts
    fun onDelivered(localId: String) = advance(localId, MsgState.DELIVERED)
    fun onRead(localId: String)     = advance(localId, MsgState.READ)
 
    private fun advance(localId: String, next: MsgState) {
        val idx = confirmed.indexOfFirst { it.localId == localId }
        if (idx >= 0) {
            val current = confirmed[idx]
            // Guard: only advance to a later state, never regress
            if (current.state.ordinal < next.ordinal) {
                confirmed[idx] = current.copy(state = next)
            }
        }
    }
 
    // Acknowledged messages by server sequence, then pending ones in send order
    fun ordered(): List<ChatMessage> =
        confirmed.sortedBy { it.serverSeq } + pending
}
  • localId is a UUID generated on the client. The server uses it as an idempotency key so a retry after a dropped socket does not create a duplicate message.
  • serverSeq is null until the server acknowledges. Sorting by it (not by System.currentTimeMillis()) gives one order that every device agrees on; pending messages go at the end in the order they were sent.
  • advance is a no-op if the message is already in a later state, making the transition idempotent. This prevents a late DELIVERED ack from overwriting a READ state.

Run the idea in plain Kotlin

enum class MsgState { DRAFT, SENDING, SENT, DELIVERED, READ }

data class ChatMessage(
  val localId: String,
  val text: String,
  val serverSeq: Long? = null,
  val state: MsgState = MsgState.DRAFT
)

class Outbox {
  val pending = mutableListOf<ChatMessage>()
  val confirmed = mutableListOf<ChatMessage>()

  fun enqueue(msg: ChatMessage) {
      pending.add(msg.copy(state = MsgState.SENDING))
  }

  fun onServerAck(localId: String, serverSeq: Long) {
      val idx = pending.indexOfFirst { it.localId == localId }
      if (idx >= 0) {
          val msg = pending.removeAt(idx)
          confirmed.add(msg.copy(serverSeq = serverSeq, state = MsgState.SENT))
      }
  }

  fun onDelivered(localId: String) {
      val idx = confirmed.indexOfFirst { it.localId == localId }
      if (idx >= 0) {
          val current = confirmed[idx]
          if (current.state.ordinal < MsgState.DELIVERED.ordinal) {
              confirmed[idx] = current.copy(state = MsgState.DELIVERED)
          }
      }
  }

  fun onRead(localId: String) {
      val idx = confirmed.indexOfFirst { it.localId == localId }
      if (idx >= 0) {
          val current = confirmed[idx]
          if (current.state.ordinal < MsgState.READ.ordinal) {
              confirmed[idx] = current.copy(state = MsgState.READ)
          }
      }
  }

  fun ordered(): List<ChatMessage> {
      return confirmed.sortedBy { it.serverSeq } + pending
  }
}

fun main() {
  val outbox = Outbox()

  // User sends three messages quickly
  outbox.enqueue(ChatMessage("m1", "Hello"))
  outbox.enqueue(ChatMessage("m2", "World"))
  outbox.enqueue(ChatMessage("m3", "Again"))
  outbox.enqueue(ChatMessage("m4", "Still sending"))

  println("Pending before acks: " + outbox.pending.size)

  // Server acks arrive out of order (network reordering)
  outbox.onServerAck("m3", 30L)
  outbox.onServerAck("m1", 10L)
  outbox.onServerAck("m2", 20L)

  // Recipient reads first two
  outbox.onDelivered("m1")
  outbox.onDelivered("m2")
  outbox.onRead("m1")

  println("Pending after acks: " + outbox.pending.size)
  println("Confirmed count: " + outbox.confirmed.size)
  println("")
  println("Conversation (acked by serverSeq, then pending):")
  for (msg in outbox.ordered()) {
      println("  seq=" + msg.serverSeq + "  state=" + msg.state + "  text=" + msg.text)
  }

  println("")
  println("m1 is READ, m2 is DELIVERED, m3 is SENT, m4 is still SENDING")
}

Expected output:

Pending before acks: 4
Pending after acks: 1
Confirmed count: 3

Conversation (acked by serverSeq, then pending):
  seq=10  state=READ  text=Hello
  seq=20  state=DELIVERED  text=World
  seq=30  state=SENT  text=Again
  seq=null  state=SENDING  text=Still sending

m1 is READ, m2 is DELIVERED, m3 is SENT, m4 is still SENDING

In production

Thundering-herd reconnect after a server restart
  • After a WebSocket server restart, server metrics showed nearly all clients reconnecting within the same second.
  • The reconnect logic used a fixed 1-second delay with no jitter, so every client fired at the same instant.
  • The server's connection handler was saturated, delaying message delivery for all users.
The fix
  • Switched to exponential backoff with random jitter (a random delay between zero and the current backoff), so reconnects spread out instead of arriving in waves.
  • Capped the backoff at 30 seconds and reset the attempt counter on a successful onOpen.
  • Verified with a load test: simulated clients reconnecting over a spread-out window instead of a single spike.
Messages appear out of order after reconnect
  • Users reported that older messages appeared below newer ones after the app reconnected from the background.
  • The conversation list was sorted by System.currentTimeMillis() stored on the client, not by the server sequence number.
  • Two devices with different clocks produced different orderings; the bug was non-deterministic.
The fix
  • Replaced the local-timestamp sort with serverSeq as the sole ordering key in the Room query.
  • Added a gap-fill request (GET /messages?afterSeq=<lastSeq>) on every reconnect so missing messages are fetched before rendering.
  • Added a unit test that inserts messages with out-of-order serverSeq and asserts the sorted output.

Common mistakes

  • Sorting messages by local timestamp. Device clocks drift and are set by the user. Messages sent close together from devices with different clocks can appear in the wrong order. Always sort by the server-assigned serverSeq.
  • Sending over WebSocket before writing to the outbox. If the process is killed between the WebSocket send and the Room write, the message is lost. Write to Room first (state = SENDING), then send. The outbox is the source of truth for pending sends.
  • Using a fixed reconnect delay. All clients reconnect at the same instant after a server restart, creating a thundering herd. Use exponential backoff with random jitter so reconnects spread over time.
  • Keeping a WebSocket alive in a foreground service. It shows a permanent notification, costs battery, no service type is meant for it, and on Android 15 a dataSync service gets only 6 hours per 24 hours before onTimeout(). Close the socket in the background and rely on FCM data messages instead.
  • Setting message state unconditionally. A late DELIVERED ack can arrive after the message is already READ. If the code sets state unconditionally, it downgrades READ to DELIVERED. Guard each transition: only advance, never regress.
  • Using offset-based pagination for chat history. If messages are deleted or inserted between page requests, offset paging skips or repeats rows. Use opaque cursor tokens (for example an encoded serverSeq) so the server can resume from the exact position.
  • Treating an FCM push as guaranteed or complete. Pushes can be delayed, collapsed or dropped. After a push or a reconnect, fetch everything after the last stored serverSeq.

Interview questions

Answer out loud first. Then reveal the answer and compare it at each depth.

“How do you keep messages in the correct order on the client?”

“What happens when the WebSocket drops and the user sends a message?”

“How does the client receive messages when the app is in the background?”

“How do you design the API for fetching chat history?”

Quiz

A user sends a message while the WebSocket is disconnected. What is the correct client behaviour?

Why should the client sort chat messages by serverSeq instead of by System.currentTimeMillis()?

Your chat app is in the background with its WebSocket closed. What is the right way to tell the client a new message arrived?

A DELIVERED ack arrives for a message that is already in READ state. What should the client do?

0 of 4 answered

Mini task

15-minute exercise: build a local outbox with Room and a fake WebSocket

  1. Create a Room entity OutboxMessage with fields: localId (String, PK), text (String), serverSeq (Long?, nullable), state (String, default "SENDING"), createdAt (Long). Add a DAO with insert, updateState, and getPending() returning a Flow<List<OutboxMessage>>.

  2. Write a ChatOutbox class that takes the DAO and a suspend fun send(msg: OutboxMessage) (your fake WebSocket). enqueue(text: String) generates a UUID, inserts the row, then calls send. If send throws, the row stays in SENDING.

  3. Write a onServerAck(localId: String, serverSeq: Long) method that updates the row to SENT with the given serverSeq. Add a guard: if the row is already READ, do nothing.

  4. Write a reconnect-style retry loop (a suspend fun with a while loop and delay, standing in for the connection manager) that reads the pending rows every 2 seconds and re-calls send for each row still in SENDING. Cap retries at 5; after that, set state to FAILED.

  5. Add a unit test (plain Kotlin with a fake in-memory DAO) that simulates three messages, acks them out of order, and asserts that ordered() returns them sorted by serverSeq.

Done condition: the test passes, the outbox survives a simulated process death (you clear the in-memory list and re-read from the DAO), and no message is sent twice (the localId idempotency check is present in the fake send).

Next: Design an offline-first notes app