Sync client-server

Hi, I have implemented Yjs on slate using the slate-yjs library, and I created a customized version of y-websocket to handle JWT authentication.

In my implementation, a Y.Doc is created on client, and information about it are sent to the server.
The server checks if the doc is in cache, otherwise it creates a server-side Y.Doc and populates it with data from an external db.

Problem is that I believe this creates a race condition, so that the empty state from the client actually overwrites the one on the server.

Correct me if I’m wrong, but I believe this is because the Y.Doc on client has been created before the one on the server.

Should I tell the server to prepare a Y.Doc before actually syncing, or is there something I’m missing?

Thank you!

Hi @kappa90,

Yjs documents always converge. So let’s say you create two fresh documents and insert some content in both documents (doc1 inserts ‘a’ into a Y.Text and doc2 inserts ‘b’ into a Y.Text):

ydoc1.getText('my text').insert(0, 'a')
ydoc2.getText('my text').insert(0, 'b')

Then the final document will contain both characters.

But if you are working with a Y.Map, you might overwrite each-others changes:

ydoc1.getMap('my map').set('key', 'a')
ydoc2.getMap('my map').set('key', 'b')

In this case you either end up with content ‘a’ or with content ‘b’.

In any case, an empty state (no changes were applied) can’t overwrite the state of another document.