How can I use a transaction while performing a multi-location update in Firebase?
In my Firebase database, I need two write to two locations at once. I have rules for both locations that ensure that a user can't write there without simultaneously writing to the other location.
The write to one of these locations needs to be an increment/decrement. Of course, that has to be done via a transaction, otherwise I can't guarantee that the user isn't overwriting some other user's simultaneous increment/decrement update to that same node.
The problem is, I can't find any documentation on combining multi-location updates with transactions. Is this just impossible to do?
Solution 1:
No. Transactions function on a single node.
That means that if you want to run a multi-location transaction, you will essentially have to run that transaction at the "lowest level shared node" in the tree. That is hardly ever a good idea.
The alternative would be to secure your multi-location write using server-side security rules. For an example of this, see Is the way the Firebase database quickstart handles counts secure?, which essentially builds a compare-and-set operation using security rules.
Solution 2:
It is now possible to combine multi-path updates with transactions with the introduction of ServerValue.increment()
Example:
Map<String, Object> postLikeUpdate = new HashMap<>();
postLikeUpdate.put("postLikedBy/" + postId + "/" + userId, true);
postLikeUpdate.put("likesCount/" + postId, ServerValue.increment(1));
FirebaseDatabase.getInstance().getReference().updateChildren(postLikeUpdate);
Link to release notes