Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

107
Views
Cloud Functions - Use global variables

I have a function cloudFunctionCall in my cloud-function setup that is invoked on every cloud function call.

import * as functions from "firebase-functions";
const mysql = require("mysql");

function cloudFunctionCall(asyncFunc) {
  return functions
    .region(region)
    .https.onCall(async (data: any, context: any) => {
      try {
        const pool = mysql.createPool(getConfig(context));
        const result = await asyncFunc(data, pool);
        pool.end();
        res.send(result);
      } catch (err) {
        log("A promise failed to resolve", err);
        res.status(500).send(err);
      }
    });
}

export const func1 = cloudFunctionCall(_func1);
export const func2 = cloudFunctionCall(_func2);

context and therefore pool defines to which database an invoked function needs to talk to which might change on every cloud function call. Now I want to avoid passing pool as a parameter to asyncFunc since it is not actually required for the function logic and makes the functions more verbose.

Now my question: Is it safe to define pool as a global variable that gets updated on every cloud function call like the following?

//...
let pool;

function cloudFunctionCall(asyncFunc) {
  return functions
    .region(region)
    .https.onCall(async (data: any, context: any) => {
      try {
        pool = mysql.createPool(getConfig(context));
        const result = await asyncFunc(data, pool);
//...

I understand that every exported function is hosted in it's own environment but what would happen if func1 would get executed twice in quick succession on different databases? Could it happen that the second invocation overwrites pool that was set by the first invocation so that the latter one executes on the wrong database?

If so, is there another way to avoid passing pool as a parameter?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Cloud Function invocations run in strict isolation of each other: each container will only ever have one execution at a time. So there is no chance of function invocations overwriting the value of your global for each other.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!