Three Ticket Twins scratch-off tickets, all No. 41, on a navy field. A finished one labeled iPhone and a half-scratched one labeled iPad feed dotted gold lines into a merged(with:) pill, which points down to a single finished ticket labeled Both devices, above the line a.merged(with: b) == b.merged(with: a)

iCloud Key-Value Store Sync: Merge Rules That Keep Data Safe

NSUbiquitousKeyValueStore will overwrite a good value with a worse one and never tell you. Pure merge functions and five wiring fixes from a game I'm building make it safe for data that matters.

iCloud saved my game. Then it saved an empty one over it.

That’s the App Store review I’m trying not to earn.

I’m building a game called Ticket Twins. It’s Concentration played on a scratch-off ticket. There’s a daily ticket that every player gets the same copy of, a weekly leaderboard built from those dailies, and books of levels that hand out stars. There’s no server and no account. What it needs from sync is small: your stars should survive a new phone, and today’s ticket should count once per player, whether you scratched it on the iPhone or the iPad.

Ticket Twins daily ticket No. 0040 mid-play on an iPad and an iPhone, side by side. The cream scratch-off ticket sits on a red background with gold starbursts. Both show the same four-by-four board with the same spots scratched: cherries, two sevens and a star revealed, the rest still silver foil, and the coin bar at 91 percent.

The same daily ticket on an iPad and an iPhone. Every player gets this board, and it should count once no matter which device it’s finished on.

That’s a few kilobytes of JSON. It doesn’t need CloudKit, a schema, or a production deploy. It needs NSUbiquitousKeyValueStore, which most of us file under “synced UserDefaults for a couple of preferences.”

The trouble is that almost everything written about the key-value store stops at set and synchronize(). That’s enough for a preference. It isn’t enough for anything the user would be upset to lose, because the store will overwrite a good value with a worse one and never tell you. What makes it safe is a set of merge rules you write yourself, plus a handful of guards around the wiring. I’ll go through both, and show the failure behind each guard so you can reproduce it.

What the Key-Value Store Actually Gives You

Apple’s documentation gives you 1 megabyte of total space for values and at most 1,024 keys. A single value can be up to 1 megabyte, which would use the whole quota. Keys can be up to 128 UTF-16 characters and don’t count against the megabyte. If a write would put you over, the write fails and the system posts the change notification with a quota-violation reason.

Writes land in memory first and go to disk later. synchronize() doesn’t push anything. The docs say it “doesn’t force the system to write new keys and values to iCloud,” that iCloud decides when to move data, and that it typically limits updates to several times per minute. Apple’s advice is to call it at launch or when you return to the foreground, and otherwise leave it alone.

Incoming data shows up as didChangeExternallyNotification. The userInfo can carry a list of changed keys and one of four reasons: a server change, an initial sync, a quota violation, or an account change.

Now look at what’s missing.

There’s no merge. Each key holds one whole value, and when two devices have written the same key, one of those values survives. The current docs only say the system “reconciles” local and server values. They don’t promise which one wins, and I wouldn’t bet a save game on a guess.

There’s no completion signal. Nothing tells you “the first download finished and you now have everything.” When you read a key and get nil, that could mean nobody has ever written it. It could also mean the data exists in iCloud and hasn’t reached this device yet. Those two cases look identical.

And there’s no server logic. I’ve been working on another app where a server is the source of truth, and last-writer-wins is fine there because the server sees every write and breaks the ties. Here there’s nobody in the middle. Whatever keeps the data correct has to run on the devices.

Apple’s archived iCloud Design Guide, last updated in 2015, says a little more. When a device writes, iCloud checks whether other devices changed the store recently. If they haven’t, the pending local changes go to the server. If they have, the local values aren’t written, and the app gets the change notification with the server’s values. Right after that comes one sentence that’s easy to read past: if the user is on level 13 on one device and level 1 on another, the device on level 13 “might want to write its changes again.” That’s a merge rule. They just leave it to you.

The Merge Rules Come First

Before any iCloud code existed, I wrote the rules as pure functions in the game’s UI-free package. They take two values and return one. They don’t know about iCloud, files, actors or the clock.

Three keys sync:

Key Value
levels.progress all level bests, as one JSON blob
daily.<ticketNumber> one daily record, for the last 14 tickets only
practice.completed a Bool

Settings like sound and haptics stay on the device. They describe the device, not the player.

Here’s the whole merge file:

