I have an EventGrid triggered Node.js Azure function app.
It can receive 100 simultaneous calls to run. If the process succeeds or fails, it writes to CosmosDB.
However the initialization of the CosmosDB client is an expensive, long running process, so I want to share this initialized client as a Singleton amongst all of the 100 instances of the function app.
Looking at the Node.js documentation, it states that a module will be cached (same instance) if it exports an object. https://nodejs.org/api/modules.html#modules_caching i.e. it will act as a singleton if I return an object.
When I test my code in Azure, I see it being called over and over.
Question: How do I initialize my CosmosDB client once amongst all of the concurrent "threads".
In my example code below, I'm faking out the long running Cosmos initialization with a long running operation of 5000m/s.
My expensive operation module returns an object.
expensiveOperation.js
const snooze = ms => new Promise(resolve => setTimeout(resolve, ms));
let value = null;
const getInstance = async (context) => {
if(value !== null) return value;
context.log("Long running process started...")
await snooze(5000);
value = 5;
return value;
}
exports.something = {
getInstance
};
index.js
const { something } = require("../expensiveOperation");
module.exports = async function (context, req) {
context.log("JavaScript HTTP trigger function processed a request.");
var first = await something.getInstance(context);
context.done();
};

