skip to content

When you move a Cloud Functions for Firebase function from 1st gen to 2nd gen, what changes in how it runs, and what can break?

level: seniorimportance: should knowfreq 40%

answer

  1. one Cloud Run service per function
  2. 80 concurrent requests by default
  3. CPU and concurrency are tied
  4. a different default service account
  5. timeouts and retry window move

basics

~20 s

2nd gen deploys each function as a Cloud Run service: an instance serves up to 80 concurrent requests by default, small functions get a full CPU, the default service account changes, and the event retry window drops to 24 hours.

solid answer

~50 s

In 2nd gen each function is a Cloud Run service. The biggest behavioural change is `concurrency`: one instance handles up to 80 requests at once by default (1,000 maximum), but only with at least one full CPU, so module-level variables holding per-request state leak between users. Small functions now default to one CPU, which raises the per-millisecond price; `cpu: "gcf_gen1"` restores fractional CPU and disables concurrency. The runtime identity moves from the App Engine default service account to the Compute Engine default one, so IAM grants must follow. HTTPS and callable timeouts rise to 60 minutes, event functions stay at 9, and the event retry window shrinks from 7 days to 24 hours. Analytics triggers stay on 1st gen. Migrate by deploying the 2nd-gen version under a new name, letting both run with an idempotent handler, then deleting the old one.

code

typescript · 28 lines
typescript
import { setGlobalOptions } from "firebase-functions";
import { onRequest } from "firebase-functions/https";
import { onDocumentCreated } from "firebase-functions/firestore";

// Defaults for every function in this codebase.
setGlobalOptions({ region: "europe-west1", maxInstances: 20 });

// Many requests share one instance: keep per-request state inside the handler.
export const courierWebhook = onRequest(
  { concurrency: 40, memory: "512MiB", timeoutSeconds: 120 },
  async (req, res) => {
    const update = req.body as { orderId?: string; status?: string };
    if (!update.orderId || !update.status) {
      res.status(400).send("orderId and status are required");
      return;
    }
    // ... record the status change ...
    res.status(204).end();
  },
);

// A small, rarely busy trigger that keeps 1st-gen fractional CPU (and so no concurrency).
export const auditOrder = onDocumentCreated(
  { document: "orders/{orderId}", cpu: "gcf_gen1", memory: "256MiB" },
  async (event) => {
    // ...
  },
);

go deeper

for a junior

Recall that 2nd gen runs on Cloud Run and that one instance can serve many requests at once.

for a middle

Explain the default of 80 concurrent requests, why it needs a full CPU, and how timeouts and the retry window differ from 1st gen.

for a senior

Show the migration you would run: module-state audit, service-account grants, a renamed deploy beside the old function, and idempotent handlers during the overlap.

for a principal

Set codebase defaults with setGlobalOptions and decide where concurrency, minimum instances and gcf_gen1 CPU are worth their cost.

