Detach subscriptions Stay organized with collections Save and categorize content based on your preferences.
When you create a subscription, you attach the subscription to a topic, andsubscribers can receive messages from the subscription. To stop subscribers fromreceiving messages, you can detach subscriptions from the topic.
Before you begin
- Learn aboutsubscriptions.
- Create one of the following subscriptions,pull,push, orBigQuery.
Required roles and permissions
To get the permission that you need to detach subscriptions, ask your administrator to grant you thePub/Sub Editor (roles/pubsub.editor) IAM role on your topic or project. For more information about granting roles, seeManage access to projects, folders, and organizations.
This predefined role contains the permission, which is required to detach subscriptions.pubsub.topics.detachSubscription
You might also be able to get this permission 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.
Detach a subscription from a topic
You can detach a subscription from a topic using the Google Cloud console, theGoogle Cloud CLI, the client library, or the Pub/Sub API.
Console
To detach a subscription, follow these steps:
In the Google Cloud console, go to theTopics page.
Select the topic from which you want to detach a subscription.
In theSubscriptions tab, select the subscription to detach.
In theSubscription details page, clickDetach.
In the dialog that appears, clickDetach again.
gcloud
In the Google Cloud console, 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.
To detach a subscription, use the
gcloud pubsub topics detach-subscriptioncommand:gcloudpubsubtopicsdetach-subscriptionSUBSCRIPTION_ID
If the request is successful, the command line displays a confirmation:
Detached subscription [SUBSCRIPTION_ID].
REST
To detach a subscription, use theprojects.subscriptions.detachmethod.
Request:
The request must be authenticated with an access token in theAuthorization header. To obtain an access token for the currentApplication Default Credentials, use thegcloud auth application-default print-access-token command.
POST https://pubsub.googleapis.com/v1/projects/PROJECT_ID/subscriptions/SUBSCRIPTION_ID:detachAuthorization: BearerACCESS_TOKEN
Where:
- PROJECT_ID is your project ID.
- SUBSCRIPTION_ID is your subscription ID.
Response:
If the request is successful, the response is an empty JSON object.
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::stringconst&project_id,std::stringconst&subscription_id){google::pubsub::v1::DetachSubscriptionRequestrequest;request.set_subscription(pubsub::Subscription(project_id,subscription_id).FullName());autoresponse=client.DetachSubscription(request);if(!response.ok())throwstd::move(response).status();std::cout <<"The subscription was successfully detached: " <<response->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;usingSystem;publicclassDetachSubscriptionSample{publicvoidDetachSubscription(stringprojectId,stringsubscriptionId){PublisherServiceApiClientpublisher=PublisherServiceApiClient.Create();DetachSubscriptionRequestdetachSubscriptionRequest=newDetachSubscriptionRequest{SubscriptionAsSubscriptionName=SubscriptionName.FromProjectSubscription(projectId,subscriptionId),};publisher.DetachSubscription(detachSubscriptionRequest);Console.WriteLine($"Subscription {subscriptionId} is detached.");}}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")funcdetachSubscription(wio.Writer,projectID,subNamestring)error{// projectID is the project which contains the topic you manage.// This might differ from the project which contains the subscription// you wish to detach, which can exist in any GCP project.// projectID := "my-project-id"// subName := "projects/some-project/subscriptions/my-sub"ctx:=context.Background()client,err:=pubsub.NewClient(ctx,projectID)iferr!=nil{returnfmt.Errorf("pubsub.NewClient: %w",err)}deferclient.Close()// Call DetachSubscription, which detaches a subscription from// a topic. This can only be done if you have the// `pubsub.topics.detachSubscription` role on the topic the// subscription is attached to.req:=&pubsubpb.DetachSubscriptionRequest{Subscription:subName,}_,err=client.TopicAdminClient.DetachSubscription(ctx,req)iferr!=nil{returnfmt.Errorf("detach subscription failed: %w",err)}fmt.Fprintf(w,"Detached subscription %s",subName)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.SubscriptionAdminClient;importcom.google.cloud.pubsub.v1.TopicAdminClient;importcom.google.pubsub.v1.DetachSubscriptionRequest;importcom.google.pubsub.v1.Subscription;importcom.google.pubsub.v1.SubscriptionName;importjava.io.IOException;publicclassDetachSubscriptionExample{publicstaticvoidmain(String...args)throwsException{// TODO(developer): Replace these variables before running the sample.StringprojectId="your-project-id";// Choose an existing subscription.StringsubscriptionId="your-subscription-id";detachSubscriptionExample(projectId,subscriptionId);}publicstaticvoiddetachSubscriptionExample(StringprojectId,StringsubscriptionId)throwsIOException{SubscriptionNamesubscriptionName=SubscriptionName.of(projectId,subscriptionId);try(TopicAdminClienttopicAdminClient=TopicAdminClient.create()){topicAdminClient.detachSubscription(DetachSubscriptionRequest.newBuilder().setSubscription(subscriptionName.toString()).build());}try(SubscriptionAdminClientsubscriptionAdminClient=SubscriptionAdminClient.create()){Subscriptionsubscription=subscriptionAdminClient.getSubscription(subscriptionName);if(subscription.getDetached()){System.out.println("Subscription is detached.");}else{System.out.println("Subscription is NOT detached.");}}}}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): Uncomment these variables before running the sample. *///constsubscriptionNameOrId='YOUR_EXISTING_SUBSCRIPTION_NAME_OR_ID';//ImportstheGoogleCloudclientlibraryconst{PubSub}=require('@google-cloud/pubsub');//Createsaclient;cachethisforfurtheruseconstpubSubClient=newPubSub();asyncfunctiondetachSubscription(subscriptionNameOrId){//Getsthestatusoftheexistingsubscriptionconstsub=pubSubClient.subscription(subscriptionNameOrId);const[detached]=awaitsub.detached();console.log(`Subscription${subscriptionNameOrId}'before'detachedstatus:${detached}`,);awaitpubSubClient.detachSubscription(subscriptionNameOrId);console.log(`Subscription${subscriptionNameOrId}detachrequestwassent.`);const[updatedDetached]=awaitsub.detached();console.log(`Subscription${subscriptionNameOrId}'after'detachedstatus:${updatedDetached}`,);}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):Uncommentthesevariablesbeforerunningthesample.*///constsubscriptionNameOrId='YOUR_EXISTING_SUBSCRIPTION_NAME_OR_ID';//ImportstheGoogleCloudclientlibraryimport{PubSub}from'@google-cloud/pubsub';//Createsaclient;cachethisforfurtheruseconstpubSubClient=newPubSub();asyncfunctiondetachSubscription(subscriptionNameOrId:string){//Getsthestatusoftheexistingsubscriptionconstsub=pubSubClient.subscription(subscriptionNameOrId);const[detached]=awaitsub.detached();console.log(`Subscription${subscriptionNameOrId}'before'detachedstatus:${detached}`,);awaitpubSubClient.detachSubscription(subscriptionNameOrId);console.log(`Subscription${subscriptionNameOrId}detachrequestwassent.`);const[updatedDetached]=awaitsub.detached();console.log(`Subscription${subscriptionNameOrId}'after'detachedstatus:${updatedDetached}`,);}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;/** * Detach a Pub/Sub subscription from a topic. * * @param string $projectId The Google project ID. * @param string $subscriptionName The Pub/Sub subscription name. */function detach_subscription($projectId, $subscriptionName){ $pubsub = new PubSubClient([ 'projectId' => $projectId, ]); $subscription = $pubsub->subscription($subscriptionName); $subscription->detach(); printf('Subscription detached: %s' . PHP_EOL, $subscription->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.api_core.exceptionsimportGoogleAPICallError,RetryErrorfromgoogle.cloudimportpubsub_v1# TODO(developer): Choose an existing subscription.# project_id = "your-project-id"# subscription_id = "your-subscription-id"publisher_client=pubsub_v1.PublisherClient()subscriber_client=pubsub_v1.SubscriberClient()subscription_path=subscriber_client.subscription_path(project_id,subscription_id)try:publisher_client.detach_subscription(request={"subscription":subscription_path})except(GoogleAPICallError,RetryError,ValueError,Exception)aserr:print(err)subscription=subscriber_client.get_subscription(request={"subscription":subscription_path})ifsubscription.detached:print(f"{subscription_path} is detached.")else:print(f"{subscription_path} is NOT detached.")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.
# subscription_id = "your-subscription-id"pubsub=Google::Cloud::PubSub.newtopic_admin=pubsub.topic_adminsubscription_admin=pubsub.subscription_adminsubscription_path=pubsub.subscription_pathsubscription_idtopic_admin.detach_subscriptionsubscription:subscription_pathsleep120subscription=subscription_admin.get_subscription\subscription:subscription_pathifsubscription.detachedputs"Subscription is detached."elseputs"Subscription is NOT detached."endThe Pub/Sub service might take several minutes to finishdetaching the subscription from the topic.
After the Pub/Sub service detaches the subscription from thetopic, the Pub/Sub service deletes any messages that it retainsfor the subscription. You can't retrieve these messages from the subscription orreattach the subscription to a topic. To free up your Google Cloud projectquota,delete the subscription.
If the subscription and the topic are in different Google Cloud projects, thePub/Sub service adds an entry to the audit logs of both projects.
What's next
- Create or modify a subscription with
gcloudcommands. - Create or modify a subscription withREST APIs.
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.