Avoiding GCF anti-patterns part 2: How to reuse Cloud Function instances for future invocations

reCAPTCHA Enterprise puts users first
October 27, 2021
Podcast: “Roided-out Sitting Duck, Part 1” with Juan Andres Guerrero-Saade
October 27, 2021
reCAPTCHA Enterprise puts users first
October 27, 2021
Podcast: “Roided-out Sitting Duck, Part 1” with Juan Andres Guerrero-Saade
October 27, 2021

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 second post in the series.

Scenario

You notice that your Function is exhibiting one of the follow:

  • slow to respond to a request
  • demonstrates unexpected behavior on subsequent executions
  • runs out of memory over time

Most common root issue

If your Cloud Function is slow to respond, have you considered moving code into the global scope? However, if your Function is demonstrating unexpected behavior on subsequent executions or is running out of memory over time, do you have code written in the global scope that could be causing the issue?

How to investigate

Does your Function perform an expensive operation, e.g. time or network intensive operation, on every invocation within the Function event handler body? Examples include:

  • opening a network connection
  • importing a library reference
  • instantiates an API client object

You should consider moving such expensive operations into the global scope.

What is the global scope

Global scope is defined as any code that is written outside the Function event handler. Code in the global scope is only executed once on instance startup. If a future Function invocation reuses that warm instance, the code in the global scope will not re-run again.

Technically speaking, code in global scope is executed additionally on the initial deployment for a “health check” – see Other helpful tips section below for more information about health checks.

How to update your Function to use the global scope

Suppose you’re saving to Firestore. Instead of making the connection on each invocation, you can make the connection in the global scope. Cloud Functions tries to reuse the execution environment of the previous function when possible, e.g. the previous instance is still warm. This means you can potentially speed up your Functions by declaring variables in the global scope.

Note: to be clear, there is no guarantee the previous environment will be used. But when the instance can be used, you should see performance benefits.

In the example below, you’ll see how the connection to Firebase is outside the body of the Function event handler. Anything outside the Function event handler is in global scope.

Leave a Reply

Your email address will not be published. Required fields are marked *