0

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?

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
Robert Mihai
  • 184
  • 1
  • 9
  • I'm not sure I understand. What do you mean by "consider an optimistic locking by adding a Version field on a document?"? – Alex Mamo Jan 02 '23 at 08:08
  • Like adding a Version field on the document and then in the UPDATE endpoint, you read the document and make a conditional update regarding the Version. 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. You can perform the operation atomically with a transaction, which can do the get, check, and update without conflict with other transactions trying to do the same thing. – Robert Mihai Jan 03 '23 at 07:24
  • So I understand that the only way to avoid data races is to use transactions when using server-side firestore client. – Robert Mihai Jan 03 '23 at 07:26

1 Answers1

2

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.

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193