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 functions = require('firebase-functions');
exports.webhook = functions.https.onRequest((req, res) => {
res.send("Hello");
});
// after
const functions = require('firebase-functions');
exports.webhookNew = functions.https.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 functions = require('firebase-functions');
exports.webhook = functions
.https.onRequest((req, res) => {
res.send("Hello");
});
// after
const functions = require('firebase-functions');
exports.webhookAsia = functions
.region('asia-northeast1')
.https.onRequest((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
onChange
event type, and you'd like to change it to onFinalize
, first rename
the function and edit it to have the onFinalize
event type.
// before
const functions = require('firebase-functions');
exports.objectChanged = functions.storage.object().onChange((object) => {
return console.log('File name is: ', object.name);
});
// after
const functions = require('firebase-functions');
exports.objectFinalized = functions.storage.object().onFinalize((object) => {
return console.log('File name is: ', object.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 2.0.0 and higher 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
- Node.js 8 (deprecated on June 8, 2020) Deployment of functions to the Node.js 8 runtime was disabled in the Firebase CLI on December 15, 2020. Execution of already-deployed functions will stop at some point in the future; if you have deployed functions to the Node.js 8 runtime, we recommend that you upgrade to the Node.js 16 runtime.
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"}
- Optionally, test your changes using the Firebase Local Emulator Suite.
- 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.
Reduce the number of cold starts
To set minimum number of instances for a function in source code, use the
runWith
parameter. This runtime option accepts
a JSON object conforming to the
RuntimeOptions
interface, which defines the value for minInstances
. For example,
this function sets a minimum of 5 instances to keep warm:
exports.getAutocompleteResponse = functions
.runWith({
// Keep 5 instances warm for this latency-critical function
minInstances: 5,
})
.https.onCall((data, context) => {
// Autocomplete a 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 = functions .runWith({ // 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, }) .https.onRequest((req, res) => { // render some html });
Limit the maximum number of instances for a function
To set maximum instances in function source code, use the
runWith
parameter. This runtime option accepts
a JSON object conforming to the
RuntimeOptions
interface, which defines
values for maxInstances
. For example, this function sets a limit of 100
instances in order to not overwhelm a hypothetical legacy database:
exports.mirrorOrdersToLegacyDatabase = functions
.runWith({
// Legacy database only supports 100 simultaneous connections
maxInstances: 100,
})
.firestore.document("orders/{orderId}")
.onWrite((change, context) => {
// 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
runWith
parameter introduced in Firebase SDK for Cloud Functions 2.0.0. This runtime option accepts
a JSON object conforming to the
RuntimeOptions
interface, which defines values for timeoutSeconds
and memory
.
For example, this storage function uses 1GB of memory and times out after
300 seconds:
exports.convertLargeFile = functions
.runWith({
// Ensure the function has enough memory and time
// to process large files
timeoutSeconds: 300,
memory: "1GB",
})
.storage.object()
.onFinalize((object) => {
// Do some complicated things that take a lot of memory and time
});
The maximum value for timeoutSeconds
is 540
, or 9 minutes.
The amount of memory granted to a function corresponds to the CPU allocated
for the function, as detailed in this list of valid values for memory
:
128MB
— 200MHz256MB
— 400MHz512MB
— 800MHz1GB
— 1.4 GHz2GB
— 2.4 GHz4GB
— 4.8 GHz8GB
— 4.8 GHz
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.