Detach subscriptions

When you create a subscription, you attach the subscription to a topic, and subscribers can receive messages from the subscription. To stop subscribers from receiving messages, you can detach subscriptions from the topic.

Before you begin

Required roles and permissions

To get the permission that you need to detach subscriptions, ask your administrator to grant you the Pub/Sub Editor (roles/pubsub.editor) IAM role on the topic. For more information about granting roles, see Manage access to projects, folders, and organizations.

This predefined role contains the pubsub.topics.detachSubscription permission, which is required to detach subscriptions.

You might also be able to get this permission with custom roles or other predefined roles.

You can configure access control at the project level and at the individual resource level. You can create a subscription in one project and attach it to a topic located in a different project. Ensure that you have the required permissions for each project.

Detach a subscription from a topic

You can detach a subscription from a topic using the Google Cloud console, the Google Cloud CLI, the client library, or the Pub/Sub API.

Console

To detach a subscription, follow these steps:

  1. In the Google Cloud console, go to the Topics page.

    Go to Topics

  2. Select the topic from which you want to detach a subscription.

  3. In the Subscriptions tab, select the subscription to detach.

  4. In the Subscription details page, click Detach.

  5. In the dialog that appears, click Detach again.

gcloud

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

    Activate Cloud Shell

    At the bottom of the Google Cloud console, a Cloud 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 detach a subscription, use the gcloud pubsub topics detach-subscription command:

    gcloudpubsubtopicsdetach-subscriptionSUBSCRIPTION_ID

    If the request is successful, the command line displays a confirmation:

    Detached subscription [SUBSCRIPTION_ID].

REST

To detach a subscription, use the projects.subscriptions.detach method.

Request:

The request must be authenticated with an access token in the Authorization header. To obtain an access token for the current Application Default Credentials, use the gcloud auth application-default print-access-token command.

POST https://pubsub.googleapis.com/v1/projects/PROJECT_ID/subscriptions/SUBSCRIPTION_ID:detach
Authorization: Bearer ACCESS_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 in Quickstart: Using Client Libraries. For more information, see the Pub/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 in Quickstart: Using Client Libraries. For more information, see the Pub/Sub C# API reference documentation.


usingGoogle.Cloud.PubSub.V1 ;
usingSystem;
publicclassDetachSubscriptionSample
{
publicvoidDetachSubscription(stringprojectId,stringsubscriptionId)
{
PublisherServiceApiClient publisher=PublisherServiceApiClient .Create ();
DetachSubscriptionRequest detachSubscriptionRequest=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, see the migration guide to v2. To see a list of v1 code samples, see the deprecated code samples.

Before trying this sample, follow the Go setup instructions in Quickstart: Using Client Libraries. For more information, see the Pub/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 in Quickstart: Using Client Libraries. For more information, see the Pub/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;
publicclass DetachSubscriptionExample{
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{
SubscriptionName subscriptionName=SubscriptionName .of(projectId,subscriptionId);
try(TopicAdminClient topicAdminClient=TopicAdminClient .create()){
topicAdminClient.detachSubscription(
DetachSubscriptionRequest .newBuilder()
.setSubscription(subscriptionName.toString ())
.build());
}
try(SubscriptionAdminClient subscriptionAdminClient=SubscriptionAdminClient .create()){
Subscription subscription=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 in Quickstart: Using Client Libraries. For more information, see the Pub/Sub Node.js API reference documentation.

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
//constsubscriptionNameOrId='YOUR_EXISTING_SUBSCRIPTION_NAME_OR_ID';
//ImportstheGoogleCloudclientlibrary
const{PubSub}=require('@google-cloud/pubsub');
//Createsaclient;cachethisforfurtheruse
constpubSubClient=newPubSub();
asyncfunctiondetachSubscription(subscriptionNameOrId){
//Getsthestatusoftheexistingsubscription
constsub=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 in Quickstart: Using Client Libraries. For more information, see the Pub/Sub Node.js API reference documentation.

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const subscriptionNameOrId = 'YOUR_EXISTING_SUBSCRIPTION_NAME_OR_ID';
// Imports the Google Cloud client library
import{PubSub} from'@google-cloud/pubsub';
// Creates a client; cache this for further use
const pubSubClient = new PubSub();
async function detachSubscription(subscriptionNameOrId: string) {
 // Gets the status of the existing subscription
 const sub = pubSubClient.subscription(subscriptionNameOrId);
 const [detached] = await sub.detached();
 console.log(
 `Subscription ${subscriptionNameOrId} 'before' detached status: ${detached}`,
 );
 await pubSubClient.detachSubscription(subscriptionNameOrId);
 console.log(`Subscription ${subscriptionNameOrId} detach request was sent.`);
 const [updatedDetached] = await sub.detached();
 console.log(
 `Subscription ${subscriptionNameOrId} 'after' detached status: ${updatedDetached}`,
 );
}

PHP

Before trying this sample, follow the PHP setup instructions in Quickstart: Using Client Libraries. For more information, see the Pub/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 in Quickstart: Using Client Libraries. For more information, see the Pub/Sub Python API reference documentation.

fromgoogle.api_core.exceptionsimport GoogleAPICallError, RetryError
fromgoogle.cloudimport pubsub_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) as err:
 print(err)
subscription = subscriber_client .get_subscription(
 request={"subscription": subscription_path}
)
if subscription.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, see the deprecated code samples.

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

# subscription_id = "your-subscription-id"
pubsub=Google::Cloud::PubSub .new
topic_admin=pubsub.topic_admin
subscription_admin=pubsub.subscription_admin
subscription_path=pubsub.subscription_pathsubscription_id
topic_admin.detach_subscriptionsubscription:subscription_path
sleep120
subscription=subscription_admin.get_subscription\
subscription:subscription_path
ifsubscription.detached
puts"Subscription is detached."
else
puts"Subscription is NOT detached."
end

The Pub/Sub service might take several minutes to finish detaching the subscription from the topic.

After the Pub/Sub service detaches the subscription from the topic, the Pub/Sub service deletes any messages that it retains for the subscription. You can't retrieve these messages from the subscription or reattach the subscription to a topic. To free up your Google Cloud project quota, delete the subscription.

If the subscription and the topic are in different Google Cloud projects, the Pub/Sub service adds an entry to the audit logs of both projects.

What's next

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

Last updated 2026年08月26日 UTC.