'Get and increment in Firebase Realtime

I'm making a Firebase function, that is supposed to get the value of a field in the Realtime Database, write the value in a Firestore Document and increment the original field. The problem is when the function gets called very frequently e.g. 500 times a second, it gets and writes the same value in a lot of documents, because many executions will get the same value before it gets incremented. Is there any way to get the value of a Realtime DB field and increment it at the same time or somehow prevent this issue? Thank you in advance.

My code:

const { getFirestore } = require('firebase-admin/firestore');
const { getDatabase, ServerValue } = require('firebase-admin/database');

const rb = getDatabase();
const db = getFirestore();

exports.increment = functions.https.onCall(async (data, context) => {
    rb.ref('count').get().then((snapshot)=>{
        let value = snapshot.val();
        db.collection("documents").doc(value.toString()).set({count:value});
        rb.ref("count").set(ServerValue.increment(1))
    })
});


Solution 1:[1]

Since you're using an auto-scaling infrastructure with Cloud Functions, it will spin up new instances if there are a lot of requests coming in. If you don't want to do that, it might be worth setting a maximum number of instances on your Cloud Function.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Frank van Puffelen