Reputation: 1988
I understand that Firebase transactions enable the atomic update of some value, given its old value and new value
But given that Firebase is a realtime database, I assume, one must use transactions only sparingly and not in 'realtime features'
here's an example:
I understand that if you are performing some mathematical operation on a value (adding 'likes' or equivalent), it makes sense to use transaction
I dont understand if it makes sense to use transactions in the following use case: Say a text field can be updated by any number of users, and we are interested in all the updates, as they occur in real time. Does firebase recommend we use transaction in this case? Or is the final 'persist operation' that occurs on the value, only limited to a single 'persist operation' per timestamp granularity of the Firebase server clock?
Further is it guaranteed that the events will be delivered in the order of which the final values were persisted?
Upvotes: 24
Views: 13645
Reputation: 599766
Whenever you use transactions on a database, you sacrifice some of your scalability in order to have a stronger data consistency guarantee. Transactions on the Firebase Database are no different, except maybe that developers tend to use Firebase in more highly concurrent situations.
With any transactional system: the key to keeping the system scalable is to minimize the number of clients contending to update the same data. In the case of Firebase, you'd accomplish that by running your transaction as low as possible in your JSON tree. I.e. a counter is a example of something that could work well under a transaction.
For larger pieces of data, such as your text editing example, using a transaction will not scale well. For such use-cases it is better to find a way to avoid the conflict altogether. Quite often this boils down to storing the delta that each user is making, instead of storing the updated state. A great example of this is in the Firepad example, which uses operational transform to create a highly concurrent collaborative editor on top of the Firebase Database.
Upvotes: 24