Avoiding deletion of referenced records

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 referencing Author #42
  • device B uploads a new Article referencing Author #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:

  1. 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.

  2. Always adding a new child record to the Author whenever a reference is made. We could call it ReferenceToken. Since child records may not become dangling, CloudKit would stop a deletion, if a new ReferenceToken sets the parent reference to the Author.

Are there any better ways doing this?

Avoiding deletion of referenced records
 
 
Q