Home > Net >  Firebase functions - two index.js files
Firebase functions - two index.js files

Time:03-03

I have code that exists in my index.js with numerous functions that have different really expensive imports. From my understanding, these functions share all global imports. So, I have two options

  • do all imports globally which leads to slow cold starts but faster function calls when warm idle instances are available
  • do lazy imports inside the functions, which makes for fast cold starts but slower function calls

I was wondering if a third option exists where I can split the index.js such that global imports are separated. Is there such an option, or an alternative that I am missing?

CodePudding user response:

Doing the expensive require from inside the function body does not necessarily lead to slower function calls, as requires are cached in-memory. Warm invocations (those that don't require a cold start) will run the require line but won't actually need to re-load the code.

// runs at cold start time, use for shared dependencies
const commonImport = require("common-import");

exports.myFunc = functions.https.onRequest((req, res) => {
  // runs only at invocation time but cached, use for unshared deps
  const expensiveImport = require("expensive-import");
});

For what it's worth, this particular type of problem is also something the Firebase team is actively investigating how to improve. You might consider signing up for the Firebase Alpha Program to receive word of early testing for such features.

CodePudding user response:

There's some arcane solutions others go through:

const common = require("common-import");
if (process.env.FUNCTION_NAME === "fn1") {
  const expensive1 = require("expensive-import-1");
}
if (process.env.FUCNTION_NAME === "fn2") {
  const expensive2 = require("expensive-import-2");
}

exports.fn1 = functions.https.onRequest((req, res) => {
  res.send(expensive1.expensiveResult());
});

exports.fn2 = functions.https.onRequest((req, res) => {
  res.send(expensive2.expensiveResult());
});

This will load only the files you want on cold-start. Those environment variables won't be present when we run your code locally to discover what functions to deploy however, so you must always export all functions you want to deploy.

As Michael said earlier though, we have someone actively working on a much better solution that will feel like a breath of fresh air, so don't spend too much time optimizing this if you can wait a bit.

  • Related