## What changes when a function moves to 2nd gen Cloud Functions for Firebase 2nd gen builds each function with Cloud Build and **deploys it as a Cloud Run service**, with Eventarc delivering events. The source looks similar, `onDocumentCreated` from `firebase-functions/firestore` instead of `functions.firestore.document().onCreate()` from `firebase-functions/v1`, but the runtime underneath behaves differently. | | 1st gen | 2nd gen | |---|---|---| | Requests per instance | 1 | up to 1,000; default 80 when CPU is at least 1 | | Maximum timeout | 9 minutes | 60 min HTTPS and callable; 30 min scheduled and task queue; 9 min other events | | Default runtime service account | `[email protected]` | `[email protected]` | | Default CPU from 128MB to 1GB | fractional, 1/12 to 7/12 | 1 full CPU | | Event retry window | 7 days | 24 hours | | Firestore named databases | not supported | supported | | Analytics triggers | supported | not supported | | Image registry | Container Registry or Artifact Registry | Artifact Registry only | 1st-gen and 2nd-gen functions can live side by side in one codebase, which is how Analytics triggers stay on 1st gen. ## Concurrency is the change that breaks code - With concurrency above 1, **many requests share one Node.js process** and its module scope at the same time. - Module-level variables holding per-request data, such as the current user, a cart or a scratch counter, leak between requests. - Global scope stays the right place for **shared, reusable** objects: the Admin SDK app, API clients, immutable configuration. - Concurrency needs at least one full CPU. A fractional `cpu`, or `cpu: "gcf_gen1"` on a function under 2GB, turns it off. - Higher concurrency may need more memory and CPU; a heavy image-processing function may not cope with many simultaneous requests even at its largest size. ## Cost and scaling knobs - `minInstances` keeps instances warm; the SDK documents that idle instances are billed for memory and 10% of CPU. - `maxInstances` caps scale-out. An HTTP function at the cap queues new requests for 30 seconds, then rejects them with `429 Too Many Requests`. - `concurrency` absorbs spikes without starting new instances. - Because 2nd gen gives small functions a full CPU, a 128MB function costs about 10.5 times more per millisecond than on 1st gen in Firebase's own table. `cpu: "gcf_gen1"` restores the old allocation, at the price of concurrency. - `setGlobalOptions()` sets defaults, such as region and `maxInstances`, once for every function in the codebase. - Options in code are the source of truth and override console edits on the next deploy unless `preserveExternalChanges` is set. ## Trigger details that move with the generation - The 1st-gen API lives in `firebase-functions/v1`; the package root and paths such as `firebase-functions/firestore` and `firebase-functions/https` are 2nd gen. - Event handlers take an `event` object, a CloudEvent with `id`, `time` and `data`, instead of 1st gen's `(snapshot, context)` pair. - Retry is still off by default, but the option is now `retry: true` rather than `failurePolicy`. - A 1st-gen Firestore trigger needs the `(default)` database in native mode; named databases and Datastore mode need 2nd gen. - The 2nd-gen Auth triggers `onUserCreated` and `onUserDeleted` are marked Preview, so check that status before moving an Auth trigger. ## A safe migration 1. Audit module-level state and make each handler safe to run concurrently. 2. Grant the IAM roles the App Engine default account held to the Compute Engine default account, or set `serviceAccount` to a dedicated, narrower one. 3. Rewrite the trigger with the 2nd-gen API under a **new name**, and set `retry`, `region`, memory and CPU explicitly rather than trusting new defaults. 4. Deploy the new function. For a while both versions receive the same events, so the handler must be idempotent. 5. Delete the old one with `firebase functions:delete`. 6. For a callable, remember that installed app versions keep calling the old name and region; keep the old endpoint until those versions have aged out. The rename-first sequence is the procedure Firebase documents for changing a function's name, region or trigger, and it avoids losing events during the switch. A team that skips it and deletes first has a window with no function listening.

  • A 2nd-gen callable stores the current user's cart in a module-level variable. What happens under load?
    With the default concurrency of 80, several requests run in the same process at once and share that variable, so one user's cart can appear in another user's response. Keep per-request data in local variables inside the handler; use module scope only for shared clients and immutable configuration. Setting `concurrency: 1` hides the bug but gives up the instance sharing that 2nd gen is for.
  • After the upgrade, a function gets permission errors reading a Cloud Storage bucket it used to read. Why?
    The runtime identity changed. 1st gen ran as `[email protected]`; 2nd gen runs as `[email protected]` unless `serviceAccount` says otherwise. IAM grants made to the old account do not carry over, so grant the role to the new account, or better, to a dedicated service account set in the function's options.

  • 2nd gen still runs one request per instance.
  • Concurrency works with any CPU setting, including fractional CPU.
  • Module-level variables are private to each request in 2nd gen.
  • The runtime service account stays the same after upgrading.
  • Every 2nd-gen function can run for 60 minutes, event triggers included.
  • Analytics triggers have a 2nd-gen equivalent.

Assumes Firebase as of 2026-10-09 with firebase-functions 7.4.0: 2nd-gen functions deploy as Cloud Run services, and 1st gen remains supported through firebase-functions/v1.