Search code examples
javascriptfirebasegoogle-cloud-functionsrace-condition

prevent race condition in firebase cloud functions


I build firebase cloud function with global variable that increment the answer into object. the issue is that I'm looking a way to prevent condition, when same users try to increment the variable in same time.

 const functions = require('firebase-functions');


// global variable 
let answers = {'a':0, 'b':0,'c':0}

exports.tryGetCount = functions.https.onRequest((req, res) => {
    // console.log(req.body)
    let userAnswer = req.body.answer;
    let userInformation = req.body.userInfo;
    if(answers.hasOwnProperty(userAnswer)){
        answers[userAnswer]++; // increment the answer 
        return res.send({answers:answers})
    }
    return res.status(400).json({error:'invalid answer propertu'})




});

Solution

  • -- Instead of using a global variable, make use of transaction

    https://firebase.google.com/docs/database/web/read-and-write#save_data_as_transactions

    var ref = new Firebase('xxx');
    
    var countRef = ref.child("ans").child("-KGb1Ls-gEErWbAMMnZC").child('count');
    
    countRef.transaction(function(currentCount) {
       return currentCount + 1;
    });