google-cloud-functions

How does Global Variables work on Firebase Function 2nd Gen?


Functions 1st Gen were able to only handle 1 request per instance, so, every global variable was going to be shared for the whole instance, until the instance dies.

But now, Functions 2nd Gen are able to process up to 1000 concurrent requests with 1 single instance... So... What happens in that case with the Global Variables?

When I say Global Variables, I mean: https://firebase.google.com/docs/functions/tips#use_global_variables_to_reuse_objects_in_future_invocations

Just to be extra clear in my question, let me add an example:

If I change the configurations in Google Cloud Console to ONLY have a MAX of 1 instance running at the same time, and I have some global variables, AND the instance is configured to handle up to 1000 requests (because by default only handles 80), so, question: Will all the requests being able to see the same value in the instance? Will all they share the same "global"?


Solution

  • There is no special behavior with global variables in Cloud Functions, and the behavior is not different between v1 and v2. It works exactly like you would expect in a typical node.js program.

    If there is a variable defined at the global scope in your code, all access from all requests on the same server instance are going to use the same value. The number of concurrent requests doesn't matter at all. In node.js, by default, there is only one thread and memory space that's used to execute all JavaScript, so all requests handled by a Cloud Functions instance are going to use that same thread and memory space. It does not use worker threads to manage requests, and the requests are not sandboxed from each other at all. For HTTP type function, it's really not much different at all from a normal express server.