Skip to content Skip to sidebar Skip to footer

Reasons For Using Transactions In Firebase Database Over Normal Writes

The Firebase documentation states that transactions are used in scenarios where a field might be needed to update frequently(Like a counter,for example.) But I don't get the point,

Solution 1:

Imagine a situation where two clients are both trying to update some count in the database at the same time. We'll call them Client A and Client B. Their behavior is ordered like this:

  1. Client A reads a count with value 1
  2. Client B reads a count with value 1
  3. Client A wants to increment the count. It writes a count of 1+1=2 back to the database.
  4. Client B wants to increment the count. It writes a count of 1+1=2 back to the database.

In this situation, the count should be 3, but instead a value a of 2 remains in the database. The count is obviously wrong now, and a transaction would have prevented the problem by forcing the writes in a particular order, and forcing the second client to re-read the count after the first client updated it. This means one of the clients updates from 1 to 2, and the second client updates from 2 to 3. Using a transaction is the only way to ensure correctness in this situation.

Post a Comment for "Reasons For Using Transactions In Firebase Database Over Normal Writes"