Reputation: 3104
I've setup an Http Cloud Function as backend for a reservation system. This function accesses data from Cloud Firestore retrieving existing time of reservation and to check if the reservation has overlaps from the existing times. This would be no problem if only one concurrent instance of the request can be triggered, however I've noticed that when requesting to the same function from multiple sources at the same time, the function would run those multiple request in a somewhat parallel way based on my log.
Here is a snippet of my function below:
exports = module.exports = functions.https.onCall(async (data, context) => {
const { stand_id, user_id, reservation } = data;
const isReservationValid = await checkAvailability(reservation, stand_id);
if (!isReservationValid) {
throw new functions.https.HttpsError('aborted', 'Errr');
}
return await createReservation(stand_id, user_id, reservation);
});
The problem arises if I call this function and pass in the same stand_id, and overlapping reservation times, I've noticed that the function wouldn't wait for the whichever is the first function to get invoked to finish before starting the subsequent requests.
Is there a way I can solve this problem better? Or any workaround?
Or did I just misunderstood the documentation below?:
Upvotes: 2
Views: 4494
Reputation: 317487
You can't arrange for only once function to be invoked at a time. You should expect that Cloud Functions will scale up multiple server instances to handle load, then scale them down when they're no longer needed. This is an important feature of Cloud Functions, since the system absolutely needs to scale under load.
The documentation you're referring to is saying that a single Cloud Functions instance can only handle one request at a time. But you need to first read and understand the first paragraph in that section, as this behavior will never change:
Cloud Functions may start multiple function instances to scale your function up to meet the current load. These instances run in parallel, which results in having more than one parallel function execution.
If your functions need to write to Firestore in your function, and those functions might be writing to the same document, you need to use a transaction to make sure each of those updates do not overwrite each other in a way that causes data loss.
Upvotes: 5