extension LevelProgress {
    public func merged(with other: LevelProgress) -> LevelProgress {
        LevelProgress(
            calm: calm.merging(other.calm) { $1.isBetter(than: $0) ? $1 : $0 },
            rush: rush.merging(other.rush) { $1.isBetter(than: $0) ? $1 : $0 }
        )
    }
}

extension DailyRecord {
    public func merged(with other: DailyRecord) -> DailyRecord {
        guard ticketNumber == other.ticketNumber else { return self }
        return other.isPreferred(over: self) ? other : self
    }

    private func isPreferred(over other: DailyRecord) -> Bool {
        if isFinished != other.isFinished { return isFinished }
        if isFinished {
            if session.coinPercent != other.session.coinPercent {
                return session.coinPercent < other.session.coinPercent
            }
        } else {
            if session.hasStarted != other.session.hasStarted { return session.hasStarted }
            if session.coinRemaining != other.session.coinRemaining {
                return session.coinRemaining < other.session.coinRemaining
            }
        }
        return encodedBytes.lexicographicallyPrecedes(other.encodedBytes)
    }

    private var encodedBytes: [UInt8] {
        let encoder = JSONEncoder()
        encoder.outputFormatting = .sortedKeys
        return (try? encoder.encode(self)).map { Array($0) } ?? []
    }
}

In plain words:

Data Rule
Level progress Per level and per mode, keep the better best. A level only one side has is kept.
Daily, one side finished The finished record wins.
Daily, both finished The lower coinPercent wins. A lost ticket counts as 0.
Daily, both unfinished A started ticket beats an unstarted one. Then less coinRemaining wins.
Daily, exact tie The record whose sorted-key JSON sorts first, byte by byte.
Daily, different ticket numbers No merge. Keep self.
Practice flag Logical OR.

Level progress is the easy one. isBetter already existed for recording a new best (more stars, then more coin left, then less time), so the merge is a dictionary union that asks the same question per level.

The daily rules took real product decisions. coinPercent is how much of your coin is left when the ticket ends, and higher is better. So “lower wins” looks backwards until you remember the daily is one attempt per player. If you finish today’s ticket on the phone and then play it again on the iPad already knowing where the pairs are, the second run can’t be allowed to raise your score. The worse result is the honest one.

Ticket Twins result card for daily ticket No. 0040 reading Ticket cleared, with 74 percent Coin and a time of 0:49 above a four-by-four grid of spots: fourteen green Clean checks and two yellow Peeked spots.

The Coin figure on the result screen is coinPercent. If this ticket was finished on two devices, the merge keeps the record with the lower number.

The last line of isPreferred is the one people skip. Without it, two different records that tie on every rule would each prefer themselves. Device A keeps A and writes it. Device B keeps B and writes it. They’d trade writes forever. Comparing encoded bytes is arbitrary, and that’s fine. It only has to be the same answer on both devices. .sortedKeys matters for that, because without it the encoder doesn’t promise a key order and the bytes wouldn’t be comparable.

I need two things from these functions. Merging has to give the same answer in either order, and merging a value with itself has to change nothing. With those, it doesn’t matter which device syncs first or how many times a value bounces around. Everyone ends up in the same place.

The tests are Swift Testing, and most of them check both orders in one go. It’s the same habit as testing Table Ready’s lesson copy against its engine: if a rule matters, a test should fail when it changes.

@Test func progressMergeKeepsBetterPerLevel() {
    let a = progress(calm: [(1, 8), (2, 0)])
    let b = progress(calm: [(1, 0), (3, 12)])
    #expect(stars(a, 1)! < stars(b, 1)!)
    for merged in [a.merged(with: b), b.merged(with: a)] {
        #expect(stars(merged, 1) == stars(b, 1))
        #expect(stars(merged, 2) == stars(a, 2))
        #expect(stars(merged, 3) == stars(b, 3))
    }
    #expect(a.merged(with: b) == b.merged(with: a))
}

@Test func finishedDailyMergeIsCommutativeAndKeepsLower() {
    let high = wonDaily(mismatches: 0)
    let low = wonDaily(mismatches: 4)
    #expect(high.session.coinPercent > low.session.coinPercent)
    #expect(high.merged(with: low) == low)
    #expect(low.merged(with: high) == low)
}

