Search code examples
firebasegoogle-cloud-platformgoogle-cloud-firestoretransactionsoptimistic-locking

Is optimistic locking an option when using a server-side firestore client?


So if you read the docs here, which says that:

The server client libraries (C#, Go, Java, Node.js, PHP, Python, Ruby) use pessimistic concurrency controls to resolve data contention.

What I don't get, is the use case where I would use a Firestore client on the server side and implement an UPDATE endpoint. To avoid data races on this endpoint, we can use a Firestore transaction but can I also implement/consider an optimistic locking by adding a Version field on a document?


Solution

  • I've found it's not possible with Firestore to do this in a single operation like a SQL "update where" statement. Instead, you will have to get the document, check the value, then update the value if the condition is met.

    Yes, that's correct. You cannot perform such an operation in a single go. You have to perform the search, and once you receive the documents, you can then update them.

    So I understand that the only way to avoid data races is to use transactions when using a server-side Firestore client.

    That's also correct. So when it comes to atomically updating Firestore documents in a multi-user environment, then indeed a transaction is required. But take into consideration that a transaction requires a round trip to the server, meaning that you are first reading the document and then updating it. If you however want to update a numeric field type, no matter what the value on the server is, for example, a counter, then you should also take into consideration using FieldValue.increment(n), which is also an atomic operation, which requires only a single write.