Avoiding GCF anti-patterns part 1: How to write event-driven Cloud Functions properly by coding with idempotency in mindAvoiding GCF anti-patterns part 1: How to write event-driven Cloud Functions properly by coding with idempotency in mindCloud Developer AdvocateTechnical Solutions Engineer

Editor’s note: Over the next several weeks, you’ll see a series of blog posts focusing on best practices for writing Google Cloud Functions based on common questions or misconceptions as seen by the Support team. We refer to these as “anti-patterns” and offer you ways to avoid them. This article is the first post in the series.

Scenario

You noticed that your Cloud Function executes multiple times for a single request. For example, your Function saves duplicate entries to Firestore for a single request.

Most common anti-pattern

Your Cloud Function is not idempotent. In this context, idempotent means that you should be able to call your Function multiple times with the same input data and the result of the initial call does not change. Examples are provided below. 

How to investigate:

For background functions, it is important to be familiar with execution guarantees. A background Function is guaranteed to be invoked at least once, which implies the following: 

  1. You need to test that you can call your Function multiple times with the same input data that does not change the initial result. 
  2. Or if you cannot write your Function in an idempotent manner, you have a plan on how to handle these additional calls. 

Examples of idempotent functions

In Serverless, it is important to write your code with idempotency in mind. If it is not possible to achieve idempotency, it’s important to have a plan on how to handle duplicate invocations.  

Let’s first examine idempotent functions by exploring HTTP-triggered functions. Then you’ll see an example of idempotency for background functions. 

HTTP Function example

In the idempotent example below, a request contains a unique value (i.e. sensor ID & timestamp) which is used as the key to save to Firestore. Notice how Firestore.set() is used to specify this unique key. Therefore, even if the HTTP Function gets the request twice (theoretically speaking), you won’t get duplicate entries in Firestore because the same unique key was used to create the document.

Leave a Comment