Google Cloud Pub/Sub Triggers

Cloud Functions can be triggered by messages published to Cloud Pub/Sub topics. Cloud Pub/Sub is a globally distributed message bus that automatically scales as you need it and provides a foundation for building your own robust, global services.

The following gcloud command deploys a function that will be triggered by Cloud Pub/Sub:

gcloud beta functions deploy helloWorld --stage-bucket cloud-functions --trigger-topic hello_world
Argument Description
--trigger-topic <name> The name of the Cloud Pub/Sub topic to which the function will be subscribed.

Cloud Pub/Sub Events

Cloud Functions triggered from Cloud Pub/Sub topic events will be sent an event containing a PubsubMessage object. The format of the PubsubMessage is as per the published format for PubsubMessage objects.

The payload of the PubsubMessage (the data you published to the topic) is contained within the PubsubMessage as a base64 encoded string in the data attribute of the PubsubMessage. To extract the payload of the PubsubMessage you need to decode the data attribute.

For example:

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();
};

Next steps

See the Cloud Pub/Sub Tutorial for an example of how to implement a background function that is triggered by Cloud Pub/Sub.

Monitor your resources on the go

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

Send feedback about...

Cloud Functions Documentation