Let's say I have a CloudKit database schema where I have records of type Author
that are referenced by multiple records of type Article
.
I want to delete an Author
record if no Article
is referencing it. Now consider the following conflict:
- device A deleted the last
Article
referencingAuthor #42
- device B uploads a new
Article
referencingAuthor #42
at the same time
The result should be that Author #42
is not deleted after both operations are finished. But both device don't know from each other changes. So either device B
could miss that device A
deleted the author. Or device A
could have missed that a new Article
was uploaded and therefore the Author #42
was deleted right after the upload of device B
.
I though about using a reference count first. But this won't work if the ref count is part of the Author
record. This is because deletions do not use the changeTag
to detect lost updates: If device A found a reference count 0 and decides to delete the Author
, it might miss that device B
incremented the count meanwhile.
I currently see two alternatives:
-
Using a second record that outlives the
Author
to keep the reference count and using an atomic operation to update and delete it. So if the update fails, the delete would fail either. -
Always adding a new child record to the
Author
whenever a reference is made. We could call itReferenceToken
. Since child records may not become dangling, CloudKit would stop a deletion, if a newReferenceToken
sets theparent
reference to theAuthor
.
Are there any better ways doing this?