Managing Topics and Subscriptions

This document gives an overview of how to manage topics and subscriptions in Google Cloud Pub/Sub.

Managing Topics

You can create, delete, and view topics using the API, the Cloud Platform Console, or the gcloud command-line tool for a complete list of Google Cloud Pub/Sub gcloud commands.

For an introduction to the Cloud Platform Console, see the Cloud Platform Console Quickstart.

Create a topic

You must first create a topic before you can publish or subscribe to it. Here is an example showing how to create a topic:

Protocol

Request:

PUT https://pubsub.googleapis.com/v1/projects/myproject/topics/mytopic

Response:

200 OK
{
 "name": "projects/myproject/topics/mytopic"
}

GCLOUD

  gcloud beta pubsub topics create myTopic

C#

For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

TopicName topicName = new TopicName(projectId, topicId);
try
{
    publisher.CreateTopic(topicName);
}
catch (RpcException e)
when (e.Status.StatusCode == StatusCode.AlreadyExists)
{
    // Already exists.  That's fine.
}

Go

For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

t, err := client.CreateTopic(ctx, topic)
if err != nil {
	return err
}
fmt.Printf("Topic created: %v\n", t)

Java

For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
  // projectId <=  unique project identifier, eg. "my-project-id"
  // topicId <= "my-topic-id"
  TopicName topicName = TopicName.create(projectId, topicId);
  Topic topic = topicAdminClient.createTopic(topicName);
  return topic;
}

Node.js

For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

function createTopic (topicName) {
  // Instantiates a client
  const pubsub = PubSub();

  // Creates a new topic, e.g. "my-new-topic"
  return pubsub.createTopic(topicName)
    .then((results) => {
      const topic = results[0];

      console.log(`Topic ${topic.name} created.`);

      return topic;
    });
}

PHP

For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

use Google\Cloud\PubSub\PubSubClient;

/**
 * Creates a Pub/Sub topic.
 *
 * @param string $projectId  The Google project ID.
 * @param string $topicName  The Pub/Sub topic name.
 */
function create_topic($projectId, $topicName)
{
    $pubsub = new PubSubClient([
        'projectId' => $projectId,
    ]);
    $topic = $pubsub->createTopic($topicName);

    printf('Topic created: %s' . PHP_EOL, $topic->name());
}

Python

For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

def create_topic(topic_name):
    """Create a new Pub/Sub topic."""
    pubsub_client = pubsub.Client()
    topic = pubsub_client.topic(topic_name)

    topic.create()

    print('Topic {} created.'.format(topic.name))

Ruby

For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

pubsub = Google::Cloud::Pubsub.new project: "my-gcp-project-id"

topic = pubsub.create_topic "my-topic"

puts "Topic created #{topic.name}"

Delete a topic

Here is an example showing how to delete a topic:

Protocol

Request:

DELETE https://pubsub.googleapis.com/v1/projects/myproject/topics/mytopic

Response:

200 OK
{
 "name": "projects/myproject/topics/mytopic"
}

GCLOUD

  gcloud beta pubsub topics delete myTopic

C#

For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

TopicName topicName = new TopicName(projectId, topicId);
publisher.DeleteTopic(topicName);

Go

For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

t := client.Topic(topic)
if err := t.Delete(ctx); err != nil {
	return err
}
fmt.Printf("Deleted topic: %v\n", t)

Java

For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
  TopicName topicName = TopicName.create(projectId, topicId);
  topicAdminClient.deleteTopic(topicName);
  return topicName;
}

Node.js

For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

function deleteTopic (topicName) {
  // Instantiates a client
  const pubsub = PubSub();

  // References an existing topic, e.g. "my-topic"
  const topic = pubsub.topic(topicName);

  // Deletes the topic
  return topic.delete()
    .then(() => {
      console.log(`Topic ${topic.name} deleted.`);
    });
}

PHP

For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

use Google\Cloud\PubSub\PubSubClient;

