skip to content

As the lead on a Core Data expense app, what context rule would you set for which contexts write, which read, and how changes reach the UI?

level: principalimportance: should knowfreq 35%

answer

  1. one reader, few writers
  2. serialise or parallelise imports
  3. every write path reaches the UI
  4. enforce it in debug builds

basics

~20 s

A common rule: viewContext serves reads and small edits, one kept background context does imports, every write path ends in a merge viewContext receives, each context gets a merge policy, and debug builds run the concurrency argument.

solid answer

~40 s

I would write it down as a short rule. `viewContext` is the only context the UI reads, and it takes small user edits, with a child context for sheets that can be cancelled. Imports and syncs go through one kept `newBackgroundContext()` writer, so they serialise on one queue instead of racing; I would allow parallel `performBackgroundTask(_:)` contexts only for independent entities. `viewContext` sets `automaticallyMergesChangesFromParent`, batch requests must merge their returned IDs or the app consumes persistent history, and each context gets a deliberate merge policy. Objects never cross queues, only `NSManagedObjectID`s, and `-com.apple.CoreData.ConcurrencyDebug 1` is on in debug and UI-test schemes. The tradeoff is throughput against simplicity: one writer is easy to reason about but makes a long import delay other writes.

go deeper

for a junior

Know the shape of the rule: the UI reads viewContext, heavy writes go to a background context, and objects are passed between them by objectID.

for a middle

Explain how each part works: a kept background context serialising imports, automatic merging into viewContext, and child contexts for cancellable edits.

for a senior

Spot where a codebase breaks the rule: unmerged batch requests, competing writers, default merge policies throwing unhandled errors, and missing debug checks.

for a principal

Own the tradeoffs: one writer against parallel writers, sibling contexts against a root-writer chain, merging by hand against history, and how enforcement keeps the rule true.

## Why a lead has to decide this Core Data gives you the parts: main and private contexts, parent and child chains, merges and merge policies. It does not tell a team how to combine them. Without a rule each feature picks its own pattern, and the app ends up with five background contexts writing the same rows, screens that miss imports and conflicts nobody handles. The decision has no single right answer; it depends on how much the app writes, from where, and how fresh the UI must be. ## Decision 1: who writes | Option | Gains | Costs | |---|---|---| | One kept `newBackgroundContext()` writer | blocks run one at a time on one queue, so writers never race each other | a 40,000-row import delays every other background write | | `performBackgroundTask(_:)` per job | jobs run in parallel, each on a fresh context | concurrent saves on the same rows produce conflicts | | Writer per domain (imports, attachments) | parallel where entities do not overlap | more contexts to configure and merge | For the expense app I would start with one writer for imports and syncs, and user edits on `viewContext`. The rule should say which entities each writer owns. ## Decision 2: the shape of the stack - **Sibling contexts on the coordinator**, as `NSPersistentContainer` creates them: each context saves straight to the store, and the others merge. This is the default and the one I would standardise on. - **A private root writer with the UI context as its child**: the UI saves only into memory and the root writes to disk in the background. Saves are cheap for the UI, but every fetch is mediated by the parent, and every write needs two saves. - **Child contexts for discardable edits**, whichever shape the stack has. ## Decision 3: how changes reach the UI 1. `viewContext.automaticallyMergesChangesFromParent = true`, so ordinary background saves update visible objects. 2. Batch inserts, updates and deletes never post a save, so the rule must require one of two things: every batch call goes through a helper that requests object IDs and calls `NSManagedObjectContext.mergeChanges(fromRemoteContextSave:into:)`, or the app enables persistent history and processes it. Writes from an extension push you toward history, which is set up with the persistent stack. 3. Lists use a fetched results controller or an equivalent observer on `viewContext`, never objects from another context. ## Decision 4: conflicts The default `NSErrorMergePolicy` makes every conflicting save throw. The rule should name a policy per context, for example `mergeByPropertyObjectTrump` on `viewContext` so user edits win property by property, and say where the error policy stays because a silent winner would hide a real problem. Conflicts that are resolved silently should still be logged during development. ## Decision 5: enforcement - **Debug builds** run with `-com.apple.CoreData.ConcurrencyDebug 1`; UI tests too, so any wrong-queue access fails a run. - **Code review**: no `NSManagedObject` in a signature that crosses queues or actors, only `NSManagedObjectID` or value types; every private context call sits in `perform`. - **Naming**: give each long-lived context a `name`; the header says a private-queue context sets that label on its queue, which makes traces readable. Set `transactionAuthor` when history is in use so each history transaction records which part of the app wrote it. - **Swift 6 language mode** helps, since `NSManagedObject` is declared non-Sendable, but it does not catch every hand-off, so it backs up the runtime check rather than replacing it. ## How the rule evolves Revisit it when a new writer appears (a widget, a share extension, a sync engine) or when imports grow until a single writer delays user-visible work. Moving persistence to SwiftData changes the vocabulary to model actors, which the SwiftData material covers, and how two devices settle a conflict is a sync design question for the system design lessons. Keep the rule to one page: who writes, how the UI hears about it, what wins a conflict, and how the build checks it.

  • When would you allow several background writers?
    When the jobs touch different entities, such as importing statements while downloading receipt images into a separate entity, and the single writer's queue is measurably delaying user-visible work. Each writer then owns its entities, has its merge policy set, and its saves still reach `viewContext` through automatic merging.
  • Why might a team reject the private-root-plus-UI-child stack?
    Every fetch from the UI context is mediated by its parent, every write needs two saves before it is durable, and a crash between them loses edits the user saw as saved. The container's sibling contexts keep one save per write and are the shape most code and documentation assume.
  • How do you check the rule is followed without reading every pull request closely?
    Run debug and UI-test schemes with the concurrency debug launch argument so violations crash in CI, wrap batch requests in one helper that always merges, and use Swift 6 language mode diagnostics as an extra net. Review then focuses on new contexts and new writers.

  • Using viewContext for the 40,000-row import because it keeps the code simple.
  • Letting every feature create its own background context with no shared rule.
  • Assuming automatic merging covers batch requests as well as normal saves.
  • Leaving every context on the default merge policy without handling the errors.
  • Relying on Swift 6 checking alone and dropping the concurrency debug argument.