How to ensure fast synchronization between devices using iCloud Database?

For a long time, I've been using just a shared file via iCloud to ensure synchronization between devices. It works very well, everything is synchronized within seconds. However, I started encountering issues with race conditions, especially if there are more than 2 devices updating data. It's easy then to override the database accidentally.

That's why I decided to try with the tool that is designed for that: iCloud Database. However, I quickly realized that the performance was extremely low.

As I understand, the recommended approach to listen to changes in the database is to create a subscription, and I did that. However, during my tests, I discovered that it can take even 10 or more minutes to get that notification. It's unacceptable, some user could be waiting for new changes on their device.

I could of course spam with fetch every 10 seconds (using changeToken), but I'm not sure if it's a good idea. I could also provide manual fetch like pull to refresh or something like that, but automatic synchronization would be much better for the user.

Today suddenly notifications started working extremely fast, within one second or so. This is weird.

I think I figured out what's going on with synchronization. Why it takes so long.

After I migrated to CoreData + CloudKit it turned out that it synchronizes remote changes only after deactivating and activating the app again (my macOS app).

I was able to confirm that the underlying mechanism relies on willBecomeActiveNotification notification. After this notification is received, the synchronization is instant. However, without it, even if the app is in the foreground it may take a long time to synchronize remote changes.

As a workaround, I discovered that sending NotificationCenter.default.post(.init(name: NSApplication.willBecomeActiveNotification)) forces Core Data synchronization. Unfortunately, it's just a workaround, not a reliable solution...

How to ensure fast synchronization between devices using iCloud Database?
 
 
Q