Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Activate retry in firebase cloud function programmatically

i'm deploying firebase cloud functions to listen on changes in our firestore via continuous deployment.

I can only find a way to activate retries manually. Which goes contrary to our cd approach.

Looking at the normal gcp cloud functions the retry flag can be given when deploying. But i cannot find a similar option in the firebase-cli or the firebase-functions interface (2.1.0)

Any hints on how to solve this? Carsten

like image 667
Carsten Rietz Avatar asked Jan 26 '23 11:01

Carsten Rietz


2 Answers

You can enable retries in Firebase Functions using GCloud Console, manually by hand. Programmatically retrying trigger-based functions was added in firebase-functions 3.10.0 (see changelog and associated pull request).

Since it's not entirely obvious from the PR or the docs, here's a quick example of the syntax:

export const myFirebaseFunc = functions
  .runWith({
    failurePolicy: {
      retry: {},
    },
    memory: '512MB',
    timeoutSeconds: 60,
  })
  .firestore.document('/path/to/some/doc')
  .onCreate(async (snap, context) => {
   /* do stuff */
 })

At the time of writing this, it looks like the failure policy is simply on or off. Thus, this is equivalent

export const myFirebaseFunc = functions
  .runWith({
    failurePolicy: true,
    memory: '512MB',
    timeoutSeconds: 60,
  })
  .firestore.document('/path/to/some/doc')
  .onCreate(async (snap, context) => {
   /* do stuff */
 })

Some caveats:

  • You'll also have to deploy with --force

  • You can enable retries only on triggered functions, not http-called functions.

  • It would be idiotic not to build in some safeguards. Retry policy maxes out at 7 days, and bills just like any other function invocation, so if you have some unhandled error, it could repeatedly run for a full week. You can use context.eventTimestamp to know when the first attempt roughly started.

Read this: https://firebase.google.com/docs/functions/retries and make sure your function in idempotent.

It was also difficult to discover what to return to force a retry or avoid a retry. Triggered Firebase functions must return a Promise. (See this vid)

A retry-enabled Firebase function will retry if:

  • it returns a rejected promise
  • throws an exception
  • or the function times out

That means that if you run into an error that you know won't eventually resolve itself with a retry (i.e. you want to stop the function execution and not retry), you can return Promise.resolve({message: 'some message'});

like image 124
jimbotron Avatar answered Feb 09 '23 01:02

jimbotron


There is currently no similar option for deployment using the Firebase CLI.

This is something being worked on by the Firebase team, so stay tuned for updates.

like image 37
Doug Stevenson Avatar answered Feb 08 '23 23:02

Doug Stevenson