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.
You notice that your Function is exhibiting one of the follow:
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?
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:
You should consider moving such expensive operations into 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.
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.