firebase-database Firebase Realtime Database Transactions A distributed counter

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!


Imagine many users all running a web application that is trying to increment a counter in the database. Each user must read the current count, add one and write out the updated value. To make sure no one reads the counter while someone else is is adding one we use a transaction:

  if (value === null) {
    // the counter doesn't exist yet, start at one
    return 1;
  } else if (typeof value === 'number') {
    // increment - the normal case
    return value + 1;
  } else {
    // we can't increment non-numeric values
    console.log('The counter has a non-numeric value: ' + value)
    // letting the callback return undefined cancels the transaction

Got any firebase-database Question?