skip to Main Content

I am considering using Mongodb-realm to sync data to native clients (flutter). Imaging two clients (C1, C2) that see document A and sync remote changes using websockets which are asynchronous. What happens if client C1 triggers an update and before client C2 is informed and updated, then C2 triggers an update at its own. Which version ends up in the MongoDB cluster and how is the client C2 informed on the collision

2

Answers


  1. MongoDB Realm writes are transactional (Swift version) and either all of the operations within the transaction passes or it all fails. Transactions are also blocking within the device so it’s best to avoid opening them on multiple threads.

    For clarity, in a multi-user situation, the rule of thumb is "last writes wins" if a single field is being updated by multiple clients. Along with "deletes always win" – if one users deletes an object – it’s going to be deleted.

    Otherwise, a document can be updated by multiple clients and those changes will not affect each other if they are on different fields. That will depend on your implementation.

    In the case presented in the question, (for single device) the write from C2 would fail since the write from C1 is in progress. If C1 and C2 are two different users, the data would be in the state of the last writer, or merged per above.

    How C2 is notified depends on the SDK but generally speaking, there’s an error handler that is called and passed in the error.

    In Swift for example, set up an error handler singleton that looks like this

    let app = App(id: YOUR_APP_SERVICES_APP_ID)
    app.syncManager.errorHandler = { error, session in
        // handle error
    }
    

    The implementation will vary from platform to platform but the concept is the same. Refer to your associated SDK for examples.

    Here’s a list of Sync Errors for reference

    Login or Signup to reply.
  2. Atlas Device Sync uses operational transform to merge changes coming from different clients. The rules for conflicting writes on the same field are "last write wins", meaning that if both C1 and C2 update A.B, the one who did it last will win and the state across both clients and the server will converge to that value.

    That being said, if they update different fields (e.g. A.B and A.C), those changes don’t conflict with each other and the final document will contain changes from both clients.

    As a final note, the rules for collections are slightly more complex as there are more operations to take into account – e.g. if both clients add elements to a list, the final list will contain all elements.

    You can read more on the conflict resolution rules in the docs.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search