Search code examples
firebasefirebase-realtime-databasetransactions

Realtime Database Firebase "All or nothing" transactions


Is there a way to manipulate the transactions API in the RTDB for "batch" writes?(We currently can't migrate to Firestore)
Our problem is as follows:
When writing a new "Job" object to the server we are preforming three consecuteve writes:

  1. Writing the location key using the GeoFire API
  2. Writing the job
  3. Connecting the Job ID to the user created it

Unfortunately, if one of the writes fails but a previous one succeeded, it causes major bugs in the system.
We are looking for ways to ensure the completeness, or reverting the operation if one of the writes fails.


Solution

  • If it is just a matter of writing and "ensuring the completeness, or reverting the operation if one of the writes fails", you can use a simultaneous update by using the update() method.

    As detailed in the documentation, "simultaneous updates .... are atomic: either all updates succeed or all updates fail.". See this part of the documentation: https://firebase.google.com/docs/database/web/read-and-write#update_specific_fields

    Note that the Real Time Database also offers the possibility to save data as transactions, see the documentation items here and here. But probably, in your case, using simultaneous updates will be sufficient.