Create a topic

Within Pub/Sub, a topic is a named resource that representsa feed of messages. You must create a topic before you can publish or subscribeto it. Pub/Sub supports two kinds of topics: a standard topic andan import topic.

This document describes how to create a Pub/Sub standard topic. Ifyou want to learn more about an import topic and how to create one, seeAbout import topics.

To create a topic you can use the Google Cloud console, the Google Cloud CLI,the client library, or the Pub/Sub API.

Before you begin

Required roles and permissions

To get the permissions that you need to create a topic, ask your administrator to grant you the Pub/Sub Editor(roles/pubsub.editor) IAM role on your project. For more information about granting roles, seeManage access to projects, folders, and organizations.

This predefined role contains the permissions required to create a topic. To see the exact permissions that are required, expand theRequired permissions section:

Required permissions

The following permissions are required to create a topic:

  • Grant this permission to create a topic on the project:pubsub.topics.create

You might also be able to get these permissions withcustom roles or otherpredefined roles.

You can configure access control at the project level and at the individualresource level. You can create a subscription in one project andattach it to a topic located in a different project.Ensure that you have the required permissions foreach project.

Properties of a topic

When you create or update a topic, you must specify its properties.

Add a default subscription

Adds a default subscription to the Pub/Sub topic.You can create another subscription for the topic after the topic is created.The default subscription has the following properties:

  • Subscription ID of-sub
  • Pull delivery type
  • Message retention duration of seven days
  • Expiration after 31 days of inactivity
  • Acknowledgment deadline of 10 seconds
  • Immediate retry policy

Use a schema

A schema is a format that the message data field must follow.A schema is a contract between the publisher and subscriber thatPub/Sub enforces. Topic schemas help standardize messagetypes and permissions to allow them to be consumed by different teamsin your organization. Pub/Sub creates a central authorityfor message types and permissions. To create a topic with schema,seeSchema overview.

Enable ingestion

Enabling this property lets you ingest streaming datafrom external sources into a topic so that you can use thefeatures of Google Cloud. To create an import topic foringestion, see the following:

Enable message retention

Specifies how long the Pub/Sub topic retains messagesafter publication. After the message retention duration is over,Pub/Sub might discard the message regardless of itsacknowledgment state. Message storage fees are charged for storing allmessages published to the topic

  • Default = Not enabled
  • Minimum value = 10 minutes
  • Maximum value = 31 days

Export message data to BigQuery

Enabling this property lets you create a BigQuery subscriptionthat writes messages to an existing BigQuery table asthey are received. You don't need to configure a separate subscriberclient. For more information about BigQuery subscriptions,seeBigQuery subscriptions.

Backup message data to Cloud Storage

Enabling this property lets you create a Cloud Storagesubscription that writes messages to an existing Cloud Storagetable as they are received. You don't need to configure a separate subscriberclient. For more information about Cloud Storage subscriptions,seeCloud Storage subscriptions.

Transforms

Topic SMTs allow for lightweight modifications to message data and attributesdirectly within Pub/Sub. This feature enables data cleaning,filtering, or format conversion before the messages are published to the topic.

For more information about SMTs, see theSMTs overview.

Google-owned and Google-managed encryption key

Specifies that the topic is encrypted usingGoogle-owned and Google-managed encryption keys. Pub/Sub encryptsmessages with Google-owned and Google-managed encryption keys by default, so choosingthis option maintains the default behavior. Google handles key management androtation automatically, ensuring your messages are always protected with thestrongest available encryption. This option requires no further configuration.For more information about Google-owned and Google-managed encryption keys,seeDefault encryption with Google-owned and Google-managed encryption keys.

Cloud KMS key

Specifies if the topic is encrypted with a customer-managed encryptionkey (CMEK). Pub/Subencrypts messages with Google-owned and Google-managed encryption keys by default. If you specifythis option, Pub/Sub uses the envelope encryption pattern withCMEK. In this approach, Cloud KMS does not encrypt the messages. Instead,Cloud KMS encrypts the Data Encryption Keys (DEKs) that Pub/Subcreates for each topic. Pub/Sub encrypts the messages usingthe newest DEK that was generated for the topic. Pub/Subdecrypts the messages shortly before they are delivered to subscribers.For more information about creating a key, seeConfigure message encryption.

Create a topic

Create a topic before you can publish or subscribe to it.

Console

