This guide describes optimizations for Cloud Run services written in JavaScript or TypeScript, running on the Node.js runtime. The information on this page supplements the general development tips, which also apply to Node.js.
Optimize startup time
By optimizing startup time, you can reduce latency, improve responsiveness, and achieve effective cost optimization. This section describes different ways to optimize startup time.
Start your app using node
instead of npm
Start your application directly using node index.js
instead of npm start
,
as npm
adds extra latency.
To start your application with node index.js
, follow either of these methods:
Use
CMD node index.js
in your Dockerfile, for example:CMD node index.js
Set
node index.js
as your entrypoint. Run the following command using the Google Cloud CLI:gcloud run deploy SERVICE --command "node index.js"
For more information and options for configuring entrypoints, see Configure containers for services.
If you use source deployments without a Dockerfile, Cloud Run performs the optimization.
Bundle your code
A bundler is a build tool that optimizes the layout of your JavaScript source files for faster load times. Some common bundler optimizations include tree shaking, minification, and coalescing of small files. Bundlers significantly reduce the total size of the bundle and reduce the number of file read requests. Common JavaScript bundlers are esbuild, webpack, and rollup.
Lazy load dependencies
At startup, Cloud Run streams each file that your code loads from a remote location. Compared to a local file system, using a remote location leads to additional latency each time a file is read. Node.js packages might use many files with indirect dependencies. Instead of importing all dependencies at startup, we recommended that you only load dependencies that are required for your server to start, and lazy load the other dependencies with dynamic imports.
For example, instead of using import at the top of your module, such as
import { Storage } from '@google-cloud/storage'
, use import()
in the function
when it requires the imported object, for example:
const { Storage } = await import('@google-cloud/storage');
To identify modules that load during startup and the time taken by each module to load on your machine, run the following command:
node --trace-event-categories node.module_timer --trace-event-file-pattern 'trace-events.log' index.js
Configure timeout
The Node.js built-in HTTP server has a default timeout of two minutes. If the
request timeout of your Cloud Run service is longer, modify the timeout
using server.setTimeout(msecs)
. You must also modify timeout for frameworks
that are built on the Node.js server, such as Express. To
achieve an unlimited timeout in Node.js and to rely on Cloud Run's built-in
timeout, use server.setTimeout(0)
.