/**
 * Creates a Pub/Sub topic.
 *
 * @param string $projectId  The Google project ID.
 * @param string $topicName  The Pub/Sub topic name.
 */
function delete_topic($projectId, $topicName)
{
    $pubsub = new PubSubClient([
        'projectId' => $projectId,
    ]);
    $topic = $pubsub->topic($topicName);
    $topic->delete();

    printf('Topic deleted: %s' . PHP_EOL, $topic->name());
}

Python

For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

def delete_topic(topic_name):
    """Deletes an existing Pub/Sub topic."""
    pubsub_client = pubsub.Client()
    topic = pubsub_client.topic(topic_name)

    topic.delete()

    print('Topic {} deleted.'.format(topic.name))

Ruby

For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

pubsub = Google::Cloud::Pubsub.new project: "my-gcp-project-id"
topic  = pubsub.topic "my-topic"

topic.delete

puts "Deleted topic my-topic"

When you delete a topic, its subscriptions are not deleted, and the subscription's message backlog is available for subscribers. After a topic is deleted, its subscriptions have the topic name _deleted-topic_.

List topics

Here is an example showing how to get a list of topics:

Protocol

Request:

GET https://pubsub.googleapis.com/v1/projects/myproject/topics

Response:

200 OK
{
  "topics": [
    {
      "name": "projects/myproject/topics/mytopic1"
    },
    {
      "name": "projects/myproject/topics/mytopic2"
    }
  ]
}

GCLOUD

   gcloud beta pubsub topics list

C#

For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

ProjectName projectName = new ProjectName(projectId);
IEnumerable<Topic> topics = publisher.ListTopics(projectName);

Go

For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

var topics []*pubsub.Topic

it := client.Topics(ctx)
for {
	topic, err := it.Next()
	if err == iterator.Done {
		break
	}
	if err != nil {
		return nil, err
	}
	topics = append(topics, topic)
}

return topics, nil

Java

For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
  ListTopicsRequest listTopicsRequest =
      ListTopicsRequest.newBuilder()
          .setProjectWithProjectName(ProjectName.create(projectId))
          .build();
  ListTopicsPagedResponse response = topicAdminClient.listTopics(listTopicsRequest);
  Iterable<Topic> topics = response.iterateAll();
  for (Topic topic : topics) {
    // do something with the topic
  }
  return response;
}

Node.js

For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

function listTopics () {
  // Instantiates a client
  const pubsub = PubSub();

  // Lists all topics in the current project
  return pubsub.getTopics()
    .then((results) => {
      const topics = results[0];

      console.log('Topics:');
      topics.forEach((topic) => console.log(topic.name));

      return topics;
    });
}

PHP

For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

use Google\Cloud\PubSub\PubSubClient;

/**
 * Lists all Pub/Sub topics.
 *
 * @param string $projectId  The Google project ID.
 */
function list_topics($projectId)
{
    $pubsub = new PubSubClient([
        'projectId' => $projectId,
    ]);
    foreach ($pubsub->topics() as $topic) {
        printf('Topic: %s' . PHP_EOL, $topic->name());
    }
}

Python

For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

def list_topics():
    """Lists all Pub/Sub topics in the current project."""
    pubsub_client = pubsub.Client()

    for topic in pubsub_client.list_topics():
        print(topic.name)

Ruby

For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

pubsub = Google::Cloud::Pubsub.new project: "my-gcp-project-id"
topics = pubsub.topics

puts "Topics:"
topics.each do |topic|
  puts topic.name
end
By default, a maximum of 100 results are returned per query. You can specify an alternative value up to 1,000 using the page size parameter.

Managing Subscriptions

This section covers how to create and manage push, pull subscriptions. For an overview and comparison of pull and push subscriptions, see the Subscriber Overview.

Create a Pull Subscription

You must create a subscription to a topic before subscribers can receive messages published to the subscription. You can create a subscription using the Google Cloud Platform Console UI or the gcloud command-line tool, as described in the gcloud Quickstart. Also see the gcloud reference for subscriber commands.

