You can deploy, delete, and modify functions using Firebase CLI commands or by setting runtime options in your functions source code.
Deploy functions
To deploy functions, run this Firebase CLI command:
$ firebase deploy --only functions
By default, the Firebase CLI deploys all of the functions inside
index.js
at the same time. If your project contains more than 5 functions,
we recommend that you use the --only
flag with specific function names
to deploy only the functions that
you've edited. Deploying specific functions
this way speeds up the deployment process and helps you avoid running into
deployment quotas. For example:
$ firebase deploy --only functions:addMessage,functions:makeUppercase
When deploying large numbers of functions, you may exceed the standard quota and receive HTTP 429 or 500 error messages. To solve this, deploy functions in groups of 10 or fewer.
See the Firebase CLI reference for the full list of available commands.
By default, the Firebase CLI looks in the functions/
folder for the
source code. If you prefer, you can organize functions
in codebases or multiple sets of files.
Delete functions
You can delete previously deployed functions in these ways:
- explicitly in the Firebase CLI with
functions:delete
- explicitly using the context menu in the functions list in the Firebase console
- implictly by removing the function from
index.js
prior to deployment.
All deletion operations prompt you to confirm before removing the function from production.
Explicit function deletion in the Firebase CLI supports multiple arguments as well as functions groups, and allows you to specify a function running in a particular region. Also, you can override the confirmation prompt.
# Delete all functions that match the specified name in all regions.
$ firebase functions:delete myfunction
# Delete a specified function running in a specific region.
$ firebase functions:delete myfunction --region us-east-1
# Delete more than one function
$ firebase functions:delete myfunction myotherfunction
# Delete a specified functions group.
$ firebase functions:delete groupA
# Bypass the confirmation prompt.
$ firebase functions:delete myfunction --force
With implicit function deletion, firebase deploy
parses index.js
and
removes from production any functions that have been removed from the file.
Modify a function's name, region or trigger
If you are renaming or changing the regions or trigger for functions that are handling production traffic, follow the steps in this section to avoid losing events during modification. Before you follow these steps, first ensure that your function is idempotent, since both the new version and the old version of your function will be running at the same time during the change.
Rename a function
To rename a function, create a new renamed version of the function in index.js
and then run two separate deployment commands. The first command deploys the
newly named function, and the second command removes the previously deployed
version. For example, if you have a function called webhook
that you'd like to
change to webhookNew
, revise the code as follows:
// before
const {onRequest} = require('firebase-functions/v2/https');
exports.webhook = onRequest((req, res) => {
res.send("Hello");
});
// after
const {onRequest} = require('firebase-functions/v2/https');
exports.webhooknew = onRequest((req, res) => {
res.send("Hello");
});
Then run the following commands to deploy the new function:
# Deploy new function called webhookNew
$ firebase deploy --only functions:webhooknew
# Wait until deployment is done; now both webhooknew and webhook are running
# Delete webhook
$ firebase functions:delete webhook
Change a function's region or regions
If you are changing the specified regions for a function that's handling production traffic, you can prevent event loss by performing these steps in order:
- Rename the function, and change its region or regions as desired.
- Deploy the renamed function, which results in temporarily running the same code in both sets of regions.
- Delete the previous function.
For example, if you have a function called webhook
that is currently in the
default functions region of us-central1
, and you want to migrate it to
asia-northeast1
, you need to first modify your source code to rename the
function and revise the region.
// before
const {onRequest} = require('firebase-functions/v2/https');
exports.webhook = onRequest((req, res) => {
res.send("Hello");
});
// after
const {onRequest} = require('firebase-functions/v2/https');
exports.webhookasia = onRequest({
region: 'asia-northeast1'
}, (req, res) => {
res.send("Hello");
});
Then deploy by running:
$ firebase deploy --only functions:webhookAsia
Now there are two identical functions running: webhook
is running in us-central1
,
and webhookasia
is running in asia-northeast1
.
Then, delete webhook
:
$ firebase functions:delete webhook
Now there is only one function - webhookasia
, which is running in asia-northeast1
.
Change a function's trigger type
As you develop your Cloud Functions for Firebase deployment over time, you may need to change a function's trigger type for various reasons. For example, you might want to:
- Change from the legacy storage
onChange
event toonFinalize
,onDelete
,onArchive
, andonMetadataUpdate
. (Learn more about this in the beta to v1 or v2 upgrade guide). - Change from one type of Firebase Realtime Database or Cloud Firestore event to another one, such as the generic
onWrite
event to the granularonCreate
event.
It is not possible to change a function's event type by just changing the
source code and running firebase deploy
. To avoid errors,
change a function's trigger type by this procedure:
- Modify the source code to include a new function with the desired trigger type.
- Deploy the function, which results in temporarily running both the old and new functions.
- Explicitly delete the old function from production using the Firebase CLI.
For instance, if you had a function objectchanged
that has the legacy
onMetadataUpdated
event type, and you'd like to change it to onObjectFinalized
, first rename
the function and edit it to have the onObjectFinalized
event type.
// before
const {onMetadataUpdated} = require('firebase-functions/v2/storage');
exports.objectchanged = onMetadataUpdated((event) => {
return console.log('File name is: ', event.data.name);
});
// after
const {onObjectFinalized} = require('firebase-functions/v2/storage');
exports.objectchanged = onObjectFinalized((event) => {
return console.log('File name is: ', event.data.name);
});
Then run the following commands to create the new function first, before deleting the old function:
# Create new function objectFinalized
$ firebase deploy --only functions:objectFinalized
# Wait until deployment is done; now both objectChanged and objectFinalized are running
# Delete objectChanged
$ firebase functions:delete objectChanged
Set runtime options
Cloud Functions for Firebase lets you select runtime options such as the Node.js runtime version and per-function timeout, memory allocation, and minimum/maximum function instances.
Set Node.js version
Firebase SDK for Cloud Functions v2 allows a selection of Node.js runtime. You can choose to run all functions in a project exclusively on the runtime environment corresponding to one of these supported Node.js versions:
- Node.js 16
- Node.js 14
- Node.js 12
- Node.js 10
To set the Node.js version:
Set the version in the engines
field in the package.json
file that was created in your functions/
directory during initialization.
For example, to use only
version 16, edit this line in package.json
:
"engines": {"node": "16"}
The engines
field is required; it must specify one of the supported
Node.js versions in order for you to deploy and run functions. Currently
firebase init functions
sets this field to 16
.
Upgrade your Node.js runtime
To upgrade your Node.js runtime:
- Make sure your project is on the Blaze pricing plan.
- Make sure you are using Firebase CLI v9.17.0 or later.
- Change the
engines
value in thepackage.json
file that was created in yourfunctions/
directory during initialization. For example, if you are upgrading from version 10 to version 16, the entry should look like this:"engines": {"node": "16"}
- Redeploy functions using the Firebase CLI v9.17.0 or later.
Control scaling behavior
By default, Cloud Functions for Firebase scales the number of running instances based on the number of incoming requests, potentially scaling down to zero instances in times of reduced traffic. However, if your app requires reduced latency and you want to limit the number of cold starts, you can change this default behavior by specifying a minimum number of container instances to be kept warm and ready to serve requests.
Similarly, you can set a maximum number to limit the scaling of instances in response to incoming requests. Use this setting as a way to control your costs or to limit the number of connections to a backing service such as to a database.
Using these settings together with the per-instance concurrency setting (new in v2), you can control and tune the scaling behavior for your functions. The nature of your application and function will determine which settings are most cost effective and will result in the best performance.
For some apps with low traffic, a lower CPU option without multi-concurrency is optimal. For others where cold starts are a critical issue, setting high concurrency and minimum instances means that a set of instances are always kept warm to handle large spikes in traffic.
For smaller-scale apps that receive very little traffic, setting low maximum instances with high concurrency means that the app can handle bursts of traffic without incurring excessive costs.
Allow concurrent requests
In Cloud Functions v1, each instance could handle one request at a time, so
scaling behavior was set only with minInstances
and maxInstances
settings.
In addition to controlling the number of instances, in Cloud Functions v2 you
can control the number of requests each instance can serve at the same time with
the concurrency
option. The default value for concurrency is 80, but you can
set it to any integer between 1 and 1000.
Functions with higher concurrency settings can absorb spikes of traffic without cold starting because each instance likely has some headroom. If an instance is configured to handle up to 50 concurrent requests but is currently handling only 25, it can handle a spike of 25 additional requests without requiring a new instance to cold start. By contrast, with a concurrency setting of just 1, that spike in requests could lead to 25 cold starts.
When experimenting with higher concurrency settings in Cloud Functions v2, keep the following in mind:
- Higher concurrrency settings may require higher CPU and RAM for optimal performance until reaching a practical limit. A function that does heavy image or video processing, for example, might lack the resources to handle 1000 concurrent requests, even when its CPU and RAM settings are maximized.
- Since Cloud Functions v2 is powered by Cloud Run, you can refer also to Google Cloud guidance for optimizing concurrency.
- Make sure to test multiconcurrency thoroughly in a test environment before switching to multiconcurrency in production.
Reduce the number of cold starts
To set minimum number of instances for a function in source code, use the
minInstances
option.. For example, this function sets a minimum of 5 instances
to keep warm:
const { onCall } = require("firebase-functions/v2/https");
exports.getAutocompleteResponse = onCall(
{
// Keep 5 instances warm for this latency-critical function
minInstances: 5,
},
(event) => {
// Autocomplete user’s search term
}
);
Here are some things to consider when setting a value for minInstances
:
- If Cloud Functions for Firebase scales your app above your
minInstances
setting, you'll experience a cold start for each instance above that threshold. - Cold starts have the most severe effect on apps with spiky traffic. If your
app has spiky traffic and you set a
minInstances
value high enough that cold starts are reduced on each traffic increase, you'll see significantly reduced latency. For apps with constant traffic, cold starts are not likely to severely affect performance. Setting minimum instances can make sense for production environments, but should usually be avoided in testing environments. To scale to zero in your test project but still reduce cold starts in your production project, you can set
minInstances
based on theFIREBASE_CONFIG
environment variable:// Get Firebase project id from `FIREBASE_CONFIG` environment variable const envProjectId = JSON.parse(process.env.FIREBASE_CONFIG).projectId; exports.renderProfilePage = onRequest( { // Keep 5 instances warm for this latency-critical function // in production only. Default to 0 for test projects. minInstances: envProjectId === "my-production-project" ? 5 : 0, }, (req, res) => { // render some html } );
Limit the maximum number of instances for a function
To set maximum instances in function source code, use the maxInstances
option.
For example, this function sets a limit of 100 instances in order to not
overwhelm a hypothetical legacy database:
const { onMessagePublished } = require("firebase-functions/v2/pubsub");
exports.mirrorevents = onMessagePublished(
{ topic: "topic-name", maxInstances: 100 },
(event) => {
// Connect to legacy database
}
);
If an HTTP function is scaled up to the maxInstances
limit, new requests are
queued for 30 seconds and then rejected with a response code of
429 Too Many Requests
if no instance is available by then.
To learn more about best practices for using maximum instances settings, check
out these
best practices for using maxInstances
.
Set timeout and memory allocation
In some cases, your functions may have special requirements for a long timeout value or a large allocation of memory. You can set these values either in the Google Cloud Console or in the function source code (Firebase only).
To set memory allocation and timeout in functions source code, use the options
parameter to customize the virtual machine running your functions. This
runtime option accepts a JSON object conforming to the
RuntimeOptions
interface. For
example, this storage function uses 1GiB of memory and times out after 300
seconds:
exports.convertLargeFile = onObjectFinalized({
timeoutSeconds: 300,
memory: "1GiB",
}, (event) => {
// Do some complicated things that take a lot of memory and time
});
The maximum value for timeoutSeconds
is 540
, or 9 minutes.
To set memory allocation and timeout in the Google Cloud Console:
- In the Google Google Cloud Console select Cloud Functions from the left menu.
- Select a function by clicking on its name in the functions list.
- Click the Edit icon in the top menu.
- Select a memory allocation from the drop-down menu labeled Memory allocated.
- Click More to display the advanced options, and enter a number of seconds in the Timeout text box.
- Click Save to update the function.
Override CPU defaults
Up to 2GB of memory allocated, each function in Cloud Functions for Firebase v2 defaults to one CPU, and then increases to 2 CPU for 4 and 8GB. Note that this is significantly different from v1 default behavior in ways that could lead to slightly higher costs for low-memory functions as expressed in the following table:
RAM allocated | Version 1 default CPU (fractional) | Version 2 default CPU | Price increase per ms |
---|---|---|---|
128MB | 1/12 | 1 | 10.5x |
256MB | 1/6 | 1 | 5.3x |
512MB | 1/3 | 1 | 2.7x |
1GB | 7/12 | 1 | 1.6x |
2GB | 1 | 1 | 1x |
4GB | 2 | 2 | 1x |
8GB | 2 | 2 | 1x |
16 GB | n/a | 4 | n/a |
If you prefer to preserve the v1 behavior for your v2 functions, set v1 defaults as a global option:
// Turn off Firebase defaults
setGlobalOptions({ cpu: 'gcfv1' });
For CPU-intensive functions, v2 provides the flexibility to configure additional CPU. You can boost CPU on a per-function basis as shown:
// Boost CPU in a function:
export const analyzeImage = onObjectFinalized({ cpu: 2 }, (event) => {
// computer vision goes here
});