firebase / functions-samples

Collection of sample apps showcasing popular use cases using Cloud Functions for Firebase
https://firebase.google.com/docs/functions
Apache License 2.0
12.03k stars 3.83k forks source link

Revise email-users example to handle multiple function executions for a single user #105

Open theolof opened 7 years ago

theolof commented 7 years ago

I'm using the code from the sample here: https://github.com/firebase/functions-samples/tree/master/quickstarts/email-users

onCreate is sometimes triggered multiple times for the same user. Most of the time it is triggered once, but sometimes it is triggered two times or even 7 times (which happened yesterday). exports.sendWelcomeEmail = functions.auth.user().onCreate(event => {

No errors in the log, just the normal debug statements and the text output from console.log('New welcome email sent to:', email);

If I choose "View all from this execution", all 7 are shown, so they come from the same execution.

7 emails are also sent, so it's not just the debug output.

Only 1 account is created.

katowulf commented 7 years ago

@theolof could you post this on Stack Overflow (feel free to ping this thread with a link) or file a bug? All issues in this repo should be relevant to the samples and must follow the issue template.

theolof commented 7 years ago

sure, thanks.

brianchirls commented 5 years ago

According to Firebase engineer @laurenzlong, multiple executions is expected behavior and functions should be idempotent. Sending an email is not idempotent.

Can we please have this issue re-opened? It'd be helpful to have the example show how to ensure an email doesn't get sent two or more times.

Thanks.

laurenzlong commented 5 years ago

Reopening, and editing the subject to make it more clear that this issue is about the sample not handling multiple executions.

laurenzlong commented 5 years ago

@theolof and @brianchirls if you have figured out an elegant solution for this, it would be great if you can share by making a PR.

jamieoliveredwards commented 5 years ago

For anyone having a similar issue I found this documentation here for Google Cloud Functions which explains http functions are called at most once and background functions are called at least once.

The solution I found is to just have a standalone http function which can be called by a POST request with the data you want to handle.

Only consideration with this method is CORS, which will send two requests to the function unless you're careful with the content of your POST request. More information is available here.

I appreciate it's not that elegant but due to the nature of Cloud Functions I can't see another way to resolve this.

I'm a newbie here so apologies if any of this is unhelpful!