SwiftPumpkin

11 of 22 · System architecture

Repository

A repository gives the rest of the app a collection-like API for domain objects, such as notes() and save(_:), and hides where the data comes from: memory, disk or network.

How it's wired

notes() / save()Read / writeSyncCallerAsks for dataRepositoryDecides the sourceLocal storeCache + diskRemote APISync
calls or tellsreports backCallers never learn where data lives. The repository owns the source-of-truth policy.
  • ThanksRepository reads cache → disk, and writes disk first, then cache, then syncs remote.
  • Callers just call notes() and save(_:).
PartOwnsLooks like
RepositoryCollection-like API, source-of-truth policyactor ThanksRepository
Local storeFast reads, offlineMemory cache, file, Core Data
RemoteServer of record or sync targetRPC / HTTP client

The questions it has to answer

  • Source of truth. Offline-first: local is truth and the network is sync. Online-first: the server is truth and local is a cache. Mixing both without a stated policy produces conflicting writes.
  • Staleness. Pick an invalidation policy: TTL, server ETags, or push invalidation.
  • Conflicts. Two devices edit the same note. Last-write-wins is simple and loses data; per-field merges or server versioning cost more.
  • Concurrency. An actor serializes access, but awaits interleave: two saves can reach disk in one order and the cache in another. Track in-flight writes per id, or version each record and keep the newest.
  • Don't leak storage types (managed objects, DTOs) through it. Return domain structs.

When I'd add a repository

Data from more than one sourceCache plus disk plus network.
Offline supportThe repository owns the sync queue and the policy.
One API call, no cachingA plain service is enough.

Compared

Online-first vs offline-first

Online-firstOffline-first
Write pathRequest, then update cacheLocal write, then sync queue
Failure modeErrors on bad networkConflicts to resolve
FitsFeeds, searchNotes, drafts, messages

Expert notes

  • In a system design round, the repository is where you answer the offline, caching and conflict questions. Say the policy out loud.

Check yourself

Answer out loud before you reveal. Recall is what makes it stick.

30-second answer

Explain Repository in 30 seconds.

System designAsked directly

What is the Repository pattern, and what does it centralize?

iOS codingAsked indirectly

You must ship a feature before the storage choice is decided. How do you avoid rewriting the view model later?

System designAsked indirectly

Similar query logic for the same entities is duplicated across many view models. Where should it live, and why?

System designAsked indirectly

Five view models each call the network singleton directly. How do you restructure access to remote and disk data?

Read it in the app's source