Reduce Firebase Cold Starts
Only require dependencies for the requested cloud function.
Serverless architecture is great for many reasons. These 3 are my favorite:
- No server maintenance.
- You only pay for site usage and not for up-time.
- Scale with ease.
These reasons alone allow you to get a site up and running quickly without the financial monthly burden of a virtual server. There are also downsides with the biggest one being Cold Starts.
What's a Cold Start?
A cold start is when serverless architecture gets a request to your service and needs to start it up including downloading and installing all of its dependencies. For Node projects that's all dependencies listed in
package.json. Cold Starts significantly increase page speed. If your service is already running because a request was made shortly before this request then there is no need for a cold start. Firebase does do some optimizations by recycling previous environments, but I air on the side of caution.
The interesting thing about serverless is that each function is treated as its own service. All dependencies get installed even though the one function that's being requested may not use all dependencies. Since you can't avoid which packages are installed you should make sure your dependencies are light. But you can avoid instantiation of unnecessary dependencies.
Firebase exposes environment variables that you can use to determine which function is being run. This allows you to reduce scope by only
requireing dependencies needed for the running function. For Node 10 and up use the
K_SERVICE environment variable and for Node < 10 use
In the above example we are getting an additional benefit of keeping the
onCall function warm by only creating one
onCall function and specifying the handler to use with
require statements which block the event loop are only done once and cached in a variable for subsequent requests.
The database is also only instantiated once and then cached. I found this to be a significant boost in response times