0

Firebase database:

{
  "balance" : 10
}

Application 1 (pseudocode):

if (balance-10 >= 0)
{
    // Application freezes for a few seconds. (Connection/hardware issue or whatever reason)
    balance -= 10;
}

Application 2 (pseudocode):

if (balance-10 >= 0)
{
    // Application is executed without any problems.
    balance -= 10;
}

If both applications start at the same time, the final "balance" value will be "-10" instead of "0".

In MySQL this problem is easy fixed by:

UPDATE `table` SET balance=IF(balance-10>=0, balance-10, balance);

What are the possible solutions for Firebase?

KENdi
  • 7,576
  • 2
  • 16
  • 31
Foreign
  • 385
  • 2
  • 20

1 Answers1

0

This is handled through transactions. Since you don't specify what technology I'm showing the web code:

balanceRef.transaction(function(current) {
  if (current && current > 10) {
    return current - 10;
  }
  return (current || 0);
}

If multiple applications run this code at the same time, one of them will get its transaction rejected and will retry.

Also see:

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • It works perfectly, I also had a problem with the first `doTransation` call, which return `null` and your 2nd url helped me. Thanks. (Java btw) – Foreign Aug 18 '17 at 03:35