Scalable Chat App

The interviewer asks

“Design a scalable chat app. How would you architect it?”

How to answer

A chat client is local-first: messages and conversations live in a SwiftData store that the UI observes with @Query, and the network only reconciles that store. Real time comes from a single WebSocket owned by an actor, which reconnects with backoff and resumes from the last server sequence number it applied; push notifications cover the app when it isn't running. Sending is optimistic: insert the message as pending with a client-generated UUID, send it, and on the server's acknowledgement attach the server ID and sequence number; the UUID makes retries idempotent and lets the client deduplicate echoes. Ordering comes from server-assigned per-conversation sequence numbers, never device clocks.

Key points (walk-through)

  • Requirements: 1:1 and group chats, instant send, real-time receive, history paging, read receipts and typing indicators, offline reading and queued sending, multi-device, media, end-to-end encryption for private messaging
  • Components: ChatConnection (actor: WebSocket, reconnect, resume), MessageStore (@ModelActor over SwiftData: upsert/dedupe, #Unique on client ID and on server ID), Outbox (pending sends with retry), ConversationModel (@MainActor @Observable, or @Query in views), MediaUploader (background URLSession), and the push handling (Notification Service Extension)
  • Data flow (receive): socket event → decode → MessageStore.upsert (dedupe by ID, place by seq) → @Query updates the open conversation → mark delivered/read in batches
  • Data flow (send): compose → insert .pending with clientID → send over the socket (or REST) → ack {clientID, serverID, seq} → update to .sent → on failure retry with backoff, then .failed with a Retry button
  • Ordering and gaps: each conversation has a monotonically increasing seq; if the client sees seq 41 then 43, it fetches 42 over REST; on reconnect it sends resume afterSeq to catch up; display order uses seq, with pending messages at the end
  • History: cursor pagination backwards (before: oldestSeq), loaded as the user scrolls up while keeping the scroll anchor; only recent messages are synced eagerly
  • Scaling (client view): one socket per app, not per conversation; batch read receipts; throttle typing indicators; lazy lists with stable IDs; the store indexes (conversationID, seq) (#Index); media as thumbnails plus on-demand full size
  • Failure modes: flaky networks (backoff with jitter, NWPathMonitor to reconnect promptly), duplicate delivery (dedupe by IDs), messages arriving while the app is suspended (push plus catch-up on foreground), the outbox stuck on one bad message (park it as failed)
  • Privacy/security: end-to-end encryption (Signal-protocol style: per-device identity keys, a double ratchet per session) means the server stores ciphertext only; keys live in the Keychain or Secure Enclave; the Notification Service Extension decrypts the push payload; CryptoKit provides the primitives, including post-quantum ML-KEM (MLKEM768) for hybrid key agreement
  • Adaptive UI: a NavigationSplitView (conversations | thread) on iPad, iPhone Duo and wide windows, collapsing to a stack on narrow widths; drafts saved per conversation so resizing or relaunching never loses text
  • Testing: Swift Testing on the store (dedupe, ordering, gap detection) with an in-memory container; a fake connection that replays scripted event streams including reconnects; UI tests for send/fail/retry

If they dig deeper

WebSocket vs HTTP long-polling vs server-sent events; URLSessionWebSocketTask vs Network framework's NetworkConnection for custom protocols. Multi-device sync of read state. Group chat fan-out on the server. Communication notifications with sender avatars. Message search with a local index. Backpressure: AsyncStream only offers buffering policies, so the consumer must keep up or batch.

Common pitfalls

Ordering by device timestamps. Loading the full history at launch. Treating the socket as the source of truth (state lost on reconnect). A socket per screen. Updating the UI from the socket's thread (use the store and @MainActor models). Claiming "end-to-end encrypted" while the server can read push payloads.

How to use it

The connection actor: one socket, reconnect with exponential backoff and jitter, resume from the last applied sequence number, and an AsyncStream of decoded events for the store to consume.

swift
actor ChatConnection {
    nonisolated let events: AsyncStream<ServerEvent>
    private let continuation: AsyncStream<ServerEvent>.Continuation
    private let session: URLSession
    private let url: URL
    private var socket: URLSessionWebSocketTask?
    private var lastSeq: Int64 = 0                     // highest server sequence number applied

    init(url: URL, session: URLSession = .shared) {
        self.url = url; self.session = session
        (events, continuation) = AsyncStream.makeStream(of: ServerEvent.self)
    }

    func run() async {                                 // until cancelled; reconnects with backoff + jitter
        var attempt = 0
        while !Task.isCancelled {
            let socket = session.webSocketTask(with: url)
            self.socket = socket; socket.resume()
            do {
                try await socket.send(.string(#"{"type":"resume","afterSeq":\#(lastSeq)}"#))   // catch up
                while true {
                    guard case .data(let data) = try await socket.receive() else { continue }
                    let event = try JSONDecoder().decode(ServerEvent.self, from: data)
                    lastSeq = max(lastSeq, event.seq); attempt = 0
                    continuation.yield(event)          // store dedups by message id
                }
            } catch {
                socket.cancel(with: .goingAway, reason: nil)
                attempt += 1
                let delay = min(30, pow(2, Double(attempt))) * Double.random(in: 0.5...1)
                try? await Task.sleep(for: .seconds(delay))   // cancelled: the while condition ends the loop
            }
        }
        continuation.finish()
    }
    func send(_ data: Data) async throws {
        guard let socket else { throw URLError(.notConnectedToInternet) }
        try await socket.send(.data(data))
    }
}

The app runs connection.run() in a task tied to the session (cancelled on logout), and a @ModelActor MessageStore consumes for await event in connection.events and upserts into SwiftData. In production, advance lastSeq only after the store has persisted the event.

Best practices

  • Make the local store the source of truth; the UI reads only from it
  • Order by server sequence numbers; detect and fill gaps
  • Send optimistically with client UUIDs; dedupe acks and echoes
  • Own one connection in an actor; reconnect with backoff and resume from a cursor
  • Page history backwards on demand
  • Encrypt end to end for private messaging, including push payloads

Related concepts

  • WebSockets, WebSocket Reconnection, Offline Mode Design, Pagination Design, Push Notification System, Background Uploads (media), Data Synchronization, CryptoKit