Pocket How
Data and architecture

CloudKit sync with SwiftData and CKSyncEngine: rules, schema deploy, conflicts

iOS 17+, iPadOS 17+. Advanced. By Cihat Salik, .

Short answer

For automatic sync, make every SwiftData property optional or defaulted, every relationship optional, and drop unique constraints, then promote the CloudKit schema to Production before release. When you own the local store, use CKSyncEngine: persist its state on every stateUpdate, store each record's system fields, and resolve serverRecordChanged yourself.

The problem

Sync that works on your two test devices can still fail quietly for users. A model with a unique constraint never uploads. A schema you forgot to deploy works in TestFlight and breaks in the App Store build. A user signs out of iCloud and your app keeps showing someone else’s data. Apple gives you two paths. SwiftData’s built-in CloudKit sync handles everything if your models follow its rules. CKSyncEngine (iOS 17) handles the CloudKit side when you own the local store and the merge logic. Pick the path first, then follow its rules exactly.

Choose the path

Apple’s WWDC23 session Sync to iCloud with CKSyncEngine draws the line:

  • NSPersistentCloudKitContainer, which SwiftData uses under the hood, is the full stack: local store plus sync.
  • CKSyncEngine is for apps that bring their own persistence: SQLite, GRDB, files, or SwiftData with your own sync layer.
  • Raw CKDatabase operations are for cases that need full control and are worth the work.

SwiftData sync covers the private database only. Paul Hudson notes in How to sync SwiftData with iCloud that sharing and the public database need NSPersistentCloudKitContainer directly. CKSyncEngine covers private and shared databases, never the public one.

Path 1: SwiftData with CloudKit

Capabilities

Add the iCloud capability with CloudKit and a container, and the Background Modes capability with Remote notifications. SwiftData reads the entitlements and uses the first container identifier it finds. To pick a specific container, or to turn sync off in an app that already has the CloudKit entitlement for other reasons, pass it explicitly:

import SwiftData

func makeSyncedContainer() throws -> ModelContainer {
    let config = ModelConfiguration(cloudKitDatabase: .private("iCloud.com.example.notes"))
    return try ModelContainer(for: Note.self, Folder.self, configurations: config)
}

func makeLocalOnlyContainer() throws -> ModelContainer {
    let config = ModelConfiguration(cloudKitDatabase: .none)
    return try ModelContainer(for: Note.self, Folder.self, configurations: config)
}

Model rules

Apple’s syncing guide lists what CloudKit cannot support, and Hudson’s chapter adds that breaking these rules makes sync fail silently:

  • No unique constraints. CloudKit syncs concurrently and cannot enforce @Attribute(.unique) or #Unique.
  • Every relationship optional. The server does not process relationship changes atomically.
  • No .deny delete rule. Changes do not sync immediately, so the server cannot deny a delete.
  • Every property optional or with a default. Records arrive in any order and with missing fields.
  • Set inverses. SwiftData infers an inverse when it can. Where it cannot, declare it, because CloudKit applies changes in an indeterminate order.
import Foundation
import SwiftData

@Model
final class Folder {
    var name: String = ""
    @Relationship(deleteRule: .cascade, inverse: \Note.folder)
    var notes: [Note]? = []
    init(name: String) { self.name = name }
}

@Model
final class Note {
    var id: UUID = UUID()
    var title: String = ""
    var body: String = ""
    var modifiedAt: Date = Date.now
    var folder: Folder?
    init(title: String) { self.title = title }
}

Without unique constraints, duplicates are your job. Two devices that each create an “Inbox” folder offline will both upload it. Deduplicate after sync on a stable key, such as a UUID you generate once or a fixed name for system folders, and merge the children into the survivor.

Initialize and deploy the schema

CloudKit has a Development and a Production environment. Debug builds talk to Development. TestFlight and App Store builds talk to Production. Apple’s guide shows how to push your schema to Development from a debug build: load a temporary NSPersistentCloudKitContainer against the same store URL, call initializeCloudKitSchema(), then remove the store before creating the ModelContainer, all inside #if DEBUG.

Then open the CloudKit Console, check the record types, and deploy the schema changes to Production. Do this before you submit the build, not after.

The rule that shapes every later release: Production schemas are additive only. Apple’s guide says you cannot delete model types or change existing attributes once promoted. You can add types and fields. Plan model changes as additions, and keep old fields readable by older app versions.

Testing

Test on real devices signed in to the same Apple Account. Hudson notes the simulator rarely syncs reliably. Delete and reinstall to confirm the app pulls existing data down.

