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 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 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))

Go (Beta)

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

import (
	"context"
	"log"
)

// PubSubMessage is the payload of a Pub/Sub event. Please refer to the docs for
// additional information regarding Pub/Sub events.
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
}

Deploying your function

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

Node.js 6

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

Node.js 8 (Beta)

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

Python (Beta)

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

Go (Beta)

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.

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 6

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

Node.js 8 (Beta)

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

Python (Beta)

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

Go (Beta)

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