Google Cloud Pub/Sub Triggers

Cloud Functions can be triggered by messages published to Cloud Pub/Sub topics in the same GCP project as the function. 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.

Event types

There is a single Cloud Pub/Sub event used by Cloud Functions, and it has the trigger type value google.pubsub.topic.publish.

This event is sent when a message is published to a Cloud Pub/Sub topic that is specified when a function is deployed. Every message published to this topic will trigger function execution with message contents passed as input data.

Event structure

Cloud Functions triggered from a Cloud Pub/Sub topic will be sent events conforming to the PubsubMessage type, with the caveat that publishTime and messageId are not directly available in the PubsubMessage. Instead, you can access publishTime and messageId via the event ID and timestamp properties of the event metadata. This metadata is accessible via the context object that is passed to your function when it is invoked.

The payload of the PubsubMessage object, the data published to the topic, is stored as a base64-encoded string in the data attribute of the PubsubMessage. To extract the payload of the PubsubMessage object, you may need to decode the data attribute as shown in the examples below.

Sample code

Node.js 8/10

/**
 * 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} pubSubEvent The event payload.
 * @param {object} context The event metadata.
 */
exports.helloPubSub = (pubSubEvent, context) => {
  const name = pubSubEvent.data
    ? Buffer.from(pubSubEvent.data, 'base64').toString()
    : 'World';

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

Node.js 6 (Deprecated)

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

Python

def hello_pubsub(event, context):
    """Background Cloud Function to be triggered by Pub/Sub.
    Args:
         event (dict):  The dictionary with data specific to this type of
         event. The `data` field contains the PubsubMessage message. The
         `attributes` field will contain custom attributes if there are any.
         context (google.cloud.functions.Context): The Cloud Functions event
         metadata. The `event_id` field contains the Pub/Sub message ID. The
         `timestamp` field contains the publish time.
    """
    import base64

    print("""This Function was triggered by messageId {} published at {}
    """.format(context.event_id, context.timestamp))

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

Go


// Package helloworld provides a set of Cloud Functions samples.
package helloworld

import (
	"context"
	"log"
)

// PubSubMessage is the payload of a Pub/Sub event.
type PubSubMessage struct {
	Data []byte `json:"data"`
}

// HelloPubSub consumes a Pub/Sub message.
func HelloPubSub(ctx context.Context, m PubSubMessage) error {
	name := string(m.Data)
	if name == "" {
		name = "World"
	}
	log.Printf("Hello, %s!", name)
	return nil
}

Publishing a message from within a function

You can also publish a message to a Pub/Sub topic from within a function. This lets you trigger subsequent Cloud Function invocations using Cloud Pub/Sub messages. You can use this technique to:

  • Chain sequential function calls together.
  • Distribute (or "fan out") groups of tasks in parallel across multiple Cloud Function instances.

In the following example, an HTTP publish function sends a message to a Pub/Sub topic, and that in turn triggers a subscribe function.

This snippet shows the publish function that publishes a message to a Pub/Sub topic:

Node.js

/**
 * Publishes a message to a Cloud Pub/Sub Topic.
 *
 * @example
 * gcloud functions call publish --data '{"topic":"[YOUR_TOPIC_NAME]","message":"Hello, world!"}'
 *
 *   - Replace `[YOUR_TOPIC_NAME]` with your Cloud Pub/Sub topic name.
 *
 * @param {object} req Cloud Function request context.
 * @param {object} req.body The request body.
 * @param {string} req.body.topic Topic name on which to publish.
 * @param {string} req.body.message Message to publish.
 * @param {object} res Cloud Function response context.
 */
exports.publish = async (req, res) => {
  if (!req.body.topic || !req.body.message) {
    res
      .status(500)
      .send(
        'Missing parameter(s); include "topic" and "subscription" properties in your request.'
      );
    return;
  }

  console.log(`Publishing message to topic ${req.body.topic}`);

  // References an existing topic
  const topic = pubsub.topic(req.body.topic);

  const messageObject = {
    data: {
      message: req.body.message,
    },
  };
  const messageBuffer = Buffer.from(JSON.stringify(messageObject), 'utf8');

  // Publishes a message
  try {
    await topic.publish(messageBuffer);
    res.status(200).send('Message published.');
  } catch (err) {
    console.error(err);
    res.status(500).send(err);
    return Promise.reject(err);
  }
};

This snippet shows the subscribe function that is triggered when the message is published to the Pub/Sub topic:

Node.js

/**
 * Triggered from a message on a Cloud Pub/Sub topic.
 *
 * @param {object} pubsubMessage The Cloud Pub/Sub Message object.
 * @param {string} pubsubMessage.data The "data" property of the Cloud Pub/Sub Message.
 */
exports.subscribe = pubsubMessage => {
  // Print out the data from Pub/Sub, to prove that it worked
  console.log(Buffer.from(pubsubMessage.data, 'base64').toString());
};

In production, you might use the cURL command-line utility to invoke the publish function, as follows:

curl https://GCF_REGION-GCP_PROJECT_ID.cloudfunctions.net/publish -X POST  -d "{\"topic\": \"PUBSUB_TOPIC\", \"message\":\"YOUR_MESSAGE\"}" -H "Content-Type: application/json"

But for testing and debugging, you could instead use the gcloud functions call command to call the function directly. The following steps describe how to run the above example using the gcloud functions call command:

  1. Create a Pub/Sub topic, where MY_TOPIC is the name of the new topic you are creating:

    gcloud pubsub topics create MY_TOPIC
  2. Deploy the publish function, where RUNTIME is the name of the runtime you are using, such as nodejs8:

    gcloud functions deploy publish --trigger-http --runtime RUNTIME
  3. Deploy the subscribe function:

    gcloud functions deploy subscribe --trigger-topic MY_TOPIC --runtime RUNTIME
  4. Directly invoke the publish function using the gcloud functions call command, and supply the required data as JSON in the --data argument:

    gcloud functions call publish --data '{"topic":"MY_TOPIC","message":"Hello World!"}'
  5. Check the logs for the subscribe function. Note that it may take a few minutes for your results to appear in the log:

    gcloud functions logs read subscribe

You should see output resembling the following:

D    ...Function execution started
I    ...{"data":{"message":"Hello World!"}}
D    ...Function execution took 753 ms, finished with status: 'ok'

Deploying your function

The following gcloud command deploys a function that will be triggered when a message is published to a Cloud Pub/Sub topic:

Node.js 8

gcloud functions deploy FUNCTION_NAME --runtime nodejs8 --trigger-topic TOPIC_NAME

Node.js 10 (Beta)

gcloud functions deploy FUNCTION_NAME --runtime nodejs10 --trigger-topic TOPIC_NAME

Node.js 6 (Deprecated)

gcloud functions deploy FUNCTION_NAME --runtime nodejs6 --trigger-topic TOPIC_NAME

Python

gcloud functions deploy FUNCTION_NAME --runtime python37 --trigger-topic TOPIC_NAME

Go

gcloud functions deploy FUNCTION_NAME --runtime go111 --trigger-topic TOPIC_NAME

where FUNCTION_NAME is the name of the function and TOPIC_NAME is the name of the Cloud Pub/Sub topic to which the function will be subscribed. If the topic doesn't exist, it is created during deployment.

See the Cloud Pub/Sub Tutorial for a complete example of how to use Cloud Pub/Sub triggers.

Legacy Cloud Pub/Sub triggers

The gcloud command below deploys a function that is triggered by legacy Cloud Pub/Sub notifications on a specific topic. These notifications are supported for legacy functions already consuming these events. However, we recommend using the --trigger-topic flag instead, as the legacy notifications might be removed at a future date.

Node.js 8

gcloud functions deploy FUNCTION_NAME --runtime nodejs8 --trigger-resource TOPIC_NAME --trigger-event providers/cloud.pubsub/eventTypes/topic.publish

Node.js 10 (Beta)

gcloud functions deploy FUNCTION_NAME --runtime nodejs10 --trigger-resource TOPIC_NAME --trigger-event providers/cloud.pubsub/eventTypes/topic.publish

Node.js 6 (Deprecated)

gcloud functions deploy FUNCTION_NAME --runtime nodejs6 --trigger-resource TOPIC_NAME --trigger-event providers/cloud.pubsub/eventTypes/topic.publish

Python

gcloud functions deploy FUNCTION_NAME --runtime python37 --trigger-resource TOPIC_NAME --trigger-event providers/cloud.pubsub/eventTypes/topic.publish

Go

gcloud functions deploy FUNCTION_NAME --runtime go111 --trigger-resource TOPIC_NAME --trigger-event providers/cloud.pubsub/eventTypes/topic.publish

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.

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

Send feedback about...

Cloud Functions Documentation