SwiftPumpkin

Mobile system design

Four walkthroughs

Each one goes requirements and numbers, then data, architecture, storage and failure. Try the prompt yourself first.

Infinite feed

Design the home feed of a social app: an endless, image-heavy list that loads fast and scrolls smoothly.

Requirements and numbers

  • First content on screen in under a second from a cold start, using cached data.
  • No dropped frames: at 120 Hz you have about 8 ms per frame, so nothing heavy on the main thread.
  • Pages of about 20 items; prefetch one or two pages ahead, not more, to bound memory and data.
  • Readable offline: show the last feed you saw, clearly marked as not fresh.

API and data model

  • GET /feed?cursor=…&limit=20 returns { items, nextCursor }. Use an opaque server cursor, not offsets: new posts at the top don't shift pages and cause duplicates or gaps.
  • Each item carries a stable id and layout hints such as image aspect ratio, so cells size correctly before images arrive.

Client architecture

  • FeedRepository (an actor) owns pages, cursors and the cache. FeedViewModel on the main actor exposes value snapshots of item view state.
  • A diffable data source or List keyed by item id, so updates animate and never reload the whole list.
  • A router owns navigation to detail screens; cells only report taps.

Storage and caching

  • Persist the first page or two in a local database for an instant cold start. Stale-while-revalidate: render the cache, fetch fresh, merge by id.
  • Images live in their own pipeline (memory plus disk cache, downsampled to display size). See the image pipeline walkthrough.
  • Clear user-specific caches on logout.

Failure handling

  • One request in flight per cursor; ignore duplicate "load more" triggers.
  • Next-page failure shows an inline retry row; backoff with jitter on automatic retries.
  • De-duplicate items by id across pages, since ranking can move items between requests.
  • Offline shows a banner over cached content, never a blank error screen.

What makes it staff-level

  • Name the metrics you'd ship with: time to first content, hitch rate, pagination error rate, image cache hit rate.
  • Discuss server-driven layout versus client templates, and what that does to release velocity and experimentation.
  • Decide what may be cached on disk and for how long, and how that interacts with privacy and logout.

Chat with an offline outbox

Design one-to-one and group chat that lets you send while offline, never shows duplicates, and keeps order.

Requirements and numbers

  • Sent messages appear instantly, online or not.
  • Each message's effect happens exactly once, even if the transport retries.
  • Per-conversation ordering; conversations with tens of thousands of messages still scroll smoothly.
  • Survives app termination mid-send.

Data model

  • Message: clientID (UUID made on device), serverID (optional until acked), conversationID, body, createdAt, status (pending, sending, sent, delivered, read, failed).
  • The local database is the source of truth. The UI observes queries on it, never network responses directly.

Send path

  • In one transaction: insert the message as pending and append it to a durable outbox. The UI shows it immediately.
  • An outbox worker (an actor) sends in order per conversation, using clientID as the idempotency key.
  • The server ack maps clientID to serverID and a sequence number; the message becomes sent.
  • Retry with exponential backoff and jitter. After N failures mark it failed, with tap to retry. On relaunch, the worker resumes from the outbox.

Receive path

  • A socket or push signals new data; the client fetches everything since its last seen sequence number for that conversation.
  • Gaps in sequence numbers trigger a backfill fetch. Upsert by serverID so replays are harmless.
  • Order by server sequence. Pending messages sit at the bottom in local order until acked.

Failure modes to name

  • Duplicate sends from retries: solved by the idempotency key.
  • Out-of-order delivery: solved by sequence numbers and gap detection.
  • Edits and deletes racing: the server is the authority; deletes are tombstones so they propagate.
  • Attachments: upload first with a resumable background session, then send a message that references the uploaded media id.

What makes it staff-level

  • State the delivery contract plainly: at-least-once transport, exactly-once effect through idempotency.
  • Window the message list from the database (load around the visible range) instead of holding the whole history in memory.
  • Ship with send latency p50/p95, failure rate and outbox depth as metrics, and note how end-to-end encryption would change the design.
  • Even with three engineers, keep sockets, the database and vendor models out of view models, and make ordering and retries one component's job. If contractors rotate through, back that with narrow APIs, written invariants and contract tests. What not to build yet: a package per feature or a use-case type per call.

Image loading pipeline

Design the image loading used by every list in the app: fast, memory-safe, and never showing the wrong image in a reused cell.

The numbers that drive the design

  • A decoded bitmap costs width × height × 4 bytes. A 4000 × 3000 photo is about 48 MB decoded.
  • Downsampled to a 300 × 300 pt thumbnail at 3x (900 × 900 px), it's about 3.2 MB. Downsampling is the single biggest win.

Pipeline

  • Request: URL plus target size.
  • Memory cache of decoded, downsampled images keyed by URL and size, cleared on memory warnings.
  • Disk cache of the original bytes with a size cap and LRU eviction, honoring HTTP cache headers.
  • Network via URLSession, coalescing duplicate in-flight requests for the same URL.
  • Decode and downsample off the main thread with ImageIO thumbnails, then deliver on the main actor.

Cell reuse and cancellation

  • Tie each load to the cell's current item id. Cancel it in prepareForReuse or when a SwiftUI view disappears.
  • Before setting the image, check the cell still shows the same item; otherwise a late load flashes the wrong picture.
  • Prefetch upcoming rows at low priority and cancel when the user scrolls away.

Failure handling

  • Retry transient errors with backoff; show a placeholder, never a broken layout.
  • Offline serves from disk; missing images keep their placeholder and reserved size.

What makes it staff-level

  • Build versus buy: an established library is usually right unless you have special needs such as custom formats or strict size limits.
  • One shared pipeline owned by one team, so features don't each grow a cache and multiply memory use.
  • Measure cache hit rate, time to image and memory peaks, and set an app-wide memory budget.

Offline-first sync

Design sync for a notes app used offline on several devices: edits must converge and nothing may be lost.

Data model

  • The local database is the source of truth. Each record has a UUID, a server version, an updatedAt, a dirty flag, and a deleted tombstone.
  • Never trust device clocks for ordering; use server versions or hybrid logical clocks.

Protocol

  • Pull: fetch changes since the last server change token, apply them, store the new token.
  • Push: send dirty records with the version they were based on. The server accepts or rejects stale versions with a conflict.
  • Per-record acks and idempotent upserts by id, so a partial push is safe to retry.

Conflicts

  • Last-writer-wins by server order: simple, but silently loses edits.
  • Field-level merge: keeps non-overlapping edits, which covers most real conflicts.
  • CRDTs for text: no conflicts by construction, at the cost of complexity and payload size.
  • Or surface the conflict to the user. Pick per data type, not one rule for everything.

When sync runs

  • On launch and on returning to the foreground, after local edits (debounced), on a silent push, and opportunistically in background refresh.
  • Deletes propagate as tombstones, garbage-collected only after every device has synced past them.

What makes it staff-level

  • State the consistency guarantee: eventual, per record, with a defined conflict rule.
  • Plan schema evolution: versioned payloads that older app versions can still read.
  • Make deletion complete: a delete must reach the server, other devices, caches and indexes.
  • Measure sync lag, conflict rate and failed pushes.