# Reduce Cold Starts in Cloud Functions for Firebase

Yes. An agent sets minimum instances and concurrency per function, moves heavy imports out of module scope and keeps lint and the compile check green, in a PR.

[Run this on Rush](https://cloud.getrush.ai/run/reduce-cold-starts/firebase-functions/). Opens the console with this prompt ready to send, in a Project that has your repository.

## What the agent does

The agent reads how each function starts before it changes anything. In a repository like firebase/functions-samples, the 2nd gen Node samples live under `Node/`, each with its own `functions/package.json` on `firebase-functions` 7 and `firebase-admin` 14 with `engines.node` set to 24, and the root `package.json` drives them through pnpm with `bootstrap-2nd-gen`, `lint-2nd-gen`, `compile-2nd-gen` and `test-2nd-gen`, which `.github/workflows/test_node.yml` runs on Node 22. `Node/quickstarts/https-time-server/functions/index.js` exports `date` from `onRequest` with `timeoutSeconds: 1200` and two regions and requires `moment` at the top of the module; `Node/quickstarts/thumbnails/functions/index.js` requires `sharp` at module scope and runs `onObjectFinalized` with `cpu: 2`; `Node/quickstarts/uppercase-firestore/functions/index.js` calls `initializeApp()` once and serves `addmessage` and `makeuppercase`. None of the 2nd gen samples sets `minInstances`, `concurrency` or `setGlobalOptions`; the only `minInstances` in the repository is in the 1st gen `runtime-options` sample.

It then decides per function instead of flipping one switch. For the HTTPS and callable functions that users wait on, the agent adds `minInstances` driven by a `defineInt` param with a default of zero, so a production project sets a warm instance count through the params file at deploy time and an emulator or preview project keeps none, which is the pattern the 1st gen sample sketches with its project id check. It sets `concurrency` explicitly on the request-driven functions so one warm instance serves many requests instead of starting more, and leaves background triggers such as `makeuppercase` and `generateThumbnail` at zero minimum instances, since nobody is waiting on a cold start there and a warm instance would be billed for nothing.

Module scope gets lighter. `moment` in the time server and `sharp` in the thumbnails function move behind a lazy require inside the handler, cached in a module variable after the first call, so the instance boots without loading them and the first request that needs them pays once. `initializeApp()` stays at module scope, which is where the Admin SDK expects it, and the Firestore client is created with `preferRest` so the instance does not open a gRPC channel before it serves anything. Each change carries a short comment naming the cold-start reason, because the samples are read as documentation.

Then it checks what it can without a Firebase project. It runs the sample's `npm run lint`, which `firebase.json` also runs as `predeploy`, and the `compile` script, which copies `tsconfig.template.json` and type-checks the JavaScript. Where a sample has tests, as `Node/test-functions-jest` and the callable sample with `firebase-functions-test` do, it runs them. It does not deploy: setting `minInstances` changes the bill, so the pull request says which functions gained a warm instance and asks the reviewer to set the param value for production.

## Start it with one API call

`POST https://api.phoenix.so/o/{org}/sessions`

```json
{
  "agent": "claude",
  "input": "Reduce cold starts in the 2nd gen Cloud Functions in this repository. Read the root package.json, .github/workflows/test_node.yml, and for each sample under Node/ its functions/index.js, functions/package.json and firebase.json first. For HTTPS and callable functions, add minInstances driven by a defineInt param that defaults to 0 and set concurrency explicitly; leave background triggers at zero minimum instances. Move heavy module-scope requires such as moment and sharp behind a lazy require cached after first use, keep initializeApp at module scope, and create the Firestore client with preferRest. Add a one-line comment at each change naming the cold-start reason. Run each sample's lint and compile scripts and any tests it has. Do not deploy. Open a pull request that lists each function, its minInstances param, its concurrency and what moved out of module scope, and says that production must set the param value.",
  "resources": [
    {
      "url": "https://github.com/your-org/your-app"
    }
  ]
}
```

1. **Get an API key.** In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
2. **Send the request.** POST the body in request.json to https://api.phoenix.so/o/{org}/sessions, with your repository as the resources URL. The run starts in its own cloud sandbox.
3. **Read what came back.** Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.

## What comes back

What comes back is a pull request touching `functions/index.js` in the samples that serve requests, with a `defineInt` param for minimum instances, explicit `concurrency` on request-driven functions, lazy requires for `moment` and `sharp`, and `preferRest` on the Firestore client. The description is a table: function, trigger type, minimum instances param, concurrency, what moved out of module scope, and a line saying production must set the param before the warm instances exist.

The run's record keeps the lint, compile and test output per sample, so a reviewer sees that `eslint --max-warnings=0` still passes under the Google config and that the JavaScript still type-checks against the shared template.

Before merging, a reviewer sets the param value for the production project, deploys one function, and reads its cold start count in Cloud Logging over a day; the pull request names the log field to filter on so that check is quick.

## Run it on every function whose p99 latency is dominated by cold starts

The setup is one `POST /o/{org}/sessions` with this body and the repository in `resources`, started from a terminal; the run continues in its sandbox after the window closes, and a follow-up through `POST /o/{org}/sessions/{id}/messages` can raise the default for one function or add `cpu` where concurrency needs it, without starting over. A team with several Firebase projects sends one request per repository, each with its own UUID as `request_id`, so a rerun of the script returns the run already started.

Give the API key a `webhook_url` and Rush POSTs `run.completed` or `run.failed` when a run's turn finishes, with `session_url` so your server can read the pull request link and the lint output.

## Why run it on Rush?

Cold-start work is many small edits across many entry points, and each one is easy to get subtly wrong: a `minInstances` on a Firestore trigger that nobody waits on, a lazy require that re-imports on every call, a global option that silently gives every function a warm instance and a bill. The agent reads every `index.js` and `package.json` in its own sandbox, decides per function, and runs each sample's own lint and compile scripts to show nothing broke.

The commands and their output stay with the run, so the pull request can point at the lint result for each sample and at the exact lines that changed, and a reviewer who knows the project's traffic only has to decide the param values.

## Frequently asked questions

### Will this raise my Firebase bill?

Only once a project sets the param above zero. The agent defaults the minimum-instance param to 0, so deploying the pull request as it stands changes nothing in billing; the description tells the reviewer which functions to warm and asks them to set the value for production.

### Why not call setGlobalOptions once?

A global minimum would give the background triggers, such as the Firestore and Storage functions, warm instances nobody waits on. The agent sets options per function so only the HTTPS and callable ones, where a person is waiting, keep an instance ready.

### Does lazy-loading sharp or moment slow the first request?

The first request on a new instance pays the import once; every later request on that instance reuses the cached module. That moves the cost from every cold start to the first call that needs the library, which for a thumbnail trigger is every call anyway, so the agent only moves imports where a function can answer without them.

### Can the agent verify the cold starts actually dropped?

Not from the sandbox: it has no Firebase project and does not deploy. It runs lint, the compile check and the tests that exist, and the pull request names the Cloud Logging field to watch after the reviewer deploys.

### Does it touch the 1st gen samples?

No. `Node-1st-gen` keeps its own options API and already shows `minInstances` in its runtime-options sample. The pull request covers the 2nd gen functions under `Node/` only.

## More Firebase Functions jobs

- [Upgrade firebase-functions and firebase-admin](https://getrush.ai/run/upgrade-firebase-functions/firebase-functions/)
- [Write Tests for Firebase Cloud Functions](https://getrush.ai/run/write-emulator-tests/firebase-functions/)
- [Enforce App Check on Firebase Callable Functions from a Linear Issue](https://getrush.ai/run/add-app-check/firebase-functions/)

## The same job on other stacks

- [Reduce Cold Starts for a NestJS API on Serverless Framework](https://getrush.ai/run/reduce-cold-starts/serverless/)

## More jobs like this: Hand off a long task

- [Reduce a Docker Image's Size for a Flask App](https://getrush.ai/run/reduce-image-size/docker/)
- [Make Turborepo CI Check Only the Packages a Pull Request Changed](https://getrush.ai/run/run-ci-on-changed-packages/turborepo/)

## Keep reading

- [How a Rush run works on your repository, from request to pull request](https://getrush.ai/cloud/)
- [Compare cloud agents, agent sandboxes and AI code review](https://getrush.ai/compare/)
- [Rush pricing: Free, Pro and Max](https://getrush.ai/pricing/)
