I have 2 nodes in my database items
and my_items
.
I have this function that does a multi-path update
, this function deletes an item from items
and adds it to the user’s my_items
:
I secured the my_items
node in a way that you can only write to it if the item exists in items
, otherwise it fails:
private void getItem(String uid, String item_key) {
Map<String, Object> updates = new HashMap<>();
//delete item
updates.put("items/" + item_key, null);
//give the item to the user
updates.put("my_items/" + uid + "/" + item_key, itemObject);
mDatabaseReference.updateChildren(updates);
}
Question (In theory):
- Knowing that Firebase Database handles requests one by one.
If users A,B,C,D called the getItem(..)
function for the same item id
together at the same time:
Does this makes sense:
- lets say A’s request reached the server first and
Succeeds
(now the item was deleted from items
and added to user A at my_items
)
- B:
Fails
(because the item no longer exists in items
, so security rule of my_items
prevents this)
- C:
Fails
(same reason)
- D:
Fails
(same reason)
Is this what would happen ? Or I got this wrong ?
Thanks.
2
Answers
This Firebase Blog post discusses atomic operations. RTDB acts on requests as they arrive. RTDB processes events as they arrive. There is another question that might be relevant Does Firebase always guarantee added events in order?
The Firebase Realtime Database processes (write) operations sequentially. So any previous write operation will have been completed before the next one is processed. That means that any data written by a previous user will indeed be present in the
root
variable in security rules evaluation for later write operations.