To create a topic, follow these steps:

  1. In the Google Cloud console, go to the Pub/SubCreate topicpage.

    Go to Create topic

  2. In theTopic ID field, enter an ID for your topic. For more informationabout naming topics, see thenaming guidelines.

  3. To create adefault subscription for thetopic, selectAdd a default subscription. This option is enabled bydefault.

  4. Optional. To use a schema with the topic, clickUse a schema andprovide the schema. For more information, seeCreate and associate a schema when you create a topic.

  5. For a standard topic, leaveEnable ingestion unselected.

  6. Optional. To retain messages after they are published, selectEnable message retention. Select the retention period in days, hours,and minutes. For more information, seeEnable message retention.

  7. Optional. To export published messages to a BigQuery table,selectExport data to BigQuery and enter the details for the table.For more information, seeCreate BigQuery subscriptions.

  8. Optional. To back up published messages to a Cloud Storage bucket,selectBackup message data to Cloud Storage and enter the details forthe Cloud Storage bucket. For more information, seeCreate Cloud Storage subscriptions.

  9. Optional. UnderTransforms, add one or moreSingle Message Transforms (SMTs) tomanipulate and filter message data. For more information, seeCreate a topic with SMTs.

  10. Optional. To use a customer-managed encryption key (CMEK) to encryptmessages, selectCloud KMS key. By default, Pub/Subuses Google default encryption, which doesn't require a CMEK. For moreinformation, seeConfigure message encryption.

  11. Optional. To manage the keys associated with the topic, clickManage keys. For moreinformation, seeTags overview.

  12. ClickCreate topic.

gcloud

  1. In the Google Cloud console, activate Cloud Shell.

    Activate Cloud Shell

    At the bottom of the Google Cloud console, aCloud Shell session starts and displays a command-line prompt. Cloud Shell is a shell environment with the Google Cloud CLI already installed and with values already set for your current project. It can take a few seconds for the session to initialize.

  2. To create a topic, run thegcloud pubsub topics createcommand:

    gcloudpubsubtopicscreateTOPIC_ID

REST

To create a topic, use theprojects.topics.createmethod:

The request must be authenticated with an access token in theAuthorizationheader. To obtain an access token for the current Application DefaultCredentials:gcloud auth application-default print-access-token.

PUThttps://pubsub.googleapis.com/v1/projects/PROJECT_ID/topics/TOPIC_IDAuthorization:BearerACCESS_TOKEN

Where:

  • PROJECT_ID is your project ID.
  • TOPIC_ID is your topic ID.

Response:

{"name":"projects/PROJECT_ID/topics/TOPIC_ID"}

C++

Before trying this sample, follow the C++ setup instructions inQuickstart: Using Client Libraries. For more information, see thePub/Sub C++ API reference documentation.

