Background Functions

You use background functions when you want to have your Cloud Function invoked indirectly via a message on a Google Cloud Pub/Sub topic, or a change in a Google Cloud Storage bucket. Background functions take two parameters, event and an optional callback function.

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

Event Parameter

The event parameter holds the data associated with the event that triggered the execution of the function along with metadata about the event itself. The event data is contained in a data property of the event:

Property Description Type
eventId A unique ID for the event. String
timestamp The date/time this event was created. String (ISO 8601)
eventType The type of the event. String
resource The resource that emitted the event. String
data The event data. Object

The contents of the data property depend on the trigger for which the function was registered (for example, the Cloud Pub/Sub topic or Cloud Storage bucket). In the case of self-triggered functions (for example, manually publishing an event to Cloud Pub/Sub), the data property contains the message you published.

Cloud Pub/Sub Example

You might use the following command to invoke a function that is normally triggered by messages sent to a Cloud Pub/Sub topic:

gcloud beta functions call helloPubSub --data '{"data":"dGVzdCB1c2Vy"}'

where dGVzdCB1c2Vy is the base64 encoded form of "test user".

And here is the function:

Node.js

/**
 * Background Cloud Function to be triggered by Pub/Sub.
 *
 * @param {object} event The Cloud Functions event.
 * @param {function} callback The callback function.
 */
exports.helloPubSub = function (event, callback) {
  const pubsubMessage = event.data;
  const name = pubsubMessage.data ? Buffer.from(pubsubMessage.data, 'base64').toString() : 'World';

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

  callback();
};

After invoking the function, you should see Hello, test user! in the function's logs.

See also:

Cloud Storage Example

You might use the following command to invoke a function that is normally triggered by changes to objects in a Cloud Storage bucket:

gcloud beta functions call helloGCS --data '{"name":"test.txt"}'

And here is the function:

Node.js

/**
 * Background Cloud Function to be triggered by Cloud Storage.
 *
 * @param {object} event The Cloud Functions event.
 * @param {function} callback The callback function.
 */
exports.helloGCS = function (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();
};

After invoking the function, you should see File test.txt uploaded. in the function's logs.

See also:

Callback Parameter

The callback parameter is used to signal completion of your function. This parameter is itself a function which conforms to the errback convention, or "error first callback", which always interprets the first argument as an error.

For example, the following would be considered a successful outcome:

  • callback();
  • callback(null, 'Success!');

Whereas the following would be considered an error:

  • callback(1);
  • callback(new Error('I\'m an error'));

Using Promises

By default, background functions expect the callback to signal the completion of the function. However, dealing with external libraries that return Promises can be cumbersome, so we also allow background functions to optionally return a Promise rather than explicitly invoking a callback. When returning a Promise, remember to omit the callback argument from the method signature.

For example:

Node.js

/**
 * Background Cloud Function that returns a Promise. Note that we don't pass
 * a "callback" argument to the function.
 *
 * @param {object} event The Cloud Functions event.
 * @param {object} event.data The event data.
 * @returns {Promise}
 */
exports.helloPromise = function helloPromise (event) {
  const request = require('request-promise');

  return request({
    uri: event.data.endpoint
  });
};

You can alternatively return discrete values from the function, and Cloud Functions will handle the callback. This is particularly useful if your function does not have any asynchronous calls, or there are conditions under which you can return a synchronous response. When you use this approach, a return value is considered a successful outcome, but you can also throw an error to trigger a failure outcome.

For example:

Node.js

/**
 * Background Cloud Function that returns synchronously. Note that we don't pass
 * a "callback" argument to the function.
 *
 * @param {object} event The Cloud Functions event.
 * @param {object} event.data The event data.
 */
exports.helloSynchronous = function helloSynchronous (event) {
  // This function returns synchronously
  if (event.data.something === true) {
    return 'Something is true!';
  } else {
    throw new Error('Something was not true!');
  }
};

Next steps

Monitor your resources on the go

Get the Google Cloud Console app to help you manage your projects.

Send feedback about...

Cloud Functions Documentation