Protocol

Request:

PUT https://pubsub.googleapis.com/v1/projects/myproject/subscriptions/mysubscription
{
  "topic": "projects/someproject/topics/sometopic"
  // Only needed if you are using push delivery
  "pushConfig": {
    "pushEndpoint": "https://myproject.appspot.com/myhandler"
  }
}

Response:

200 OK
{
  "name": "projects/myproject/subscriptions/mysubscription",
  "topic": "projects/someproject/topics/sometopic",
  "pushConfig": {
    "pushEndpoint": "https://myproject.appspot.com/myhandler"
  },
  "ackDeadlineSeconds": 10
}

GCLOUD

   gcloud beta pubsub subscriptions create mySubscription --topic myTopic

C#

For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

TopicName topicName = new TopicName(projectId, topicId);
SubscriptionName subscriptionName = new SubscriptionName(projectId,
    subscriptionId);
try
{
    Subscription subscription = subscriber.CreateSubscription(
        subscriptionName, topicName, pushConfig: null,
        ackDeadlineSeconds: 60);
}
catch (RpcException e)
when (e.Status.StatusCode == StatusCode.AlreadyExists)
{
    // Already exists.  That's fine.
}

Go

For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

sub, err := client.CreateSubscription(ctx, name, pubsub.SubscriptionConfig{
	Topic:       topic,
	AckDeadline: 20 * time.Second,
})
if err != nil {
	return err
}
fmt.Printf("Created subscription: %v\n", sub)

Java

For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
  // eg. projectId = "my-test-project", topicId = "my-test-topic"
  TopicName topicName = TopicName.create(projectId, topicId);
  // eg. subscriptionId = "my-test-subscription"
  SubscriptionName subscriptionName =
      SubscriptionName.create(projectId, subscriptionId);
  // create a pull subscription with default acknowledgement deadline
  Subscription subscription =
      subscriptionAdminClient.createSubscription(
          subscriptionName, topicName, PushConfig.getDefaultInstance(), 0);
  return subscription;
}

Node.js

For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

function createSubscription (topicName, subscriptionName) {
  // Instantiates a client
  const pubsub = PubSub();

  // References an existing topic, e.g. "my-topic"
  const topic = pubsub.topic(topicName);

  // Creates a new subscription, e.g. "my-new-subscription"
  return topic.subscribe(subscriptionName)
    .then((results) => {
      const subscription = results[0];

      console.log(`Subscription ${subscription.name} created.`);

      return subscription;
    });
}

PHP

For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

use Google\Cloud\PubSub\PubSubClient;

/**
 * Creates a Pub/Sub subscription.
 *
 * @param string $projectId  The Google project ID.
 * @param string $topicName  The Pub/Sub topic name.
 * @param string $subscriptionName  The Pub/Sub subscription name.
 */
function create_subscription($projectId, $topicName, $subscriptionName)
{
    $pubsub = new PubSubClient([
        'projectId' => $projectId,
    ]);
    $topic = $pubsub->topic($topicName);
    $subscription = $topic->subscription($subscriptionName);
    $subscription->create();

    printf('Subscription created: %s' . PHP_EOL, $subscription->name());
}

Python

For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

def create_subscription(topic_name, subscription_name):
    """Create a new pull subscription on the given topic."""
    pubsub_client = pubsub.Client()
    topic = pubsub_client.topic(topic_name)

    subscription = topic.subscription(subscription_name)
    subscription.create()

    print('Subscription {} created on topic {}.'.format(
        subscription.name, topic.name))

Ruby

For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

pubsub = Google::Cloud::Pubsub.new project: "my-gcp-project-id"
topic  = pubsub.topic "my-topic"

subscription = topic.subscribe "my-subscription"

puts "Subscription created #{subscription.name}"

Create a Push Subscription

You can create push subscriptions by providing an HTTP endpoint URL, as shown in these examples:

