Firebase transactions via REST API

I find transactions ( https://www.firebase.com/docs/transactions.html ) a great way to handle concurrency, however it seems they can only be done from clients.

We use Firebase mainly by recording data from our servers and monitoring them on clients. Is there a way to achieve an optimistic concurrency model when writing data through the REST API?

Thanks!

+6
source share
3 answers

You can use the update counter to make write operations work similar to transactions. (I will use some pseudo code below, sorry for that, but I did not want to write out the complete REST API for an example.)

For example, if I have an object like this:

{ total: 100, update_counter: 0 } 

And write the rule as follows:

 { ".write": "newData.hasChild('update_counter')", "update_counter": { ".validate": "newData.val() === data.val()+1" } } 

Now I can prevent concurrent changes by simply passing update_counter with each operation. For instance:

 var url = 'https://<INSTANCE>.firebaseio.com/path/to/data.json'; addToTotal(url, 25, function(data) { console.log('new total is '+data.total); }); function addToTotal(url, amount, next) { getCurrentValue(url, function(in) { var data = { total: in.total+amount, update_counter: in.update_counter+1 }; setCurrentValue(ref, data, next, addToTotal.bind(null, ref, amount, next)); }); } function getCurrentValue(url, next) { // var data = (results of GET request to the URL) next( data ); } function setCurrentValue(url, data, next, retryMethod) { // set the data with a PUT request to the URL // if the PUT fails with 403 (permission denied) then // we assume there was a concurrent edit and we need // to try our pseudo-transaction again // we have to make some assumptions that permission_denied does not // occur for any other reasons, so we might want some extra checking, fallbacks, // or a max number of retries here // var statusCode = (server response code to PUT request) if( statusCode === 403 ) { retryMethod(); } else { next(data); } } 
+13
source

FYI, Firebase Realtime Database officially supports this now.

Read the blog and docs for more information.

+3
source

check out the Firebase-Transactions project: https://github.com/vacuumlabs/firebase-transactions

I believe that this can be very convenient for your business, especially if you make a lot of records from the server.

(disclaimer: I am one of the authors)

+2
source

All Articles