@Test func exactTieIsDeterministic() {
    let a = wonDaily(mismatches: 1)
    var other = dailySession()
    LevelPlay.mismatch(&other)
    _ = other.addElapsed(5)
    let symbols = other.board.symbols
    for symbol in Set(symbols).sorted() {
        for spot in symbols.indices where symbols[spot] == symbol { LevelPlay.reveal(&other, spot) }
        _ = other.finishResolution()
    }
    let b = DailyRecord(ticketNumber: 7, session: other)
    #expect(a.session.coinPercent == b.session.coinPercent)
    #expect(a != b)
    #expect(a.merged(with: b) == b.merged(with: a))
    #expect(a.merged(with: a) == a)
}

The helpers build real sessions by playing them, so the tests break if scoring changes. The tie test makes two finished records with the same coinPercent and five seconds of difference in elapsed time, then checks that both orders agree.

One more test in that suite has nothing to do with merging. It takes a 6×6 level from the level catalog (36 cells, the biggest grid in the game), plays it to the end, wraps the session in a DailyRecord, and expects the encoding to stay under 32 KB. Fourteen dailies plus progress has to fit in one megabyte with room to spare, and I’d rather a test tell me than a quota notification.

The Wiring

CloudSync is a @MainActor @Observable class. It never touches NSUbiquitousKeyValueStore directly. It talks to this:

@MainActor
protocol KeyValueStoring: AnyObject {
    func data(forKey key: String) -> Data?
    func bool(forKey key: String) -> Bool
    func set(_ data: Data, forKey key: String)
    func set(_ value: Bool, forKey key: String)
    func removeObject(forKey key: String)
    var allKeys: [String] { get }
    @discardableResult func synchronize() -> Bool
    func externalChangeNotifications() -> NotificationCenter.Notifications?
}

The real adapter forwards every call to NSUbiquitousKeyValueStore.default. InMemoryKeyValueStore is a dictionary. In tests, two CloudSync instances with their own local stores share one in-memory store, and that’s two devices on one iCloud account. No test ever touches real iCloud.

Every remote read goes through one small enum:

private enum Remote<Value> {
    case absent
    case unreadable
    case value(Value)
}

A key with no data is .absent. Data that won’t decode is .unreadable, and that includes a blob from a newer version of the app, because the models throw on a schema version they don’t know. Those two cases get very different treatment, and you can see it in the progress pull:

private func pullProgress() -> Bool {
    let local = progressStore.load()
    switch remoteProgress() {
    case .unreadable:
        return false
    case .absent:
        if local != LevelProgress() { write(local, forKey: Self.progressKey) }
        return false
    case .value(let remote):
        let merged = local.merged(with: remote)
        if merged != remote { write(merged, forKey: Self.progressKey) }
        guard merged != local else { return false }
        do {
            try progressStore.save(merged)
            return true
        } catch {
            logger.error("Could not save merged progress: \(error.localizedDescription, privacy: .public)")
            return false
        }
    }
}

An unreadable value is never written over. If an old build can’t read what a new build wrote, the old build should leave it alone. The push side follows the same rule, so an old build simply stops syncing that key until it’s updated. That’s the right trade.

When there is a value, the code merges, and then it only writes each side if the merge changed that side. If the remote already equals the merge, nothing goes up. If local already equals the merge, nothing gets saved and the UI isn’t told to refresh. A pull that changes local data bumps a revision counter, and the views reload off that.

Sync runs in three places. start() runs once at launch. pullAll() runs every time the app becomes active. And local saves go through small decorator stores that write the file first and then push that one key. The game’s models don’t know sync exists.

That was the first version, and the two-device tests passed. Then I did a hardening pass and found five ways it could still go wrong.

Fix 1: The Empty Write

This is the one from the top of the post.

Install the game on a new phone, signed into an iCloud account that already has your progress. Launch it. The app calls synchronize() and pulls right away. The first download from iCloud hasn’t landed yet, so levels.progress reads as absent. Local progress is empty too, because the app was installed thirty seconds ago.

The first version handled absent the obvious way: remote doesn’t have it, so push what I have. What it had was an empty LevelProgress. Now there are two values for that key. One is on the server and holds every star you’ve earned. The other is on the new phone, holds nothing, and is the most recent write.

If your old device is still around, the merge rules fix this. The empty value arrives there, gets merged with the real one, and the real one goes back up. But the case this feature exists for is the one where the old device is gone: a trade-in, or a delete and reinstall. Then iCloud’s copy is the only copy, and I’ve just put a newer, emptier write in front of it and left the outcome to “reconciles.”

