Building a one-to-many Pub/Sub system

Stay organized with collections Save and categorize content based on your preferences.


This tutorial walks you through setting up a simple set of applications that communicate by sending messages through Pub/Sub rather than synchronous RPCs. By decoupling applications, messaging:

  • Makes applications more robust
  • Might simplify development

For example, the caller (publisher) does not need the receiver (subscriber) to be up and available. It simply sends a message to Pub/Sub. Nor does the publisher need to know which and how many subscriber applications need to receive the message. As a result, the service can be relied upon to deliver the message to one or more subscriber applications whenever they are available.


System overview

In this tutorial, you start a publisher application that sends a "Hello, World!" message to two subscribers using one-to-many communication, as illustrated below:

Diagram of the
  topic, its attached subscriptions, and the publisher and subscriber
  applications that send message to and receive messages from Cloud

The two subscriber applications use the same code, but you start them at different times. This process demonstrates how Pub/Sub enables asynchronous communication. To build this system, you:

  1. Create the Pub/Sub topic and subscriptions needed.
  2. Create a service account that the applications use for authentication.
  3. Set up IAM permissions.
  4. Start three independent applications: one publisher and two subscribers.

Tutorial setup

Set up your Google Cloud project and Pub/Sub topic and subscriptions

  1. Log into Google Cloud console.

    Go to the Google Cloud console

    If you're new to Cloud, click Activate and follow the prompts to set up your Cloud account.

  2. Select an existing project or create a new one. A default project is created for you the first time you use Google Cloud.

    In the Home section of the Google Cloud console, make a note of the Project ID. You use this value to set your current Cloud Storage project during the gcloud CLI initialization process. You also pass this ID to the Python script as you start the publisher and subscriber applications.

  3. Go to the Pub/Sub section of the Google Cloud console.

    Go to the Pub/Sub section

    Follow the prompt to enable the API.

  4. Click Create a topic. Publishing applications send messages to topics. Use hello_topic as the Name.

  5. In the Topic details page, click Create Subscription:

    1. Name the subscription sub_one. Do not change any of the default settings. You are creating a StreamingPull subscription, which is a type of pull subscription.

    2. Use the same procedure to create another subscription attached to hello_topic, named sub_two.

      You can click the topic name in the Topics view to see the new subscriptions or you can change to the Subscriptions view.

At this point, your Pub/Sub environment is ready to manage message flow between the publishing and subscribing applications.

Create service account credentials

  1. Create a service account:

    1. In the Google Cloud console, go to the Service Accounts page.

      Go to Service Accounts

    2. Select your project.

    3. Click Create Service Account.

    4. In the Service account name field, enter a name, such as pubsub-tutorial. The Google Cloud console fills in the Service account ID field based on this name.

    5. Optional: In the Service account description field, enter a description for the service account.

    6. Click Create and continue.

    7. For the tutorial, the service account needs publishing and subscribing permissions. Use the Select a role dropdown to add the Pub/Sub Publisher role.

      The Service
account permissions dialog, using the string 'pub' to filter for
Pub/Sub roles

    8. Click Add another role and add Pub/Sub Subscriber.

      The Service
account permissions dialog, with Pub/Sub Publisher and Pub/Sub subscriber,
clicking the Continue button

    9. Click Done to finish creating the service account.

      Do not close your browser window. You will use it in the next step.

  2. Download a JSON key for the service account you just created. The client library uses the key to access the Pub/Sub API.

    1. In the Google Cloud console, click the email address for the service account that you created.
    2. Click Keys.
    3. Click Add key, then click Create new key.
    4. Click Create. A JSON key file is downloaded to your computer.

      The key is sent to your Downloads folder. For the purposes of this tutorial, you can leave it there.

    5. Rename the key file to ~/Downloads/key.json.

    6. Click Close.

Install the Google Cloud CLI

  1. Follow the instructions for installing and initializing the Google Cloud CLI.

    • While initializing the gcloud CLI, select the option to enter a project ID and enter the ID of the project that you created or chose in the setup section.

    • You can return to this tutorial after you install and initialize the gcloud CLI. You do not need to install other components or download the Cloud Client Libraries.

    After you have installed the gcloud CLI, you can use the Google Cloud CLI perform Pub/Sub operations in Compute Engine.

  2. Start a new terminal before using these gcloud commands:

    gcloud pubsub topics list
    gcloud pubsub subscriptions list

    You can also use the gcloud config set project PROJECT_ID to change the project from the one you set up during initialization.

Get Python and set up a virtual environment

This tutorial provides a usage example, so you don't need to follow the example shown in the virtual environment setup section. You can return to this tutorial after installing the virtual environment.

