Cloud Functions global scope

Daz Wilkin
2 min readAug 22, 2017

--

I’ve worked with a couple of customers who reasonably — albeit incorrectly — assume that global scope with Cloud Functions is per function invocation.

It is not.

It is possible to use global scope with Cloud Functions to share static config|state across Cloud Functions invocations.

Don’t be misled by the nomenclature, although referred to as “serverless”, there are — of course — servers and, one or more of these runs one or more instances of your Cloud Functions. And this yields our solution:

global scope is per “serverless” instance (!) not per function invocation.

Example

index.js

/* jshint strict: true */
/* jshint esversion: 6 */
/* jslint vars: true */
/*jslint node: true */"use strict";const myInstanceConstant = (() => {
console.log("Instantiating 'myInstanceConstant'");
return "Henry";
})();
exports.helloWorld = (req, res) => {
const myFunctionConstant = (() => {
console.log("Instantiating 'myFunctionConstant'");
return "Hoops";
})();
console.log(`${myInstanceConstant}:${myFunctionConstant}`);
res.status(200).end();
};

The above example merely outlines the pattern. The constant ‘myInstanceConstant’ will be instantiated once per instance creation. In the logs from this function, when an instance is created to invoke the function on first call, ‘myInstanceConstant’ is instantiated (09:30:25). Then, I invoke the function multiple times (in reasonably quick succession) and, while the function is clearly invoked, and the local constant ‘myFunctionConstant’ is instantiated each time, the ‘myInstanceConstant’ in the global scope is *not* recreated.

If I were to generate sufficient traffic for Cloud Functions to create a 2nd, 3rd instance… when each instance is created, ‘myInstanceConstant’ will be instantiated (for each instance).

You should define requires, config and static content in the global scope wherever possible.

Google Runtime Configuration API

Google Cloud Runtime Configuration API is available as API Client Library for JavaScript (Node.js). You may use the service to define config|static content that you would like to share across Cloud Functions.

Fredrik has written a useful wrapper around Google’s API Client Library implementation of the Runtime Configuration API and provides an example of how to incorporate this into Cloud Functions. His library is available in npm as “cloud-functions-runtime-config”.

Conclusion

global scope is per “serverless” instance (!) not per function invocation.

--

--