9 of 20 · 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. iOS code often calls it a store, service or client.
How it's wired
- ThanksRepository reads cache → disk, and writes disk first, then cache, then syncs remote. Callers just call notes() and save(_:).
| Part | Owns | Looks like |
|---|---|---|
| Repository | Collection-like API, source-of-truth policy | actor ThanksRepository |
| Local store | Fast reads, offline | Memory cache, file, Core Data |
| Remote | Server of record or sync target | RPC / HTTP client |
Swift example: atomic local write + durable outbox
Offline-first repositories must keep the local record and its sync job in one transaction so a crash never leaves them out of sync.
Actor repository with transactional outbox
Separate NoteRepository and OutboxRepository break atomicity unless they share a transaction boundary.
protocol DatabaseTransaction: Sendable {
func upsertNote(_ note: ThankYouNote) throws
func enqueueOutbox(noteID: UUID) throws
}
protocol LocalDatabase: Sendable {
func write(_ block: @Sendable (DatabaseTransaction) throws -> Void) async throws
}
actor OfflineNoteRepository {
private let db: any LocalDatabase
init(db: any LocalDatabase) {
self.db = db
}
func save(_ note: ThankYouNote) async throws {
try Task.checkCancellation()
// Both writes succeed or both roll back: a crash mid-save can't lose the outbox entry.
try await db.write { tx in
try tx.upsertNote(note)
try tx.enqueueOutbox(noteID: note.id)
}
}
}A separate background worker drains the outbox with an idempotency key and exponential backoff.
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 source | Cache plus disk plus network. |
|---|---|
| Offline support | The repository owns the sync queue and the policy. |
| One API call, no caching | A plain service is enough. |
Compared
Online-first vs offline-first
| Online-first | Offline-first | |
|---|---|---|
| Write path | Request, then update cache | Local write, then sync queue |
| Failure mode | Errors on bad network | Conflicts to resolve |
| Fits | Feeds, search | Notes, 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.
Explain Repository in 30 seconds.
- A repository, which iOS code usually calls a store or client, gives features a small API like
notes()andsave(_:)and hides whether data comes from memory, disk or the network. - Its real job is policy: which source is the truth, when cached data goes stale, and how conflicts resolve.
- For offline-first, local is the truth and the network is sync.
- The cost is one more layer, so I skip it for a single endpoint with no caching.
What is the Repository pattern, and what does it centralize?
- In iOS code it's usually a store or client: one type that owns access to a kind of data, like
NoteStore.notes(matching:), so features ask for what they want and never see Core Data, files or endpoints. - It centralizes query construction and data policy, meaning caching, source of truth and mapping into plain structs.
- I'd add one once several features read the same data or storage may change.
- For one endpoint with no caching, I'd skip it, because it's a layer with nothing to hide.
You must ship a feature before the storage choice is decided. How do you avoid rewriting the view model later?
- I'd define the protocol in the feature's terms, like
protocol UserStore { func user(id: User.ID) async throws -> User? }, and inject it into the view model'sinit. - Making it
async throwsfrom day one matters, because an in-memory version that can't fail would let callers skip error handling the real store needs. - I'd ship with an in-memory actor, which doubles as the test fake, then swap in SwiftData or Core Data without touching the view model.
Similar query logic for the same entities is duplicated across many view models. Where should it live, and why?
- I'd diff the copies first, because duplicated queries usually drift, and settle which behavior is correct before moving anything.
- Then I'd give each entity one store, like
OrderStore.orders(status:), so view models pass criteria and the store owns fetching and mapping. - I'd migrate one view model at a time behind tests.
- If the copies are trivial one-line fetches, I'd leave them, because the layer would cost more than the duplication.
Five view models each call the network singleton directly. How do you restructure access to remote and disk data?
- I'd move network and disk access behind injected stores, like
ProfileStore, and stop view models reachingNetworkManager.shared. - The coordinator or composition root passes the store in, so each view model's dependencies show in its
initand tests pass fakes. - I'd migrate one view model at a time, keeping the singleton behind the store until nothing else calls it.
- It's still one shared object, but now it has one owner and a lifetime I can replace.
Read it in the app's source
Done with Repository? Mark it complete. Nailing its cards builds this pumpkin, row by row.