Search code examples
firebasegoogle-cloud-firestoregoogle-cloud-functionsidempotent

Cloud functions and Firebase Firestore with Idempotency


I'm using Firestore at beta version with Cloud Functions. In my app I need to trigger a function that listens for an onCreate event at /company/{id}/point/{id} and performs an insert (collection('event').add({...}))

My problem is: Cloud Functions with Firestore require an idempotent function. I don't know how to ensure that if my function triggers two times in a row with the same event, I won't add two documents with the same data.

I've found that context.eventId could handle that problem, but I don't recognize a way to use it.

exports.creatingEvents = functions.firestore
  .document('/companies/{companyId}/points/{pointId}')
  .onCreate((snap, context) => {

    //some logic...

    return db.doc(`eventlog/${context.params.companyId}`).collection('events').add(data)
})

Solution

  • Two things:

    1. First check your collection to see if a document has a property with the value of context.eventId in it. If it exists, do nothing in the function.
    2. If a document with the event id doesn't already exist, put the value of context.eventId in a property in the document that you add.

    This should prevent multiple invocations of the function from adding more than one document for a given event id.