CodexBloom - Programming Q&A Platform

GCP Cloud Functions Timing Out When Accessing Firestore - 'Deadline Exceeded' Error

๐Ÿ‘€ Views: 411 ๐Ÿ’ฌ Answers: 1 ๐Ÿ“… Created: 2025-06-12
gcp cloud-functions firestore JavaScript

I'm experiencing a frustrating issue with my Google Cloud Function that interacts with Firestore. The function is supposed to trigger upon receiving a Pub/Sub message, process some data, and then update Firestore. However, I'm getting a 'Deadline Exceeded' error, which suggests that my function is timing out before it can complete the Firestore update. Hereโ€™s the relevant portion of my code: ```javascript const functions = require('firebase-functions'); const admin = require('firebase-admin'); admin.initializeApp(); exports.processMessage = functions.pubsub.topic('my-topic').onPublish(async (message) => { const data = message.json; try { // Simulated processing time await new Promise((resolve) => setTimeout(resolve, 8000)); // Simulating 8 seconds of processing await admin.firestore().collection('my-collection').doc(data.id).set(data); console.log('Document written successfully'); } catch (error) { console.error('Error writing document:', error); throw new functions.https.HttpsError('internal', 'Error writing to Firestore'); } }); ``` The default timeout for Cloud Functions is set to 60 seconds, so I know Iโ€™m within that limit. However, I suspect that the issue is related to asynchronous operations, particularly the Firestore write. Iโ€™ve confirmed that Firestore is set up correctly and that the service account has appropriate permissions in the IAM settings. As a test, I removed the Firestore write operation and simply returned a success message after the simulated processing, and that worked fine. This leads me to believe that the Firestore call is the bottleneck. I also tried optimizing my Firestore database structure but didnโ€™t see any significant improvement. Is there a way to ensure that the Firestore operation completes successfully without timing out? Should I be handling this differently, perhaps by batching requests or adjusting the way Iโ€™m managing promises? Any insights or suggestions would be greatly appreciated! Any ideas what could be causing this?