Check out the publisher and subscriber code

  1. Create a project folder to contain the Pub/Sub Python files needed for this tutorial. Then change to it and download the code:

     git clone
  2. Close any open terminals before proceeding.

Set up three terminals

  1. Start one terminal for each tutorial application (one publisher and two subscribers). In each of the terminals, perform all of the operations in this section. For convenience, we refer to these terminals as:

    • publisher terminal
    • sub_one terminal
    • sub_two terminal
  2. Create a Python virtual environment and activate it.

    In the first terminal, run this command to create and activate a virtual environment named pyenv-qs:


    python -m venv pyenv-qs
    source pyenv-qs/bin/activate


    py -m venv pyenv-qs

    In the other two terminals, run the following command:


    source pyenv-qs/bin/activate



    After you run the activate command, your command prompt should include (pyenv-qs) $.

    You can also point your virtual environment to a different Python version.

  3. Install the Pub/Sub Python client library using pip:

    python -m pip install --user --upgrade google-cloud-pubsub

    Associate the JSON key with the service account. You assigned the key Pub/Sub roles when you created the service account credentials. The Pub/Sub client libraries access the environment variable GOOGLE_APPLICATION_CREDENTIALS and are granted the roles and permissions associated with the service account.


    export GOOGLE_APPLICATION_CREDENTIALS=~/Downloads/key.json


  4. Set up an environment variable with your current project ID. This gcloud command determines your currently selected project ID and sets it as a variable:


    export PROJECT=`gcloud config get-value project`


    $env:PROJECT=$(gcloud config get-value project)

    To verify that your current Google Cloud is correctly registered as this variable:


    echo $PROJECT


  5. Change to your project folder, then navigate to the tutorial sample folder:

    cd python-pubsub/samples/snippets/quickstart/

Start the apps and observe message flow

Start the Subscriber 1 application

In the sub_one terminal, start Subscriber 1:


python $PROJECT sub_one


py $env:PROJECT sub_one

Once started, this application opens a bidirectional streaming connection with the server. Pub/Sub delivers messages over the stream.

Subscriber 1
  application begins listening for messages on the sub_one subscription.

Start the Publisher application

In the publisher terminal, start the Publisher application:


python $PROJECT hello_topic


py $env:PROJECT hello_topic

After the publisher application starts, the Pub/Sub system does the following:

  • The Publisher application sends a "Hello, World!" message to Pub/Sub while remaining unaware of any existing subscriptions. The server also assigns a message ID.

  • The Subscriber 1 application receives the 'Hello World' message, prints it, and sends an acknowledgment to Pub/Sub.

  • The Publisher application prints the acknowledgement. The acknowledgment tells Pub/Sub that the message has been processed successfully and does not need to be re-sent to this or any other sub_one subscriber.

Pub/Sub removes the message from sub_one.

The Publisher
  application publishes the message and assigns a message ID. The Subscriber 1
  application receives the 'Hello World' message and sends an

Start the Subscriber 2 application

In the sub_two terminal, start Subscriber 2:


python $PROJECT sub_two


py $env:PROJECT sub_two

This subscriber receives messages delivered to the sub_two subscription. Subscriber 2 reuses the script. The difference is that Subscriber 2 isn't started until after the Publisher has sent the message to the topic and subscriptions. If Publisher were calling Subscriber 2 directly, the publishing application would either have to wait until Subscriber 2 comes up or it would have to time out. Pub/Sub manages this process by effectively saving the message for Subscriber 2.

Subscriber 2
  starts listening and receives the message that was waiting for it in

You are now ready to develop with Pub/Sub!

How did it go?

Additional resources and links are available on the Pub/Sub support page.

Clean up

  1. Stop all running applications.

  2. Delete the ~/pubsub-quickstart directory from your local environment.

  3. Shut down the tutorial project in the IAM & admin section of the Google Cloud console.

  4. Remove the service account credentials: rm ~/Downloads/key.json

What's next

Here are some things that you can try:

  • Examine the tutorial's and code and browse other Pub/Sub samples on Github. As an exercise, create a version of that publishes the local time every second.

  • Learn to batch messages.

  • Using Push subscriptions, receive messages that trigger App Engine endpoints or Cloud Functions.

  • Retrieve previously acknowledged messages using replay. By default, Pub/Sub removes acknowledged messages from subscriptions. In this tutorial, for instance, you would not be able to rerun to receive the "Hello, World!" message again. The replay feature allows you to set up subscriptions so that you can receive messages after they have been acknowledged.

  • Get started with client libraries in other languages.