How can I use a transaction while performing a multi-location update in Firebase?

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.


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