The archived design guide doesn’t make that look any better. Its recency check only holds back a local write when another device changed the store recently. Progress written long ago on an old phone isn’t a recent change, so by Apple’s old description, the new phone’s empty write is the one that goes through. That’s an old document, not a promise about how the store behaves today. But it’s not the answer I want here, so I’m not leaving it to chance.

The fix is one condition, in both the pull and the push:

case .absent:
    if progress != LevelProgress() { write(progress, forKey: Self.progressKey) }

An empty value carries no information, so it never gets written. The other two keys already had this by their shape. A daily is only pushed if a record exists, and the practice flag only ever writes true.

@Test func emptyDeviceLeavesRemoteProgressAbsent() throws {
    let remote = InMemoryKeyValueStore()
    let device = try makeDevice(remote: remote)

    device.sync.pullAll()
    device.sync.push(progress: LevelProgress())

    #expect(remote.data(forKey: "levels.progress") == nil)
}

The general version: absent might mean “not downloaded yet,” so never answer it with a value that says nothing.

Fix 2: Subscribe Before You Sync

Same new phone, same first launch. The first version of start() called its observe method before synchronize(), so in the source it looked like the subscription came first. But that method created the notifications(named:) sequence inside a Task { }, and the body of that Task doesn’t run until start() returns. By then synchronize() had been called and the pull had already found nothing. So in practice the app subscribed after the first sync. If the initial-sync notification was posted in that gap, nobody was listening for it. The data was sitting in the store and the app kept showing an empty game until something else triggered a pull.

Apple’s old sample code registers the observer and then calls synchronize(), in that order. The current docs say to register “shortly after launch.” So now start() creates the sequence synchronously, at the top, before synchronize(), and hands it to observe() at the end:

func start() {
    guard !hasStarted else { return }
    hasStarted = true
    let notifications = keyValueStore.externalChangeNotifications()
    keyValueStore.synchronize()
    pullAll()
    if let notifications { observe(notifications) }
}

That one applies outside sync too. A call that comes first in the source isn’t first if its work is inside a Task.

The handler maps the four reasons onto two kinds of work:

private func handle(userInfo: [AnyHashable: Any]?) {
    let reason = userInfo?[NSUbiquitousKeyValueStoreChangeReasonKey] as? Int
    let keys = userInfo?[NSUbiquitousKeyValueStoreChangedKeysKey] as? [String] ?? []
    switch reason {
    case NSUbiquitousKeyValueStoreServerChange:
        handleExternalChange(.keys(keys))
    case NSUbiquitousKeyValueStoreInitialSyncChange, NSUbiquitousKeyValueStoreAccountChange:
        handleExternalChange(.everything)
    case NSUbiquitousKeyValueStoreQuotaViolationChange:
        logger.error("iCloud key-value quota exceeded")
    default:
        break
    }
}

A server change pulls only the keys it names. An initial sync or an account change pulls everything.

I’ll be straight about the limits of this one. It’s the only fix here without a unit test, because the in-memory store returns nil for notifications and there’s nothing to race against. And notifications(named:) returns an async sequence, and Apple doesn’t document whether the observer attaches when the sequence is created or when the loop starts iterating. The order in start() is as early as I can ask. I don’t treat it as a guarantee. The pull on every foreground is the backstop, and it’s the reason a missed notification costs a delay and not data.

Fix 3: The Ticket Number Has to Match the Key

A daily record carries its own ticketNumber. The key carries one too: daily.41 should hold ticket 41. The first version trusted that.

Put ticket 40’s record under daily.41 and follow the pull for ticket 41. The device has no local record for 41 yet, so this line takes the remote value as is:

let merged = local?.merged(with: remote) ?? remote

Then it saves it. The file store names files by the record’s own ticket number, so the save lands on ticket 40’s file. Whatever this device had for ticket 40 is replaced without going through a single merge rule. A worse result can replace a better one, or an unfinished ticket can replace a finished one. The merge function’s own guard doesn’t help, because with no local record the merge never runs.

How would a record end up under the wrong key? A bug in some future build is enough. The store is shared by every version of the app the player has installed on any device, so I don’t trust what I read from it.

The fix treats a mismatch like any other value that can’t be trusted:

