Background Functions

You use background functions when you want to have your Cloud Function invoked indirectly in response to an event, such as a message on a Google Cloud Pub/Sub topic, a change in a Google Cloud Storage bucket, or a Firebase event.

For information on how to retry background functions, see Retrying Background Functions.

Function Parameters

Background functions are passed arguments holding data associated with the event that triggered the function's execution. The parameters of background functions are described below:

Node.js 6

Your function is passed the arguments (event, callback):

Property Description Type
event An object representing the event that triggered the function. Object
event.data The data object for the event. Its type depends on the event. Cloud Storage Object or PubsubMessage
event.context The context object for the event. Object
event.context.eventId A unique ID for the event. For example: "70172329041928". String
event.context.timestamp The date/time this event was created. For example: "2018-04-09T07:56:12.975Z". String (ISO 8601)
event.context.eventType The type of the event. For example: "google.pubsub.topic.publish". String
event.context.resource The resource that emitted the event. String
callback

A callback to signal completion of the function's execution. Follows the "errback" convention, which interprets the first argument as an error:

callback();                    // Success
callback(null, 'Success!');    // Success
callback(1);                   // Error
callback(new Error('Failed')); // Error
Function

You should always either invoke the callback or return a Promise when your function has completed. Otherwise, your function may continue to run and be forcibly terminated by the system. Code that is in scope after the callback function has been called (or a Promise has been returned) is not guaranteed to execute. You should ensure that your function has completed all its work, including any asynchronous processes, prior to calling the callback or returning a Promise. For more information, see Terminating background functions.

Node.js 8 (Beta)

Your function is passed the arguments (data, context, callback):

Property Description Type
data The data object for the event. Its type depends on the event. Cloud Storage Object or PubsubMessage
context The context object for the event. Object
context.eventId A unique ID for the event. For example: "70172329041928". String
context.timestamp The date/time this event was created. For example: "2018-04-09T07:56:12.975Z". String (ISO 8601)
context.eventType The type of the event. For example: "google.pubsub.topic.publish". String
context.resource The resource that emitted the event. String
callback

A callback to signal completion of the function's execution. Follows the "errback" convention, which interprets the first argument as an error:

callback();                    // Success
callback(null, 'Success!');    // Success
callback(1);                   // Error
callback(new Error('Failed')); // Error
Function

You should always signal that your function has completed. To signal function completion, you can:

  • return a value or a Promise,
  • wrap your function using the async keyword (which causes your function to implicitly return a Promise), or
  • invoke the callback argument.
Code that is in scope after the callback function has been called (or a Promise has been returned) is not guaranteed to execute. You should ensure that your function has completed all its work, including any asynchronous processes, prior to calling the callback or returning a Promise. For more information, see Terminating background functions.

Python (Beta)

Your function is passed the arguments (data, context):

Property Description Type
data A dictionary containing the data for the event. Its format depends on the event. Cloud Storage Object or PubsubMessage
context The context object for the event. Context
context.eventId A unique ID for the event. For example: "70172329041928". String
context.timestamp The date/time this event was created. For example: "2018-04-09T07:56:12.975Z". String (ISO 8601)
context.eventType The type of the event. For example: "google.pubsub.topic.publish". String
context.resource The resource that emitted the event. String

The contents of the event's data object depend on the trigger for which the function was registered (for example, Cloud Pub/Sub or Cloud Storage). In the case of direct-triggered functions (triggered using the gcloud functions call command), the event data contains the message you sent directly.

Cloud Pub/Sub Example

This example shows a Cloud Function triggered by Cloud Pub/Sub events. Every time a message is published to a Cloud Pub/Sub topic, the function is invoked, and a greeting using data derived from the Pub/Sub message is written to the log.

Node.js 6

/**
 * Background Cloud Function to be triggered by Pub/Sub.
 * This function is exported by index.js, and executed when
 * the trigger topic receives a message.
 *
 * @param {object} event The Cloud Functions event.
 * @param {function} callback The callback function.
 */
exports.helloPubSub = (event, callback) => {
  const pubsubMessage = event.data;
  const name = pubsubMessage.data ? Buffer.from(pubsubMessage.data, 'base64').toString() : 'World';

  console.log(`Hello, ${name}!`);

  callback();
};

Node.js 8 (Beta)

/**
 * Background Cloud Function to be triggered by Pub/Sub.
 * This function is exported by index.js, and executed when
 * the trigger topic receives a message.
 *
 * @param {object} data The event payload.
 * @param {object} context The event metadata.
 */
exports.helloPubSub = (data, context) => {
  const pubSubMessage = data;
  const name = pubSubMessage.data ? Buffer.from(pubSubMessage.data, 'base64').toString() : 'World';

  console.log(`Hello, ${name}!`);
};

Python (Beta)

def hello_pubsub(data, context):
    """Background Cloud Function to be triggered by Pub/Sub.
    Args:
         data (dict): The dictionary with data specific to this type of event.
         context (google.cloud.functions.Context): The Cloud Functions event
         metadata.
    """
    import base64

    if 'data' in data:
        name = base64.b64decode(data['data']).decode('utf-8')
    else:
        name = 'World'
    print('Hello, {}!'.format(name))

For more information about deploying Cloud Functions triggered by Cloud Pub/Sub events, see Google Cloud Pub/Sub Triggers and Cloud Pub/Sub Tutorial.

Cloud Storage Example

This example shows a Cloud Function triggered by Cloud Storage events. Every time an object is created in a Cloud Storage bucket, the function is invoked, and a message about the change is written to the log.

Node.js 6

/**
 * Background Cloud Function to be triggered by Cloud Storage.
 *
 * @param {object} event The Cloud Functions event.
 * @param {function} callback The callback function.
 */
exports.helloGCS = (event, callback) => {
  const file = event.data;

  if (file.resourceState === 'not_exists') {
    console.log(`File ${file.name} deleted.`);
  } else if (file.metageneration === '1') {
    // metageneration attribute is updated on metadata changes.
    // on create value is 1
    console.log(`File ${file.name} uploaded.`);
  } else {
    console.log(`File ${file.name} metadata updated.`);
  }

  callback();
};

Node.js 8 (Beta)

/**
 * Background Cloud Function to be triggered by Cloud Storage.
 *
 * @param {object} data The event payload.
 * @param {object} context The event metadata.
 */
exports.helloGCS = (data, context) => {
  const file = data;
  if (file.resourceState === 'not_exists') {
    console.log(`File ${file.name} deleted.`);
  } else if (file.metageneration === '1') {
    // metageneration attribute is updated on metadata changes.
    // on create value is 1
    console.log(`File ${file.name} uploaded.`);
  } else {
    console.log(`File ${file.name} metadata updated.`);
  }
};

Python (Beta)

def hello_gcs(data, context):
    """Background Cloud Function to be triggered by Cloud Storage.
    Args:
         data (dict): The dictionary with data specific to this type of event.
         context (google.cloud.functions.Context): The Cloud Functions
         event metadata.
    """
    print("File: {}.".format(data['objectId']))

For more information about deploying Cloud Functions triggered by Cloud Storage events, see Cloud Storage Triggers and Cloud Storage Tutorial.

Next steps

Was this page helpful? Let us know how we did:

Send feedback about...

Cloud Functions Documentation