Skip to main content

Cloud Functions v2 With Pub/Sub

One of the characteristics of many of today's cloud solutions is that there are many ways of doing the same thing. Cloud functions and Pub/Sub follow this trend. I'll describe two of the ways of using the newer version of cloud functions (v2) with a Pub/Sub trigger.

tip

Use the eventarc mode unless you specifically need some of the benefts of the https mode, such as the increased execution time limit.

The eventarc way

This method creates a cloud function that's triggered by Pub/Sub directly, without using http requests of any sort.

  • Create a Cloud Function as you normally would and enable the required API if needed
  • During the creation process, click on "Add eventarc trigger" in the "Trigger" section ADD EVENTARC TRIGGER
  • Select "First-party" as trigger type
  • Select "Cloud Pub/Sub" as Event provider
  • Select "google.cloud.pubsub.topic.v1.messagePublished" as event
  • Select the desired topic or create one if needed Step 2 Trigger definition

You can now publish the function and test it by opening the shell and using the command:

gcloud pubsub topics publish TOPICNAME --message "Test Message"

where TOPICNAME is the name of the topic you selected.

This should trigger the newly created function, to check if it worked you can use its logs!

Keep in mind that given the http nature of cloud functions a POST request can still trigger it.

The https way

This methods creates a https-triggered cloud function and uses a Pub/Sub subscriber topic to push the message to the function.

  • Create a Cloud Function as you normally would and enable the required API if needed
  • Create a new Pub/Sub topic, deselect the "Add a default subscription" option
  • Go to the Pub/Sub page and create a new subscription
  • Give a name the the subscription, select "Push" as delivery type and insert the endpoint of your cloud function as "Endpoint URL"
tip

If you didn't select the "Allow unauthenticated" option during the creation of your cloud function, you will need to enable authentication at this step and select a service account with at least the "roles/cloudfunctions.invoker" role.

tip

Depending on your use case, you should also enable exponential backoff delay and increase the acknowledgement deadline to 20 seconds or more.

The end result should be something like this: Push topic and authentication

You can now test the cloud function by opening the shell and using the command:

gcloud pubsub topics publish TOPICNAME --message "Test Message"

where TOPICNAME is the name of the topic you created.