namespacepubsub=::google::cloud::pubsub;namespacepubsub_admin=::google::cloud::pubsub_admin;[](pubsub_admin::TopicAdminClientclient,std::stringproject_id,std::stringtopic_id){autotopic=client.CreateTopic(pubsub::Topic(std::move(project_id),std::move(topic_id)).FullName());// Note that kAlreadyExists is a possible error when the library retries.if(topic.status().code()==google::cloud::StatusCode::kAlreadyExists){std::cout <<"The topic already exists\n";return;}if(!topic)throwstd::move(topic).status();std::cout <<"The topic was successfully created: " <<topic->DebugString()            <<"\n";}

C#

Before trying this sample, follow the C# setup instructions inQuickstart: Using Client Libraries. For more information, see thePub/Sub C# API reference documentation.

usingGoogle.Cloud.PubSub.V1;usingGrpc.Core;usingSystem;publicclassCreateTopicSample{publicTopicCreateTopic(stringprojectId,stringtopicId){PublisherServiceApiClientpublisher=PublisherServiceApiClient.Create();vartopicName=TopicName.FromProjectTopic(projectId,topicId);Topictopic=null;try{topic=publisher.CreateTopic(topicName);Console.WriteLine($"Topic {topic.Name} created.");}catch(RpcExceptione)when(e.Status.StatusCode==StatusCode.AlreadyExists){Console.WriteLine($"Topic {topicName} already exists.");}returntopic;}}

Go

The following sample uses the major version of the Go Pub/Sub client library (v2). If you are still using the v1 library, seethe migration guide to v2.To see a list of v1 code samples, seethe deprecated code samples.

Before trying this sample, follow the Go setup instructions inQuickstart: Using Client Libraries.For more information, see thePub/Sub Go API reference documentation.

import("context""fmt""io""cloud.google.com/go/pubsub/v2""cloud.google.com/go/pubsub/v2/apiv1/pubsubpb")funccreate(wio.Writer,projectID,topicIDstring)error{// projectID := "my-project-id"// topicID := "my-topic"ctx:=context.Background()client,err:=pubsub.NewClient(ctx,projectID)iferr!=nil{returnfmt.Errorf("pubsub.NewClient: %w",err)}deferclient.Close()topic:=&pubsubpb.Topic{Name:fmt.Sprintf("projects/%s/topics/%s",projectID,topicID),}t,err:=client.TopicAdminClient.CreateTopic(ctx,topic)iferr!=nil{returnfmt.Errorf("CreateTopic: %w",err)}fmt.Fprintf(w,"Topic created: %v\n",t)returnnil}

Java

Before trying this sample, follow the Java setup instructions inQuickstart: Using Client Libraries. For more information, see thePub/Sub Java API reference documentation.

importcom.google.cloud.pubsub.v1.TopicAdminClient;importcom.google.pubsub.v1.Topic;importcom.google.pubsub.v1.TopicName;importjava.io.IOException;publicclassCreateTopicExample{publicstaticvoidmain(String...args)throwsException{// TODO(developer): Replace these variables before running the sample.StringprojectId="your-project-id";StringtopicId="your-topic-id";createTopicExample(projectId,topicId);}publicstaticvoidcreateTopicExample(StringprojectId,StringtopicId)throwsIOException{try(TopicAdminClienttopicAdminClient=TopicAdminClient.create()){TopicNametopicName=TopicName.of(projectId,topicId);Topictopic=topicAdminClient.createTopic(topicName);System.out.println("Created topic: "+topic.getName());}}}

Node.js

Before trying this sample, follow the Node.js setup instructions inQuickstart: Using Client Libraries. For more information, see thePub/Sub Node.js API reference documentation.

/***TODO(developer):Uncommentthisvariablebeforerunningthesample.*///consttopicNameOrId='YOUR_TOPIC_NAME_OR_ID';//ImportstheGoogleCloudclientlibraryconst{PubSub}=require('@google-cloud/pubsub');//Createsaclient;cachethisforfurtheruseconstpubSubClient=newPubSub();asyncfunctioncreateTopic(topicNameOrId){//CreatesanewtopicawaitpubSubClient.createTopic(topicNameOrId);console.log(`Topic${topicNameOrId}created.`);}

Node.ts

Before trying this sample, follow the Node.js setup instructions inQuickstart: Using Client Libraries. For more information, see thePub/Sub Node.js API reference documentation.

/***TODO(developer):Uncommentthisvariablebeforerunningthesample.*///consttopicNameOrId='YOUR_TOPIC_NAME_OR_ID';//ImportstheGoogleCloudclientlibraryimport{PubSub}from'@google-cloud/pubsub';//Createsaclient;cachethisforfurtheruseconstpubSubClient=newPubSub();asyncfunctioncreateTopic(topicNameOrId:string){//CreatesanewtopicawaitpubSubClient.createTopic(topicNameOrId);console.log(`Topic${topicNameOrId}created.`);}

PHP

Before trying this sample, follow the PHP setup instructions inQuickstart: Using Client Libraries. For more information, see thePub/Sub PHP API reference documentation.

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

Before trying this sample, follow the Python setup instructions inQuickstart: Using Client Libraries. For more information, see thePub/Sub Python API reference documentation.

fromgoogle.cloudimportpubsub_v1# TODO(developer)# project_id = "your-project-id"# topic_id = "your-topic-id"publisher=pubsub_v1.PublisherClient()topic_path=publisher.topic_path(project_id,topic_id)topic=publisher.create_topic(request={"name":topic_path})print(f"Created topic:{topic.name}")

Ruby

The following sample uses Ruby Pub/Sub client library v3. If you are still using the v2 library, see the migration guide to v3.To see a list of Ruby v2 code samples, seethe deprecated code samples.

Before trying this sample, follow the Ruby setup instructions inQuickstart: Using Client Libraries.For more information, see thePub/Sub Ruby API reference documentation.

# topic_id = "your-topic-id"pubsub=Google::Cloud::PubSub.newtopic_admin=pubsub.topic_admintopic=topic_admin.create_topicname:pubsub.topic_path(topic_id)puts"Topic#{topic.name} created."

Organization policy constraints

Organizational policies can restrict topic creation, for example,a policy can restrict message storage in a Compute Engineregion. To avoid topic creation errors, examine and updateorganizational policies, as needed, before creating a topic.

If your project is newly created, wait a few minutes forthe organization policy to initialize before creating a topic.

Go to Organization Policies

For more information, seeConfigure message storage policies.

What's next

Apache Kafka® is a registeredtrademark of The Apache Software Foundation or its affiliates in the UnitedStates and/or other countries.

Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2026-02-19 UTC.