private func remoteDaily(_ key: String) -> Remote<DailyRecord> {
    let remote = decode(DailyRecord.self, key: key)
    if case .value(let record) = remote, record.ticketNumber != Self.dailyNumber(in: key) {
        logger.error("Ignoring remote \(key, privacy: .public) with mismatched ticket number")
        return .unreadable
    }
    return remote
}
@Test func mismatchedRemoteDailyIsIgnored() throws {
    let remote = InMemoryKeyValueStore()
    let device = try makeDevice(remote: remote)
    let other = finished(today - 1)
    let data = try JSONEncoder().encode(other)
    remote.set(data, forKey: "daily.\(today)")

    device.sync.pullAll()
    device.sync.handleExternalChange(.keys(["daily.\(today)"]))

    #expect(device.daily.load(ticketNumber: today) == nil)
    #expect(device.daily.load(ticketNumber: today - 1) == nil)
    #expect(remote.data(forKey: "daily.\(today)") == data)
    #expect(device.sync.revision == 0)
}

Nothing is saved for either day, the remote value is left where it is, and the UI isn’t told anything changed. The cost is that the key stays stuck until it ages out of the window. I’ll take a stuck key over a wrong record.

Fix 4: A Grace Day on the Prune

Only the last 14 dailies sync. That covers any leaderboard week and keeps the store far from its quota. On every pull, remote daily keys older than the window get removed. Local files are never deleted by sync.

The window is counted back from today’s ticket number, and today’s ticket number comes from the device’s local calendar. Two devices on the same account don’t always agree on what day it is. Take the phone on a trip and leave the iPad at home, and for part of every day they’re one ticket apart.

Say the phone is on ticket 41 and the iPad is still on ticket 40. The iPad’s window starts at 27. The phone’s starts at 28.

The iPad has a file for ticket 27, sees no daily.27 in the store, and pushes it. The phone gets the change. Ticket 27 is older than the phone’s window, so the first version removed it. The iPad gets that change, sees the key is absent again, and pushes it again. The phone removes it again. Each device is doing exactly what I told it to, and they trade a write and a delete for as long as both are awake. Nothing is lost locally. But it’s constant churn against a store that iCloud throttles to a few updates a minute, and it’s the kind of thing you’d never see with one test device on your desk.

The fix moves the prune line back one ticket:

private var pruneThreshold: Int {
    windowStart - 1
}

private func pruneRemoteDailies() {
    let threshold = pruneThreshold
    for key in keyValueStore.allKeys {
        if let number = Self.dailyNumber(in: key), number < threshold {
            keyValueStore.removeObject(forKey: key)
        }
    }
}

A key one ticket older than this device’s window is somebody else’s business. This device doesn’t pull it and doesn’t delete it. The same check guards the per-key path in handleExternalChange.

@Test func edgeKeyIsNotPrunedWithinGrace() throws {
    let remote = InMemoryKeyValueStore()
    let device = try makeDevice(remote: remote)
    let windowStart = today - 13
    try seed(remote, daily: finished(windowStart - 1))
    try seed(remote, daily: finished(windowStart - 2))

    device.sync.pullAll()

    #expect(remote.data(forKey: "daily.\(windowStart - 1)") != nil)
    #expect(remote.data(forKey: "daily.\(windowStart - 2)") == nil)
}

The clock and the time zone are injected into CloudSync as closures, so the test pins “today” and the window math is exact. The other direction needed no fix. A key from tomorrow isn’t in the window and isn’t below the threshold, so the device that’s behind ignores it until its own midnight.

Fix 5: The Open Ticket That Saved Over a Finished One

This one is my favorite, because the remote copy was right the whole time.

You open today’s ticket on the iPad and leave it sitting there. Then you finish the same ticket on your phone. A minute later the finished record reaches the iPad. CloudSync merges it and writes it to the iPad’s file. Finished beats unfinished, so that’s correct.

But the ticket is still open on the iPad’s screen. I don’t swap a board out from under someone mid-scratch, so the open ticket keeps its in-memory session. Now you scratch one more spot. The ticket saves, and the save writes an unfinished record straight over the finished file.

The push that follows does the right thing. It merges with the remote, sees the remote is already the finished record, and writes nothing. So iCloud is correct and the iPad’s own file is wrong. It gets worse if you play the iPad ticket to the end and do better than you did on the phone. The local file now holds the higher result, and the weekly score is computed from local files. That’s the “replay it on a second device” case the merge rules were written to block, coming in through the local save path.

The fix lives in the decorator, not in CloudSync:

struct SyncedDailyRecordStore: DailyRecordStoring {
    let base: any DailyRecordStoring
    let push: @MainActor @Sendable (DailyRecord) -> Void

    func load(ticketNumber: Int) -> DailyRecord? {
        base.load(ticketNumber: ticketNumber)
    }

