I’ve recently been added to a GCP project that deploys several functions wrote in JS and noticed that a bunch of those functions repeat a lot of code, an example:
function fetchXYZ’s index.js requires functions getABC and updateABC so those are displayed in fetchXYZ’s source tab, simultaneously function getABC requires function fetchXYZ so it is displayed in getABC’s source tab.
Question is, is there a way to optimize or avoid a scenario like this?
There are some alternative options. Fair note, I’m not a developer by nature, and mostly an enthusiastic amateur when it comes to Serverless technologies, mostly on AWS. Serverless Architectures are a deep topic and have very different considerations than some traditional SOA and microservice architectures. There are whole fields of study and books on the topic (some of our senior people and early devs literally wrote a book on it)
There are two big things with FaaS offerings (AWS Lambda, Azure Functions, and GCP Cloud Functions) that generally hold true. First, every millisecond (well, 100ms) you’re running the function, you’re paying for it. Secondly, functions can experience cold starts, dramatically increasing their execution time.
Cloud Functions can call other Cloud Functions. But the rules still apply. If you’re calling another function and waiting for it to return a value, you’re paying for both functions at the same time. This can blow out quite a bit.
Example – fetchXYZ is calling getXYZ, and waiting for the function to return a value to fetchXYZ so it can finish running
fetchXYZ.js [Starts] [Runs] [Calls] [Returns] ================================================================== * 1500ms getXYZ.js [Starts] [Runs] [Returns] ===================== * 200ms
Since it’s waiting for the second function to start, the first function keeps running, paying for the execution, including the startup of the second function. At 1700ms, compared to maybe 400ms for a consolidated function, that’s quite an additional cost (over 400%). Additionally, that second startup time will be noticed by users as quite a bit of lag time. Even if the code is duplicated in places, it’s still more efficient to keep the code in one place, and ensure you have good code management.
But there are times functions calling functions can be great. If they’re asynchronous in nature (that is, the first function doesn’t have to wait for the second function to complete), it can be a perfectly acceptable way to get things done. On AWS, there are things like Step Functions which help orchestrate these more complex workflows, but I don’t believe GCP has anything similar at this time.
Hope this helps a little bit. Would welcome insights from anyone with deeper serverless experience!