mikemags1
mikemags1

Reputation: 867

Why does my function parameter evaluate to different values during a Firebase Transaction?

In my firebase cloud functions code :

return num_picks_ref.transaction(function(cur_num_picks) {
  console.log(`cur_num_picks: ${cur_num_picks}`)
  console.log(`cur_num_picks <= 0: ${cur_num_picks <= 0}`)
  if (cur_num_picks <= 0) { 
      console.error(`user ${uid} is submitting picks too fast, reached negative pick balance.`)
    }
  return cur_num_picks - 1
})

Then in the output logs, I get :

12:46:35.519 PM ---- db_positions_decrementPickCount ---- cur_num_picks: 87
12:46:35.420 PM ---- db_positions_decrementPickCount ---- user KtY8U5e1p8MCJDOFW2eEuLW5DO83 is submitting picks too fast, reached negative pick balance.    
12:46:35.416 PM ---- db_positions_decrementPickCount ---- cur_num_picks: null

I understand that transactions can be called multiple times to guarantee atomic writes, but this is the only code modifying cur_num_picks in the environment. Nowhere else is modifying that value in the realtime DB.

It seems the functions are not run in the order specified which does not make sense to me.

Most importantly, cur_num_picks evaluates to 87 in the first line, but not 87 again in the next line. How can this be?

Upvotes: 0

Views: 25

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317760

Your observation about the order of execution of functions is correct - Cloud Functions gives you no guarantee about the order. This is because Cloud Functions needs to be scalable and run your functions on multiple server instances. The moment you start running functions in parallel like this, order can not be guaranteed (there is too much non-deterministic latency between all the systems involved). Your code needs to deal with this fact.

Your second observation about the value of cur_num_picks is completely unrelated. With transactions, you need to expect that the first value you receive to the function could be null. You code should handle this case. Read more about that here.

Upvotes: 0

Related Questions