Path 2: CKSyncEngine

CKSyncEngine schedules sync with the system, handles push subscriptions, batches uploads, and retries transient errors such as networkFailure, requestRateLimited, zoneBusy and notAuthenticated. It leaves three things to you: your local store, the mapping between your types and CKRecord, and every error that needs app logic, including conflicts.

It needs the same two capabilities as SwiftData sync.

Set up the engine

Create the engine early in launch, pass the state you saved last time, and keep a single engine per database. Christian Selig, who shipped CKSyncEngine in his apps and wrote up what he learned, stresses the same point Apple does: one engine for the private database, optionally another for the shared one.

The delegate protocol is Sendable with async requirements, so an actor is a natural fit. The snippet below leaves out the local store type (LocalStore), which only needs to read and write your models and keep each record’s encoded system fields.

import CloudKit

actor SyncCoordinator: CKSyncEngineDelegate {
    static let zoneID = CKRecordZone.ID(zoneName: "Notes")

    private let store: LocalStore
    private let database = CKContainer(identifier: "iCloud.com.example.notes").privateCloudDatabase
    private var _engine: CKSyncEngine?

    init(store: LocalStore) {
        self.store = store
    }

    var engine: CKSyncEngine {
        get async {
            if let _engine { return _engine }
            let configuration = CKSyncEngine.Configuration(
                database: database,
                stateSerialization: await store.loadSyncState(),
                delegate: self
            )
            let engine = CKSyncEngine(configuration)
            _engine = engine
            return engine
        }
    }

    func noteChanged(id: String) async {
        let recordID = CKRecord.ID(recordName: "Note|\(id)", zoneID: Self.zoneID)
        await engine.state.add(pendingRecordZoneChanges: [.saveRecord(recordID)])
    }

    func noteDeleted(id: String) async {
        let recordID = CKRecord.ID(recordName: "Note|\(id)", zoneID: Self.zoneID)
        await engine.state.add(pendingRecordZoneChanges: [.deleteRecord(recordID)])
    }
}

The Note| prefix follows a tip from Selig: the engine hands you record IDs without the record type, so encode the type in the record name.

Persist state and handle events

Everything the engine tells you arrives in handleEvent(_:syncEngine:). The one you cannot skip is stateUpdate. Apple’s documentation says persisting it is your responsibility, and Selig explains why: it is the checkpoint that keeps pending changes and change tokens across launches and crashes.

extension SyncCoordinator {
    func handleEvent(_ event: CKSyncEngine.Event, syncEngine: CKSyncEngine) async {
        switch event {
        case .stateUpdate(let update):
            await store.saveSyncState(update.stateSerialization)

        case .accountChange(let change):
            await handleAccountChange(change, engine: syncEngine)

        case .fetchedRecordZoneChanges(let changes):
            for modification in changes.modifications {
                await store.apply(serverRecord: modification.record)
            }
            for deletion in changes.deletions {
                await store.deleteLocal(recordName: deletion.recordID.recordName)
            }

        case .sentRecordZoneChanges(let sent):
            for record in sent.savedRecords {
                await store.saveSystemFields(of: record)
            }
            await handleFailures(sent.failedRecordSaves, engine: syncEngine)

        default:
            break
        }
    }

    func nextRecordZoneChangeBatch(
        _ context: CKSyncEngine.SendChangesContext,
        syncEngine: CKSyncEngine
    ) async -> CKSyncEngine.RecordZoneChangeBatch? {
        let scope = context.options.scope
        let pending = syncEngine.state.pendingRecordZoneChanges.filter { scope.contains($0) }
        return await CKSyncEngine.RecordZoneChangeBatch(pendingChanges: pending) { recordID in
            await self.store.record(for: recordID)
        }
    }
}

Use RecordZoneChangeBatch(pendingChanges:recordProvider:) (iOS 17). Apple’s documentation explains that each batch is one request with a server limit of 250 records, and this initializer stops at the limit and leaves the rest pending. Return nil from the record provider for a record that no longer exists locally and the batch skips it.

Jordan Morgan’s Superwall walkthrough calls out the other half of store.record(for:): build the CKRecord from the stored system fields, then copy your current values onto it. Archive system fields with encodeSystemFields(with:) after every save and every fetched change. Without them, every upload looks like a brand-new record and collides with the server copy.

Never call fetchChanges() or sendChanges() from inside these delegate methods. Selig warns that it can loop. Call them from UI actions such as pull to refresh.

Create the zone