GCLOUD

   gcloud beta pubsub subscriptions create mySubscription --topic myTopic --push-endpoint="https://myapp.appspot.com/push"

Java

For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
  TopicName topicName = TopicName.create(projectId, topicId);
  SubscriptionName subscriptionName =
          SubscriptionName.create(projectId, subscriptionId);

  // eg. endpoint = "https://my-test-project.appspot.com/push"
  PushConfig pushConfig = PushConfig.newBuilder().setPushEndpoint(endpoint).build();

  // acknowledgement deadline in seconds for the message received over the push endpoint
  int ackDeadlineInSeconds = 10;

  Subscription subscription =
          subscriptionAdminClient.createSubscription(
                  subscriptionName, topicName, pushConfig, ackDeadlineInSeconds);
  return subscription;
}

Go

For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

// For example, endpoint is "https://my-test-project.appspot.com/push".
sub, err := client.CreateSubscription(ctx, name, pubsub.SubscriptionConfig{
	Topic:       topic,
	AckDeadline: 10 * time.Second,
	PushConfig:  pubsub.PushConfig{Endpoint: endpoint},
})
if err != nil {
	return err
}
fmt.Printf("Created subscription: %v\n", sub)

Update a subscription

Once a subscription has been created, you can update the push endpoint of a subscription or switch from push to pull and vice versa. Here are examples showing how to update an existing pull or push subscription by specifying a non-empty, valid HTTPs push endpoint URL:

GCLOUD

   gcloud beta pubsub subscriptions modify-push-config mySubscription --push-endpoint="https://anotherapp.appspot.com/push"

Java

For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
  SubscriptionName subscriptionName = SubscriptionName.create(projectId, subscriptionId);
  PushConfig pushConfig = PushConfig.newBuilder().setPushEndpoint(endpoint).build();
  subscriptionAdminClient.modifyPushConfig(subscriptionName, pushConfig);
}

Go

For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

// For example, endpoint is "https://my-test-project.appspot.com/push".
subConfig, err := client.Subscription(name).Update(ctx, pubsub.SubscriptionConfigToUpdate{
	PushConfig: &pubsub.PushConfig{Endpoint: endpoint},
})
if err != nil {
	return err
}
fmt.Printf("Updated subscription config: %#v", subConfig)

List subscriptions

You can list all subscriptions in a project, or only subscriptions to a particular topic. See Access Control for details on limiting access, if needed. Here are examples showing how to list all subscriptions in a project.

GCLOUD

   gcloud beta pubsub subscriptions list

C#

For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

ProjectName projectName = new ProjectName(projectId);
IEnumerable<Subscription> subscriptions =
    subscriber.ListSubscriptions(projectName);

Java

For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
  ListSubscriptionsRequest listSubscriptionsRequest =
      ListSubscriptionsRequest.newBuilder()
          .setProjectWithProjectName(ProjectName.create(projectId))
          .build();
  ListSubscriptionsPagedResponse response =
      subscriptionAdminClient.listSubscriptions(listSubscriptionsRequest);
  Iterable<Subscription> subscriptions = response.iterateAll();
  for (Subscription subscription : subscriptions) {
    // do something with the subscription
  }
  return response;
}

Go

For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

var subs []*pubsub.Subscription
it := client.Subscriptions(ctx)
for {
	s, err := it.Next()
	if err == iterator.Done {
		break
	}
	if err != nil {
		return nil, err
	}
	subs = append(subs, s)
}

Node.js

For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

function listSubscriptions () {
  // Instantiates a client
  const pubsub = PubSub();

  // Lists all subscriptions in the current project
  return pubsub.getSubscriptions()
    .then((results) => {
      const subscriptions = results[0];

      console.log('Subscriptions:');
      subscriptions.forEach((subscription) => console.log(subscription.name));

      return subscriptions;
    });
}

PHP

For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

use Google\Cloud\PubSub\PubSubClient;

/**
 * Lists all Pub/Sub subscriptions.
 *
 * @param string $projectId  The Google project ID.
 */
