Document ID Conflict Resolution

There is a well known conflict resolution system for the contents of document synced between couchbase server and couchbase lite. This is not about that.

Imagine this scenario: one instance of couchbase lite creates a document (along with a meta().id) and saves it locally, waiting to sync to the server when opportunity arises (maybe in an area of poor internet connectivity). Another, completely different instance of couchbase lite (different phone) creates a document (completely different) but with the same document meta().id as the first instance.

When both instances try to sync to the server, can the server tell these are two different documents and re-assign an ID to one of them? does the first document synced get overwritten by the second document?

I know this is a scenario which might never happen, but for the sake of being ready for the unexpected, what happens when different documents of the same ID are synced to the server?

No; there is no such thing as changing a document’s ID, since with a different ID it wouldn’t be the same document.

does the first document synced get overwritten by the second document?

When the second client tries to push its doc, the server rejects it due to a conflict. This gets treated just like any other conflict: the client pulls the server revision and asks your conflict handler to resolve them.

If you wanted to rename the document, your app logic could detect this situation and resolve the conflict in favor of the existing revision, but start an asynchronous task to save its current revision under a new document ID.

But it’s best to assign doc IDs such that they won’t collide this way. UUIDs of course are good for that. Or you could base the docID on something unique about the entity the document represents.

my goodness, Jens, your name appears in pretty much every thread I have read on this forum. thanks for being so supportive.

I am using UUID’s currently to avoid the occurrence of that situation. so, just so i understand the gist of your message, in the odd case my scenario plays out, the second CBL instance that tries to sync last will replace the contents of its own document with the contents of the document already in the server?

This scenario is treated just like any other conflict. So by default (if you don’t register a conflict handler) the second device to sync will replace the contents of the document with its own — “last writer wins”. If you don’t want that, you can register a conflict handler which will be given the contents of both revisions and gets to decide what happens.

If you’re using the default UUIDs, the odds of a collision are effectively zero. I can never remember the exact math behind the ‘birthday paradox’, but with about 2^128 possible UUIDs I’m sure it’s more likely that an asteroid will hit the Earth first.

1 Like

Well, my queries are fully satisfied. thank you.