    func save(_ record: DailyRecord) throws {
        var kept = record
        if let existing = base.load(ticketNumber: record.ticketNumber), existing.isFinished {
            kept = record.merged(with: existing)
        }
        try base.save(kept)
        MainActor.assumeIsolated { push(kept) }
    }
}

Once a finished record is on disk, every later save for that ticket goes through the merge. It only does this when the existing record is finished. During normal play the newer save should simply win, and I don’t want two unfinished saves that tie on coin to be settled by the byte comparison.

The test walks the whole story:

@Test func openTicketSaveKeepsPulledFinishedRecord() throws {
    let remote = InMemoryKeyValueStore()
    let device = try makeDevice(remote: remote)
    let sync = device.sync
    let store = SyncedDailyRecordStore(base: device.daily, push: { sync.push(daily: $0) })
    let remoteFinished = finished(today, mismatches: 4)
    try seed(remote, daily: remoteFinished)
    sync.pullAll()
    #expect(device.daily.load(ticketNumber: today) == remoteFinished)
    let week = DateInterval(start: DailyCalendar.utcNoon(ofTicket: today - 3), end: DailyCalendar.utcNoon(ofTicket: today + 3))
    let before = WeeklyLeaderboard.score(in: week, store: store)

    let ticket = DailyTicket.make(number: today)
    let open = DailyRecord(ticketNumber: today, session: TicketSession(board: ticket.board, rules: ticket.rules))
    try store.save(open)
    #expect(device.daily.load(ticketNumber: today) == remoteFinished)

    let other = finished(today)
    try store.save(other)
    let preferred = other.merged(with: remoteFinished)
    #expect(device.daily.load(ticketNumber: today) == preferred)
    #expect(remoteDaily(remote, today) == preferred)
    #expect(preferred.session.coinPercent <= remoteFinished.session.coinPercent)
    #expect(WeeklyLeaderboard.score(in: week, store: store) <= before)
}

A finished record comes down. An open ticket saves and the file doesn’t change. A second finished attempt saves, the file and the remote both hold whichever one the rules prefer, and the weekly score didn’t go up.

What I took from it: merge rules that only run during sync aren’t enough. Every write to synced data has to go through them, and that includes the local save.

The Short Version

If you’re putting anything that matters in the key-value store, here’s the list I’d work from.

  • Write the merge as a pure function first. Test both argument orders and test a value against itself.
  • End every rule chain with a tie-break that’s the same on every device, even an arbitrary one.
  • Treat a missing key as “unknown,” not “empty.” Never push a value that carries no information.
  • Tell absent apart from unreadable, and never write over something you can’t read.
  • Check that a value belongs under the key you found it in.
  • Only write when the merge is different from what’s already there.
  • Create the change-notification sequence before the first synchronize(), not inside a Task, and pull on every foreground anyway.
  • If you prune by date, leave a margin for devices that disagree about the date.
  • Run local saves through the same rules once remote data can land in local storage.
  • Bound your sizes with a test.
  • Put the store behind a protocol so two fake devices can share one dictionary.

When to Move Up to CloudKit

This approach has limits, and they’re worth knowing.

Everything here only moves forward. A best gets better, a ticket gets finished, a flag turns on. That’s why the merges are so short. It also means I can’t express a delete. If I ever add a Reset Progress button, these rules will happily bring every star back from the other device. Supporting that means tombstones and timestamps, and at that point I’d be rebuilding a database on top of a dictionary.

So I’d move to CloudKit when the data stops fitting that shape. That means history that keeps growing instead of a 14-day window. It means deletes that have to stick. It means anything shared between people, or anything where I need to show the user whether sync actually worked, because the key-value store won’t tell me. And I’d move well before the megabyte gets close.

CloudKit isn’t free either. PushTo100 syncs through it, and getting that reliable meant building my own upload-first, conflict-aware sync engine on top of CloudKit. I wrote up what that took in 72 Syncs and Counting.

For a few kilobytes of progress that only ever improves, the key-value store plus a page of merge rules is the right size. I still haven’t watched all of this run across two real devices in two time zones. The tests prove the rules and the wiring. They don’t prove Apple’s timing, and that part only shows up on hardware.

When it works, the new phone just has your stars on it, and nobody thinks about why.

Thanks for reading.

Stay in the loop

Deep dives on Swift, SwiftUI, and building real apps — from the code to the App Store. No fluff, no toy projects.