I'm using a Cloud Function that performs the following steps:
This is the code I'm using:
exports.syncItems = functions.https.onRequest((request, response) => {
sync('url', 'colName').then(() => {
response.status(200).send('Success!');
}).catch((error) => {
response.status(404).send('Failure!');
});
});
async function sync(url, colName) {
const response = await fetchData(url); // async function
const items = prepareData(response); // not async function
return await importData(colName, items); // async function
}
async function importData(colName, items) {
const colRef = firestore.collection(colName);
const batch = firestore.batch();
items.forEach(item => {
let docId = item.identifier;
let docRef = colRef.doc(`${docId}`);
batch.set(docRef, {
// set data here
});
});
return await batch.commit();
}
Behind the hood accessing Firestore is mediated by AdminSDK.
const admin = require('firebase-admin');
admin.initializeApp({
credential: admin.credential.applicationDefault(),
projectId: 'myProjectId'
});
Data import happens very fast when using Firebase emulators. Firestore shows the collection and the associated documents almost instantly.
Instead, when deploying syncItems
Google Cloud Function to Firebase I see a delay (even 2/3 minutes).
Is there any possible reason for that?
Performance of Firebase emulator is very different compared to the performance when deployed in Cloud Functions for Firebase. They have different codes and they are running on different computing resources.
Based on the documentation for Cloud Functions for Firebase:
Cloud Functions for Firebase is a serverless framework that lets you automatically run backend code in response to events triggered by Firebase features and HTTPS requests. Your JavaScript or TypeScript code is stored in Google's cloud and runs in a managed environment. There's no need to manage and scale your own servers.
Since Cloud Function is serverless, it is prone to cold starts. It is also scalable so that your data can be distributed across. Firebase emulator only loads the resources needed when testing your project. When you deploy it to Cloud Functions, the factors that I mentioned above take place.
You can check the documentation below on best practices for designing, implementing, testing, and deploying Cloud Functions:
Let me know if you have questions or clarifications.