I'm using Firebase Functions with https triggers, and I was wondering how long after sending the response to the client, the functions keeps executing. I want to send a response to the client and then perform another operation (send a mail). Currently I'm doing this as following:
module.exports.doSomeJob = functions.https.onRequest((req, res) => { doSomeAsyncJob() .then(() => { res.send("Ok"); }) .then(() => { emailSender.sendEmail(); }) .catch(...); });
The above code is working for me, but I'm suspecting that the code only works because sending the mail has finished before the res.send has completed, so I was wondering how exactly the termination process is working to make sure the code will not break.
Note: Several of the recommendations in this document center around what is known as a cold start. Functions are stateless, and the execution environment is often initialized from scratch, which is called a cold start. Cold starts can take significant amounts of time to complete.
You should expect that the HTTP function terminates the moment after you send the response. Any other behavior is some combination of luck or a race condition. Don't write code that depends on luck.
If you need to send a response to the client before the work is fully complete, you will need to kick off a second function to continue where the HTTP function left off. It's common to use a pub/sub function to do with. Have the HTTP function send a pub/sub message to another function, then terminate the HTTP function (by sending a response) only after the message is sent.
If the expected response is not pegged to the outcome of the execution, then you can use
module.exports.doSomeJob = functions.https.onRequest((req, res) => { res.write('SUCCESS') return doSomeAsyncJob() .then(() => { emailSender.sendEmail(); }) .then(() => { res.end(); }) .catch(...); });
This sends back a response a soon as a request is received, but keeps the function running until res.end()
is called Your client can end the connection as soon as a response is received back, but the cloud function will keep running in the background Not sure if this helps, but it might be a workaround where the client needs a response within a very limited time, considering that executing pub/sub requires some extra processing on its own and takes time to execute
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With