function list_subscriptions($projectId)
{
    $pubsub = new PubSubClient([
        'projectId' => $projectId,
    ]);
    foreach ($pubsub->subscriptions() as $subscription) {
        printf('Subscription: %s' . PHP_EOL, $subscription->name());
    }
}

Python

For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

def list_subscriptions(topic_name):
    """Lists all subscriptions for a given topic."""
    pubsub_client = pubsub.Client()
    topic = pubsub_client.topic(topic_name)

    for subscription in topic.list_subscriptions():
        print(subscription.name)

Ruby

For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

pubsub        = Google::Cloud::Pubsub.new project: "my-gcp-project-id"
subscriptions = pubsub.subscriptions

puts "Subscriptions:"
subscriptions.each do |subscription|
  puts subscription.name
end

Here are examples showing how to access subscriptions for a specific topic.

GCLOUD

   gcloud beta pubsub topics list-subscriptions myTopic

Java

For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
  TopicName topicName = TopicName.create(projectId, topicId);
  ListTopicSubscriptionsRequest request =
      ListTopicSubscriptionsRequest.newBuilder()
          .setTopicWithTopicName(topicName)
          .build();
  ListTopicSubscriptionsPagedResponse response =
      topicAdminClient.listTopicSubscriptions(request);
  Iterable<String> subscriptionNames = response.iterateAll();
  for (String subscriptionName : subscriptionNames) {
    // do something with the subscription name
  }
  return response;
}

Go

For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

var subs []*pubsub.Subscription

it := client.Topic(topicID).Subscriptions(ctx)
for {
	sub, err := it.Next()
	if err == iterator.Done {
		break
	}
	if err != nil {
		return nil, err
	}
	subs = append(subs, sub)
}

Delete a subscription

Here are examples showing how to delete subscriptions in a project once they are no longer required.

GCLOUD

   gcloud beta pubsub subscriptions delete mySubscription

C#

For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

SubscriptionName subscriptionName = new SubscriptionName(projectId,
    subscriptionId);
subscriber.DeleteSubscription(subscriptionName);

Java

For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
  SubscriptionName subscriptionName = SubscriptionName.create(projectId, subscriptionId);
  subscriptionAdminClient.deleteSubscription(subscriptionName);
  return subscriptionName;
}

Node.js

For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

function deleteSubscription (subscriptionName) {
  // Instantiates a client
  const pubsub = PubSub();

  // References an existing subscription, e.g. "my-subscription"
  const subscription = pubsub.subscription(subscriptionName);

  // Deletes the subscription
  return subscription.delete()
    .then(() => {
      console.log(`Subscription ${subscription.name} deleted.`);
    });
}

PHP

For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

use Google\Cloud\PubSub\PubSubClient;

/**
 * Creates a Pub/Sub subscription.
 *
 * @param string $projectId  The Google project ID.
 * @param string $subscriptionName  The Pub/Sub subscription name.
 */
function delete_subscription($projectId, $subscriptionName)
{
    $pubsub = new PubSubClient([
        'projectId' => $projectId,
    ]);
    $subscription = $pubsub->subscription($subscriptionName);
    $subscription->delete();

    printf('Subscription deleted: %s' . PHP_EOL, $subscription->name());
}

Python

For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

def delete_subscription(topic_name, subscription_name):
    """Deletes an existing Pub/Sub topic."""
    pubsub_client = pubsub.Client()
    topic = pubsub_client.topic(topic_name)
    subscription = topic.subscription(subscription_name)

    subscription.delete()

    print('Subscription {} deleted on topic {}.'.format(
        subscription.name, topic.name))

Ruby

For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

pubsub       = Google::Cloud::Pubsub.new project: "my-gcp-project-id"
topic        = pubsub.topic "my-topic"
subscription = topic.subscription "my-subscription"

subscription.delete

puts "Deleted subscription my-subscription"

Send feedback about...

Cloud Pub/Sub Documentation