Records live in a custom zone, and the zone has to exist before the first save. Queue it as a database change when the user signs in:

extension SyncCoordinator {
    func handleAccountChange(_ change: CKSyncEngine.Event.AccountChange, engine: CKSyncEngine) async {
        switch change.changeType {
        case .signIn:
            engine.state.add(pendingDatabaseChanges: [.saveZone(CKRecordZone(zoneID: Self.zoneID))])
            await queueEverythingForUpload(engine: engine)
        case .signOut, .switchAccounts:
            await store.deleteAllLocalData()
            await store.saveSyncState(nil)
            _engine = nil
        @unknown default:
            break
        }
    }

    func queueEverythingForUpload(engine: CKSyncEngine) async {
        let ids = await store.allRecordIDs(in: Self.zoneID)
        engine.state.add(pendingRecordZoneChanges: ids.map { .saveRecord($0) })
    }
}

The engine saves zones before records in a send. If a save still fails with zoneNotFound, for example after the user deleted iCloud data in Settings, queue the zone again and re-queue the record.

Account changes

The engine only syncs with a signed-in account and reports changes through accountChange. Apple’s documentation for signOut and switchAccounts says to delete locally stored data for the previous account. For signIn, Apple lists four choices for existing local data: keep it separate, merge it into the account, delete it, or ask the user. Merging is what most users expect when they first turn on iCloud.

Selig adds two observations from production. While the app is running, a switch usually arrives as a sign-out followed by a sign-in; switchAccounts shows up after a relaunch. And on sign-out or switch, throw away the saved engine state and create a new engine. On sign-in, keep it.

Conflicts

CloudKit rejects a save made from stale system fields with serverRecordChanged. The engine does not resolve it. Apple’s session resolves in favor of the server, and so does Selig in most cases, keeping a higher value only for fields that should never go backward.

extension SyncCoordinator {
    func handleFailures(
        _ failures: [CKSyncEngine.Event.SentRecordZoneChanges.FailedRecordSave],
        engine: CKSyncEngine
    ) async {
        for failure in failures {
            let recordID = failure.record.recordID
            switch failure.error.code {
            case .serverRecordChanged:
                if let serverRecord = failure.error.serverRecord {
                    await store.merge(serverRecord: serverRecord, localRecord: failure.record)
                    engine.state.add(pendingRecordZoneChanges: [.saveRecord(recordID)])
                }
            case .zoneNotFound:
                engine.state.add(pendingDatabaseChanges: [.saveZone(CKRecordZone(zoneID: recordID.zoneID))])
                engine.state.add(pendingRecordZoneChanges: [.saveRecord(recordID)])
            case .unknownItem:
                await store.clearSystemFields(recordName: recordID.recordName)
                engine.state.add(pendingRecordZoneChanges: [.saveRecord(recordID)])
            case .quotaExceeded:
                engine.state.add(pendingRecordZoneChanges: [.saveRecord(recordID)])
            default:
                break
            }
        }
    }
}

Two details from Selig’s notes are easy to miss. Deletes skip conflict checks entirely, so a delete on one device wins over an edit on another. And quotaExceeded saves are not re-queued for you; re-add them and tell the user their iCloud storage is full.

Fields that older versions do not know

CloudKit only writes the fields you set on a record. That protects new fields from older app versions, as long as older versions never remove fields they do not recognize. Selig recommends storing enums as strings: an old version that cannot decode a new case must not write nil back over it.

Testing

Apple’s session suggests running two engines with separate local stores to stand in for two devices, and setting automaticallySync to false in tests so you control the order of sends and fetches. That is the only reliable way to reproduce a conflict on purpose.

Traps

  • Schema not deployed to Production. Sync works in debug and fails in TestFlight. Deploy in the CloudKit Console before submitting.
  • A unique constraint on a synced SwiftData model. Sync stops without an error you will see.
  • Not saving stateUpdate. The engine forgets pending changes and starts over on every launch.
  • Not saving system fields. Every edit becomes a conflict.
  • Using CKSyncEngine with the public database. Apple’s documentation says not to.
  • Testing sync in the simulator. Use two physical devices.

Decision table

Need Use
SwiftData app, private data, simple models SwiftData with cloudKitDatabase: .private(...)
Sharing records between users NSPersistentCloudKitContainer or CKSyncEngine on the shared database
Your own store, your own merge rules CKSyncEngine
Public, read-mostly content CKDatabase operations on the public database
Unique keys required locally CKSyncEngine, or deduplicate after SwiftData sync

Sources and further reading

Read next