Create and manage Lite subscriptions

Subscribers use a Lite subscription to read messages from a Lite topic. When you create a Lite subscription, you attach it to a Lite topic. You can attach many Lite subscriptions to a single Lite topic.

There are two types of subscription:

  • Standard subscription. Create a standard subscription when you have a client that needs to read messages from the Lite topic topic.
  • Export subscription. Create an export subscription when you need to export Lite messages to Pub/Sub. For more information, see Export Pub/Sub Lite messages to Pub/Sub.

Properties of a Lite subscription

A subscription for a zonal Lite topic has identical properties to a subscription for a regional Lite topic, except for the following:

  • Location type, a zone or a region, used in the resource name. An example of a region location is us-central1; an example of a zone location is us-central1-a.

  • Reliability. See Data replication in a Lite topic to learn more about reliability differences between regional and zonal topics.

Delivery requirement for messages

A temporary failure in writing a message to storage causes the publisher to retry sending the message. These retries are transparent to the end-user. Lite subscriptions have a delivery requirement property that changes how subscriptions react to these message retries. You can set this property to one of the following two options:

  • Deliver messages immediately. With this option enabled, the subscriber clients receive all messages after they arrive at the server. This process is not dependent on the status of the messages being written to disk. Offsets are not reused, but messages with offsets that are not written to storage might not be re-readable following a seek operation.

  • Deliver messages after stored. With this option enabled, the subscriber does not receive messages until they are written to disk. The messages are guaranteed to be re-readable after a seek operation. Enabling this option increases the end-to-end latency for receiving messages from the publisher to the subscriber.

Guidelines to name a subscription

A Pub/Sub Lite resource name uniquely identifies a Pub/Sub Lite resource, such as a topic, subscription, or reservation. The resource name must fit the following format:

projects/project-identifier/collection/ID

  • project-identifier: Must be the project ID or project number, available from the Google Cloud console. For example, my-cool-project is a project ID. 123456789123 is a project number.

  • collection: Must be one of topics, subscriptions, or reservations.

  • ID: Must conform to the following guidelines:

    • Not begin with the string goog
    • Start with a letter
    • Contain between 3 and 255 characters
    • Contain only the following characters: Letters [A-Za-z], numbers [0-9], dashes -, underscores _, periods ., tildes ~, plus signs +, and percent signs %

    You can use the special characters in the preceding list in resource names without URL-encoding. However, you must ensure that any other special characters are properly encoded or decoded when you use them in URLs. For example, mi-tópico is an invalid ID. However, mi-t%C3%B3pico is valid. This format is important when you make REST calls.

Create a Lite subscription

A Lite subscription must be in the same project and location as the Lite topic to which the Lite subscription is attached.

To create a Lite topic, see Create and manage a Lite topic.

For a list of the available locations, see Pub/Sub Lite locations.

You can create a Lite subscription with the Google Cloud console, the Google Cloud CLI, or the Pub/Sub Lite API.

For information about creating an export subscription, see Export Pub/Sub Lite messages to Pub/Sub.

Console

  1. Go to the Lite Subscriptions page.

    Go to Lite Subscriptions

  2. Click Create Lite subscription.

  3. Enter a Lite subscription ID.

  4. Choose a Lite topic to receive messages from.

  5. Choose Deliver messages immediately or Deliver messages after stored.

  6. Choose a type of Starting offset.

  7. Choose a Delivery type.

  8. Click Create.

gcloud

To create a Lite subscription, use the gcloud pubsub lite-subscriptions create command:

gcloudpubsublite-subscriptionscreateSUBSCRIPTION_ID\
--location=LOCATION\
--topic=TOPIC_ID\
--delivery-requirement=DELIVERY_REQUIREMENT

Replace the following:

  • SUBSCRIPTION_ID: the ID of the Lite subscription

  • LOCATION: the name of a location that Pub/Sub Lite supports

  • TOPIC_ID: the ID of the Lite topic to attach to the Lite subscription

  • DELIVERY_REQUIREMENT: deliver-after-stored or deliver-immediately

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

Created [SUBSCRIPTION_ID].

Protocol

To create a Lite subscription, send a POST request like the following:

POST https://REGION-pubsublite.googleapis.com/v1/admin/projects/PROJECT_NUMBER/locations/LOCATION/subscriptions/SUBSCRIPTION_ID
Authorization: Bearer $(gcloud auth print-access-token)

Replace the following:

Specify the following fields in the request body:

{
"topic":projects/PROJECT_NUMBER/locations/LOCATION/topics/TOPIC_ID,
"deliveryConfig":{
"deliveryRequirement":DELIVERY_REQUIREMENT,
}
}

Replace DELIVERY_REQUIREMENT with deliver-after-stored or deliver-immediately.

If the request is successful, the response is the Lite subscription in JSON format:

{
 "deliveryConfig": {
 "deliveryRequirement": DELIVERY_REQUIREMENT,
 }
 "name": "projects/PROJECT_NUMBER/locations/LOCATION/subscriptions/SUBSCRIPTION_ID",
 "topic": "projects/PROJECT_NUMBER/locations/LOCATION/topics/TOPIC_ID",
}

Go

Before running this sample, follow the Go setup instructions in Pub/Sub Lite Client Libraries.

import(
"context"
"fmt"
"io"
"cloud.google.com/go/pubsublite"
)
funccreateSubscription(wio.Writer,projectID,region,location,topicID,subIDstring)error{
// projectID := "my-project-id"
// region := "us-central1"
// NOTE: location can be either a region ("us-central1") or a zone ("us-central1-a")
// For a list of valid locations, see https://cloud.google.com/pubsub/lite/docs/locations.
// location := "us-central1"
// NOTE: topic and subscription must be in the same region/zone (e.g. "us-central1-a")
// topicID := "my-topic"
// subID := "my-subscription"
ctx:=context.Background()
client,err:=pubsublite.NewAdminClient(ctx,region)
iferr!=nil{
returnfmt.Errorf("pubsublite.NewAdminClient: %w",err)
}
deferclient.Close()
sub,err:=client.CreateSubscription(ctx,pubsublite.SubscriptionConfig {
Name:fmt.Sprintf("projects/%s/locations/%s/subscriptions/%s",projectID,location,subID),
Topic:fmt.Sprintf("projects/%s/locations/%s/topics/%s",projectID,location,topicID),
DeliveryRequirement:pubsublite.DeliverImmediately ,// can also be DeliverAfterStored
})
iferr!=nil{
returnfmt.Errorf("client.CreateSubscription got err: %w",err)
}
fmt.Fprintf(w,"Created subscription: %s\n",sub.Name)
returnnil
}

Java

Before running this sample, follow the Java setup instructions in Pub/Sub Lite Client Libraries.

importcom.google.api.gax.rpc.AlreadyExistsException ;
importcom.google.cloud.pubsublite.AdminClient ;
importcom.google.cloud.pubsublite.AdminClientSettings ;
importcom.google.cloud.pubsublite.CloudRegion ;
importcom.google.cloud.pubsublite.CloudRegionOrZone ;
importcom.google.cloud.pubsublite.CloudZone ;
importcom.google.cloud.pubsublite.ProjectNumber ;
importcom.google.cloud.pubsublite.SubscriptionName ;
importcom.google.cloud.pubsublite.SubscriptionPath ;
importcom.google.cloud.pubsublite.TopicName ;
importcom.google.cloud.pubsublite.TopicPath ;
importcom.google.cloud.pubsublite.proto.Subscription ;
importcom.google.cloud.pubsublite.proto.Subscription.DeliveryConfig;
importcom.google.cloud.pubsublite.proto.Subscription.DeliveryConfig.DeliveryRequirement;
importjava.util.concurrent.ExecutionException;
publicclass CreateSubscriptionExample{
publicstaticvoidmain(String...args)throwsException{
// TODO(developer): Replace these variables before running the sample.
StringcloudRegion="your-cloud-region";
charzoneId='b';
StringtopicId="your-topic-id";
StringsubscriptionId="your-subscription-id";
longprojectNumber=Long.parseLong("123456789");
// True if using a regional location. False if using a zonal location.
// https://cloud.google.com/pubsub/lite/docs/topics
booleanregional=false;
createSubscriptionExample(
cloudRegion,zoneId,projectNumber,topicId,subscriptionId,regional);
}
publicstaticvoidcreateSubscriptionExample(
StringcloudRegion,
charzoneId,
longprojectNumber,
StringtopicId,
StringsubscriptionId,
booleanregional)
throwsException{
CloudRegionOrZone location;
if(regional){
location=CloudRegionOrZone .of(CloudRegion .of(cloudRegion));
}else{
location=CloudRegionOrZone .of(CloudZone .of(CloudRegion .of(cloudRegion),zoneId));
}
TopicPath topicPath=
TopicPath .newBuilder()
.setProject(ProjectNumber .of(projectNumber))
.setLocation(location)
.setName(TopicName .of(topicId))
.build();
SubscriptionPath subscriptionPath=
SubscriptionPath .newBuilder()
.setLocation(location)
.setProject(ProjectNumber .of(projectNumber))
.setName(SubscriptionName .of(subscriptionId))
.build();
Subscription subscription=
Subscription .newBuilder()
.setDeliveryConfig(
// Possible values for DeliveryRequirement:
// - `DELIVER_IMMEDIATELY`
// - `DELIVER_AFTER_STORED`
// You may choose whether to wait for a published message to be successfully written
// to storage before the server delivers it to subscribers. `DELIVER_IMMEDIATELY` is
// suitable for applications that need higher throughput.
DeliveryConfig.newBuilder()
.setDeliveryRequirement(DeliveryRequirement.DELIVER_IMMEDIATELY))
.setName(subscriptionPath .toString ())
.setTopic(topicPath .toString ())
.build();
AdminClientSettings adminClientSettings=
AdminClientSettings .newBuilder().setRegion(CloudRegion .of(cloudRegion)).build();
try(AdminClient adminClient=AdminClient .create(adminClientSettings)){
Subscription response=adminClient.createSubscription(subscription).get();
System.out.println(response.getAllFields()+" created successfully.");
}catch(ExecutionExceptione){
try{
throwe.getCause();
}catch(AlreadyExistsException alreadyExists){
System.out.println("This subscription already exists.");
}catch(Throwablethrowable){
throwable.printStackTrace();
}
}
}
}

Python

Before running this sample, follow the Python setup instructions in Pub/Sub Lite Client Libraries.

fromgoogle.api_core.exceptionsimport AlreadyExists
fromgoogle.cloud.pubsubliteimport AdminClient , Subscription
fromgoogle.cloud.pubsublite.typesimport (
 CloudRegion ,
 CloudZone ,
 SubscriptionPath ,
 TopicPath ,
)
# TODO(developer):
# project_number = 1122334455
# cloud_region = "us-central1"
# zone_id = "a"
# topic_id = "your-topic-id"
# subscription_id = "your-subscription-id"
# regional = True
if regional:
 location = CloudRegion(cloud_region)
else:
 location = CloudZone(CloudRegion(cloud_region), zone_id)
topic_path = TopicPath(project_number, location, topic_id)
subscription_path = SubscriptionPath(project_number, location, subscription_id)
subscription = Subscription(
 name=str(subscription_path),
 topic=str(topic_path),
 delivery_config=Subscription.DeliveryConfig(
 # Possible values for delivery_requirement:
 # - `DELIVER_IMMEDIATELY`
 # - `DELIVER_AFTER_STORED`
 # You may choose whether to wait for a published message to be successfully written
 # to storage before the server delivers it to subscribers. `DELIVER_IMMEDIATELY` is
 # suitable for applications that need higher throughput.
 delivery_requirement=Subscription.DeliveryConfig.DeliveryRequirement.DELIVER_IMMEDIATELY,
 ),
)
client = AdminClient(cloud_region)
try:
 response = client.create_subscription (subscription)
 print(f"{response.name} created successfully.")
except AlreadyExists:
 print(f"{subscription_path} already exists.")

After creating a Lite subscription to a Lite topic, you can receive messages from the Lite subscription.

Update a Lite subscription

You can update Lite subscriptions with the Google Cloud console, the Google Cloud CLI, or the Pub/Sub Lite API.

Console

  1. Go to the Lite Subscriptions page.

    Go to Lite Subscriptions

  2. Click the Lite subscription ID.

  3. In the Lite subscription details page, click Edit.

gcloud

To update a Lite subscription, use the gcloud pubsub lite-subscriptions update command:

gcloudpubsublite-subscriptionsupdateSUBSCRIPTION_ID\
--location=LOCATION\
--delivery-requirement=DELIVERY_REQUIREMENT

Replace the following:

  • SUBSCRIPTION_ID: the ID of the Lite subscription

  • LOCATION: the name of the location that the Lite subscription is in

  • DELIVERY_REQUIREMENT: deliver-after-stored or deliver-immediately

If the request is successful, the command line displays the Lite subscription:

deliveryConfig:
 deliveryRequirement: DELIVERY_REQUIREMENT
name: projects/PROJECT_NUMBER/locations/LOCATION/subscriptions/SUBSCRIPTION_ID
topic: projects/PROJECT_NUMBER/locations/LOCATION/topics/TOPIC_ID

Protocol

To update a Lite subscription, send a PATCH request like the following:

PATCH https://REGION-pubsublite.googleapis.com/v1/admin/projects/PROJECT_NUMBER/locations/LOCATION/subscriptions/SUBSCRIPTION_ID?updateMask=deliveryConfig.deliveryRequirement
Authorization: Bearer $(gcloud auth print-access-token)

Replace the following:

  • REGION: the region to store the Lite subscription in

  • PROJECT_NUMBER: the project number of the project with the Lite subscription

  • LOCATION: the name of the location that the Lite subscription is in

  • SUBSCRIPTION_ID: the ID of the Lite subscription

Specify the following fields in the request body:

{
"deliveryConfig":{
"deliveryRequirement":DELIVERY_REQUIREMENT,
}
}

Replace DELIVERY_REQUIREMENT with deliver-after-stored or deliver-immediately.

If the request is successful, the response is the Lite subscription in JSON format:

{
 "deliveryConfig": {
 "deliveryRequirement": DELIVERY_REQUIREMENT,
 }
 "name": "projects/PROJECT_NUMBER/locations/LOCATION/subscriptions/SUBSCRIPTION_ID",
 "topic": "projects/PROJECT_NUMBER/locations/LOCATION/topics/TOPIC_ID",
}

Go

Before running this sample, follow the Go setup instructions in Pub/Sub Lite Client Libraries.

import(
"context"
"fmt"
"io"
"cloud.google.com/go/pubsublite"
)
funcupdateSubscription(wio.Writer,projectID,region,location,subIDstring)error{
// projectID := "my-project-id"
// region := "us-central1"
// NOTE: location can be either a region ("us-central1") or a zone ("us-central1-a")
// For a list of valid locations, see https://cloud.google.com/pubsub/lite/docs/locations.
// location := "us-central1"
// subID := "my-subscription"
ctx:=context.Background()
client,err:=pubsublite.NewAdminClient(ctx,region)
iferr!=nil{
returnfmt.Errorf("pubsublite.NewAdminClient: %w",err)
}
deferclient.Close()
subPath:=fmt.Sprintf("projects/%s/locations/%s/subscriptions/%s",projectID,location,subID)
config:=pubsublite.SubscriptionConfigToUpdate {
Name:subPath,
DeliveryRequirement:pubsublite.DeliverAfterStored ,
}
updatedCfg,err:=client.UpdateSubscription(ctx,config)
iferr!=nil{
returnfmt.Errorf("client.UpdateSubscription got err: %w",err)
}
fmt.Fprintf(w,"Updated subscription: %#v\n",updatedCfg)
returnnil
}

Java

Before running this sample, follow the Java setup instructions in Pub/Sub Lite Client Libraries.

importcom.google.api.gax.rpc.NotFoundException ;
importcom.google.cloud.pubsublite.AdminClient ;
importcom.google.cloud.pubsublite.AdminClientSettings ;
importcom.google.cloud.pubsublite.CloudRegion ;
importcom.google.cloud.pubsublite.CloudRegionOrZone ;
importcom.google.cloud.pubsublite.CloudZone ;
importcom.google.cloud.pubsublite.ProjectNumber ;
importcom.google.cloud.pubsublite.SubscriptionName ;
importcom.google.cloud.pubsublite.SubscriptionPath ;
importcom.google.cloud.pubsublite.proto.Subscription ;
importcom.google.cloud.pubsublite.proto.Subscription.DeliveryConfig;
importcom.google.cloud.pubsublite.proto.Subscription.DeliveryConfig.DeliveryRequirement;
importcom.google.protobuf.FieldMask ;
importjava.util.concurrent.ExecutionException;
publicclass UpdateSubscriptionExample{
publicstaticvoidmain(String...args)throwsException{
// TODO(developer): Replace these variables before running the sample.
StringcloudRegion="your-cloud-region";
charzoneId='b';
// Choose an existing subscription.
StringsubscriptionId="your-subscription-id";
longprojectNumber=Long.parseLong("123456789");
// True if using a regional location. False if using a zonal location.
// https://cloud.google.com/pubsub/lite/docs/topics
booleanregional=false;
updateSubscriptionExample(cloudRegion,zoneId,projectNumber,subscriptionId,regional);
}
publicstaticvoidupdateSubscriptionExample(
StringcloudRegion,charzoneId,longprojectNumber,StringsubscriptionId,booleanregional)
throwsException{
CloudRegionOrZone location;
if(regional){
location=CloudRegionOrZone .of(CloudRegion .of(cloudRegion));
}else{
location=CloudRegionOrZone .of(CloudZone .of(CloudRegion .of(cloudRegion),zoneId));
}
SubscriptionPath subscriptionPath=
SubscriptionPath .newBuilder()
.setLocation(location)
.setProject(ProjectNumber .of(projectNumber))
.setName(SubscriptionName .of(subscriptionId))
.build();
FieldMask fieldMask=
FieldMask .newBuilder().addPaths ("delivery_config.delivery_requirement").build();
Subscription subscription=
Subscription .newBuilder()
.setDeliveryConfig(
// Possible values for DeliveryRequirement:
// - `DELIVER_IMMEDIATELY`
// - `DELIVER_AFTER_STORED`
// `DELIVER_AFTER_STORED` requires a published message to be successfully written
// to storage before the server delivers it to subscribers.
DeliveryConfig.newBuilder()
.setDeliveryRequirement(DeliveryRequirement.DELIVER_AFTER_STORED))
.setName(subscriptionPath .toString ())
.build();
AdminClientSettings adminClientSettings=
AdminClientSettings .newBuilder().setRegion(CloudRegion .of(cloudRegion)).build();
try(AdminClient adminClient=AdminClient .create(adminClientSettings)){
Subscription subscriptionBeforeUpdate=adminClient.getSubscription(subscriptionPath).get();
System.out.println("Before update: "+subscriptionBeforeUpdate.getAllFields());
Subscription subscriptionAfterUpdate=
adminClient.updateSubscription(subscription,fieldMask).get();
System.out.println("After update: "+subscriptionAfterUpdate.getAllFields());
}catch(ExecutionExceptione){
try{
throwe.getCause();
}catch(NotFoundException notFound){
System.out.println("This subscription is not found.");
}catch(Throwablethrowable){
throwable.printStackTrace();
}
}
}
}

Python

Before running this sample, follow the Python setup instructions in Pub/Sub Lite Client Libraries.

fromgoogle.api_core.exceptionsimport NotFound
fromgoogle.cloud.pubsubliteimport AdminClient , Subscription
fromgoogle.cloud.pubsublite.typesimport CloudRegion , CloudZone , SubscriptionPath
fromgoogle.protobuf.field_mask_pb2import FieldMask
# TODO(developer):
# project_number = 1122334455
# cloud_region = "us-central1"
# zone_id = "a"
# topic_id = "your-topic-id"
# subscription_id = "your-subscription-id"
# regional = True
if regional:
 location = CloudRegion(cloud_region)
else:
 location = CloudZone(CloudRegion(cloud_region), zone_id)
subscription_path = SubscriptionPath(project_number, location, subscription_id)
field_mask = FieldMask(paths=["delivery_config.delivery_requirement"])
subscription = Subscription(
 name=str(subscription_path),
 delivery_config=Subscription.DeliveryConfig(
 # Possible values for delivery_requirement:
 # - `DELIVER_IMMEDIATELY`
 # - `DELIVER_AFTER_STORED`
 # `DELIVER_AFTER_STORED` requires a published message to be successfully written
 # to storage before the server delivers it to subscribers.
 delivery_requirement=Subscription.DeliveryConfig.DeliveryRequirement.DELIVER_AFTER_STORED,
 ),
)
client = AdminClient(cloud_region)
try:
 response = client.update_subscription (subscription, field_mask)
 print(f"{response.name} updated successfully.")
except NotFound:
 print(f"{subscription_path} not found.")

View Lite subscription details

You can get details about a Lite subscription using the Google Cloud console, the Google Cloud CLI, or the Pub/Sub Lite API.

Console

  1. Go to the Lite Subscriptions page.

    Go to Lite Subscriptions

  2. Click the Lite subscription ID.

  3. In the Lite subscription details page, click the Details tab.

gcloud

To get details about a Lite subscription, use the gcloud pubsub lite-subscriptions describe command:

gcloudpubsublite-subscriptionsdescribeSUBSCRIPTION_ID\
--location=LOCATION

Replace the following:

  • SUBSCRIPTION_ID: the ID of the Lite subscription

  • LOCATION: the name of the location that the Lite subscription is in

If the request is successful, the command line displays the Lite topic:

deliveryConfig:
 deliveryRequirement: DELIVERY_REQUIREMENT
name: projects/PROJECT_NUMBER/locations/LOCATION/subscriptions/SUBSCRIPTION_ID
topic: projects/PROJECT_NUMBER/locations/LOCATION/topics/TOPIC_ID

Protocol

To get details about a Lite subscription, send a GET request like the following:

GET https://REGION-pubsublite.googleapis.com/v1/admin/projects/PROJECT_NUMBER/locations/LOCATION/subscriptions/SUBSCRIPTION_ID
Authorization: Bearer $(gcloud auth print-access-token)

Replace the following:

  • REGION: the region to store the Lite subscription in

  • PROJECT_NUMBER: the project number of the project with the Lite subscription

  • LOCATION: the name of the location that the Lite subscription is in

  • SUBSCRIPTION_ID: the ID of the Lite subscription

If the request is successful, the response is the Lite topic in JSON format:

{
 "deliveryConfig": {
 "deliveryRequirement": DELIVERY_REQUIREMENT,
 }
 "name": "projects/PROJECT_NUMBER/locations/LOCATION/subscriptions/SUBSCRIPTION_ID",
 "topic": "projects/PROJECT_NUMBER/locations/LOCATION/topics/TOPIC_ID",
}

Go

Before running this sample, follow the Go setup instructions in Pub/Sub Lite Client Libraries.

import(
"context"
"fmt"
"io"
"cloud.google.com/go/pubsublite"
)
funcgetSubscription(wio.Writer,projectID,region,location,subIDstring)error{
// projectID := "my-project-id"
// region := "us-central1"
// NOTE: location can be either a region ("us-central1") or a zone ("us-central1-a")
// For a list of valid locations, see https://cloud.google.com/pubsub/lite/docs/locations.
// location := "us-central1"
// subID := "my-subscription"
ctx:=context.Background()
client,err:=pubsublite.NewAdminClient(ctx,region)
iferr!=nil{
returnfmt.Errorf("pubsublite.NewAdminClient: %w",err)
}
deferclient.Close()
subPath:=fmt.Sprintf("projects/%s/locations/%s/subscriptions/%s",projectID,location,subID)
sub,err:=client.Subscription(ctx,subPath)
iferr!=nil{
returnfmt.Errorf("client.Subscription got err: %w",err)
}
fmt.Fprintf(w,"Got subscription: %#v\n",sub)
returnnil
}

Java

Before running this sample, follow the Java setup instructions in Pub/Sub Lite Client Libraries.

importcom.google.api.gax.rpc.NotFoundException ;
importcom.google.cloud.pubsublite.AdminClient ;
importcom.google.cloud.pubsublite.AdminClientSettings ;
importcom.google.cloud.pubsublite.CloudRegion ;
importcom.google.cloud.pubsublite.CloudRegionOrZone ;
importcom.google.cloud.pubsublite.CloudZone ;
importcom.google.cloud.pubsublite.ProjectNumber ;
importcom.google.cloud.pubsublite.SubscriptionName ;
importcom.google.cloud.pubsublite.SubscriptionPath ;
importcom.google.cloud.pubsublite.proto.Subscription ;
importjava.util.concurrent.ExecutionException;
publicclass GetSubscriptionExample{
publicstaticvoidmain(String...args)throwsException{
// TODO(developer): Replace these variables before running the sample.
StringcloudRegion="your-cloud-region";
charzoneId='b';
// Choose an existing subscription.
StringsubscriptionId="your-subscription-id";
longprojectNumber=Long.parseLong("123456789");
// True if using a regional location. False if using a zonal location.
// https://cloud.google.com/pubsub/lite/docs/topics
booleanregional=false;
getSubscriptionExample(cloudRegion,zoneId,projectNumber,subscriptionId,regional);
}
publicstaticvoidgetSubscriptionExample(
StringcloudRegion,charzoneId,longprojectNumber,StringsubscriptionId,booleanregional)
throwsException{
CloudRegionOrZone location;
if(regional){
location=CloudRegionOrZone .of(CloudRegion .of(cloudRegion));
}else{
location=CloudRegionOrZone .of(CloudZone .of(CloudRegion .of(cloudRegion),zoneId));
}
SubscriptionPath subscriptionPath=
SubscriptionPath .newBuilder()
.setLocation(location)
.setProject(ProjectNumber .of(projectNumber))
.setName(SubscriptionName .of(subscriptionId))
.build();
AdminClientSettings adminClientSettings=
AdminClientSettings .newBuilder().setRegion(CloudRegion .of(cloudRegion)).build();
try(AdminClient adminClient=AdminClient .create(adminClientSettings)){
Subscription subscription=adminClient.getSubscription(subscriptionPath).get();
System.out.println(subscription.getAllFields());
}catch(ExecutionExceptione){
try{
throwe.getCause();
}catch(NotFoundException notFound){
System.out.println("This subscription is not found.");
}catch(Throwablethrowable){
throwable.printStackTrace();
}
}
}
}

Python

Before running this sample, follow the Python setup instructions in Pub/Sub Lite Client Libraries.

fromgoogle.api_core.exceptionsimport NotFound
fromgoogle.cloud.pubsubliteimport AdminClient
fromgoogle.cloud.pubsublite.typesimport CloudRegion , CloudZone , SubscriptionPath
# TODO(developer):
# project_number = 1122334455
# cloud_region = "us-central1"
# zone_id = "a"
# subscription_id = "your-subscription-id"
# regional = True
if regional:
 location = CloudRegion(cloud_region)
else:
 location = CloudZone(CloudRegion(cloud_region), zone_id)
subscription_path = SubscriptionPath(project_number, location, subscription_id)
client = AdminClient(cloud_region)
try:
 response = client.get_subscription (subscription_path)
 print(f"{response.name} exists.")
except NotFound:
 print(f"{subscription_path} not found.")

List Lite subscriptions

You can list the Lite subscriptions in a project or the Lite subscriptions to a Lite topic.

List Lite subscriptions in a project

You can list Lite subscriptions in a project using the Google Cloud console, the Google Cloud CLI, or the Pub/Sub Lite API.

Console

gcloud

gcloudpubsublite-subscriptionslist\
--location=LOCATION

Replace LOCATION with the name of the location that the Lite subscriptions are in.

If the request is successful, the command line displays the Lite subscriptions:

---
deliveryConfig:
deliveryRequirement:DELIVERY_REQUIREMENT
name:projects/PROJECT_NUMBER/locations/LOCATION/subscriptions/SUBSCRIPTION_ID
topic:projects/PROJECT_NUMBER/locations/LOCATION/topics/TOPIC_ID
---
deliveryConfig:
deliveryRequirement:DELIVERY_REQUIREMENT
name:projects/PROJECT_NUMBER/locations/LOCATION/subscriptions/SUBSCRIPTION_ID
topic:projects/PROJECT_NUMBER/locations/LOCATION/topics/TOPIC_ID

Protocol

  • To list the Lite subscriptions in a project, send a GET request like the following:
GET https://REGION-pubsublite.googleapis.com/v1/admin/projects/PROJECT_NUMBER/subscriptions
Authorization: Bearer $(gcloud auth print-access-token)

Replace the following:

  • REGION: the region to store the Lite subscription in

  • PROJECT_NUMBER: the project number of the project with the Lite subscription

If the request is successful, the response is the Lite topic in JSON format:

{
 "subscriptions": [
 {
 "name": "projects/PROJECT_NUMBER/locations/LOCATION/subscriptions/SUBSCRIPTION_ID"
 },
 {
 "name": "projects/PROJECT_NUMBER/locations/LOCATION/subscriptions/SUBSCRIPTION_ID"
 }
 ]
}

Go

Before running this sample, follow the Go setup instructions in Pub/Sub Lite Client Libraries.

import(
"context"
"fmt"
"io"
"cloud.google.com/go/pubsublite"
"google.golang.org/api/iterator"
)
funclistSubscriptionsInProject(wio.Writer,projectID,region,locationstring)error{
// projectID := "my-project-id"
// region := "us-central1"
// NOTE: location can be either a region ("us-central1") or a zone ("us-central1-a")
// For a list of valid locations, see https://cloud.google.com/pubsub/lite/docs/locations.
// location := "us-central1"
ctx:=context.Background()
client,err:=pubsublite.NewAdminClient(ctx,region)
iferr!=nil{
returnfmt.Errorf("pubsublite.NewAdminClient: %w",err)
}
deferclient.Close()
// To list topics in a region, set location to a cloud region instead.
parent:=fmt.Sprintf("projects/%s/locations/%s",projectID,location)
subIter:=client.Subscriptions (ctx,parent)
for{
sub,err:=subIter.Next()
iferr==iterator.Done{
break
}
iferr!=nil{
returnfmt.Errorf("subIter.Next() got err: %w",err)
}
fmt.Fprintf(w,"Got subscription config: %v",sub)
}
returnnil
}

Java

Before running this sample, follow the Java setup instructions in Pub/Sub Lite Client Libraries.

importcom.google.cloud.pubsublite.AdminClient ;
importcom.google.cloud.pubsublite.AdminClientSettings ;
importcom.google.cloud.pubsublite.CloudRegion ;
importcom.google.cloud.pubsublite.CloudRegionOrZone ;
importcom.google.cloud.pubsublite.CloudZone ;
importcom.google.cloud.pubsublite.LocationPath ;
importcom.google.cloud.pubsublite.ProjectNumber ;
importcom.google.cloud.pubsublite.proto.Subscription ;
importjava.util.List;
publicclass ListSubscriptionsInProjectExample{
publicstaticvoidmain(String...args)throwsException{
// TODO(developer): Replace these variables before running the sample.
StringcloudRegion="your-cloud-region";
charzoneId='b';
longprojectNumber=Long.parseLong("123456789");
// True if using a regional location. False if using a zonal location.
// https://cloud.google.com/pubsub/lite/docs/topics
booleanregional=true;
listSubscriptionsInProjectExample(cloudRegion,zoneId,projectNumber,regional);
}
publicstaticvoidlistSubscriptionsInProjectExample(
StringcloudRegion,charzoneId,longprojectNumber,booleanregional)throwsException{
AdminClientSettings adminClientSettings=
AdminClientSettings .newBuilder().setRegion(CloudRegion .of(cloudRegion)).build();
CloudRegionOrZone location;
if(regional){
location=CloudRegionOrZone .of(CloudRegion .of(cloudRegion));
}else{
location=CloudRegionOrZone .of(CloudZone .of(CloudRegion .of(cloudRegion),zoneId));
}
LocationPath locationPath=
LocationPath .newBuilder()
.setProject(ProjectNumber .of(projectNumber))
.setLocation(location)
.build();
try(AdminClient adminClient=AdminClient .create(adminClientSettings)){
List<Subscription>subscriptions=adminClient.listSubscriptions(locationPath).get();
for(Subscription subscription:subscriptions){
System.out.println(subscription.getAllFields());
}
System.out.println(subscriptions.size()+" subscription(s) listed in the project.");
}
}
}

Python

Before running this sample, follow the Python setup instructions in Pub/Sub Lite Client Libraries.

fromgoogle.cloud.pubsubliteimport AdminClient
fromgoogle.cloud.pubsublite.typesimport CloudRegion , CloudZone , LocationPath
# TODO(developer):
# project_number = 1122334455
# cloud_region = "us-central1"
# zone_id = "a"
# regional = True
if regional:
 location = CloudRegion(cloud_region)
else:
 location = CloudZone(CloudRegion(cloud_region), zone_id)
location_path = LocationPath(project_number, location)
client = AdminClient(cloud_region)
response = client.list_subscriptions (location_path)
for subscription in response:
 print(subscription.name)
print(f"{len(response)} subscription(s) listed in your project and location.")

Listing Lite subscriptions to a Lite topic

You can list Lite subscriptions to a Lite topic using the Google Cloud console, the Google Cloud CLI, or the Pub/Sub Lite API.

Console

  1. Go to the Lite Topics page.

    Go to Lite Topics

  2. Select a Lite topic ID.

  3. In the Lite topics details page, the Lite subscriptions section includes a list of Lite subscriptions to the Lite topic.

gcloud

gcloudpubsublite-topicslist-subscriptionsTOPIC_ID\
--location=LOCATION

Replace the following:

  • TOPIC_ID: the ID of the Lite topic that the Lite subscriptions are attached to

  • LOCATION: the name of the location that the Lite subscription is in

If the request is successful, the command line displays the Lite subscriptions:

---
deliveryConfig:
deliveryRequirement:DELIVERY_REQUIREMENT
name:projects/PROJECT_NUMBER/locations/LOCATION/subscriptions/SUBSCRIPTION_ID
topic:projects/PROJECT_NUMBER/locations/LOCATION/topics/TOPIC_ID
---
deliveryConfig:
deliveryRequirement:DELIVERY_REQUIREMENT
name:projects/PROJECT_NUMBER/locations/LOCATION/subscriptions/SUBSCRIPTION_ID
topic:projects/PROJECT_NUMBER/locations/LOCATION/topics/TOPIC_ID

Protocol

  • To list the Lite subscriptions to a Lite topic, send a GET request like the following:
GET https://REGION-pubsublite.googleapis.com/v1/admin/projects/PROJECT_NUMBER/lite-topics/TOPIC_ID/subscriptions
Authorization: Bearer $(gcloud auth print-access-token)

Replace the following:

  • REGION: the region to store the Lite subscription in

  • PROJECT_NUMBER: the project number of the project with the Lite subscription

  • LOCATION: the name of the location that the Lite subscription is in

  • TOPIC_ID: the ID of the Lite topic that the Lite subscriptions are attached to

If the request is successful, the response is a list of Lite subscriptions in JSON format:

{
 "subscriptions": [
 {
 "name": "projects/PROJECT_NUMBER/locations/LOCATION/subscriptions/SUBSCRIPTION_ID"
 },
 {
 "name": "projects/PROJECT_NUMBER/locations/LOCATION/subscriptions/SUBSCRIPTION_ID"
 }
 ]
}

Go

Before running this sample, follow the Go setup instructions in Pub/Sub Lite Client Libraries.

import(
"context"
"fmt"
"io"
"cloud.google.com/go/pubsublite"
"google.golang.org/api/iterator"
)
funclistSubscriptionsInTopic(wio.Writer,projectID,region,location,topicIDstring)error{
// projectID := "my-project-id"
// region := "us-central1"
// NOTE: location can be either a region ("us-central1") or a zone ("us-central1-a")
// For a list of valid locations, see https://cloud.google.com/pubsub/lite/docs/locations.
// location := "us-central"
// topicID := "my-topic"
ctx:=context.Background()
client,err:=pubsublite.NewAdminClient(ctx,region)
iferr!=nil{
returnfmt.Errorf("pubsublite.NewAdminClient: %w",err)
}
deferclient.Close()
topicPath:=fmt.Sprintf("projects/%s/locations/%s/topics/%s",projectID,location,topicID)
subPathIter:=client.TopicSubscriptions (ctx,topicPath)
for{
subPath,err:=subPathIter.Next()
iferr==iterator.Done{
break
}
iferr!=nil{
returnfmt.Errorf("subPathIter.Next got err: %w",err)
}
fmt.Fprintf(w,"Got subscription: %s\n",subPath)
}
returnnil
}

Java

Before running this sample, follow the Java setup instructions in Pub/Sub Lite Client Libraries.

importcom.google.cloud.pubsublite.AdminClient ;
importcom.google.cloud.pubsublite.AdminClientSettings ;
importcom.google.cloud.pubsublite.CloudRegion ;
importcom.google.cloud.pubsublite.CloudRegionOrZone ;
importcom.google.cloud.pubsublite.CloudZone ;
importcom.google.cloud.pubsublite.ProjectNumber ;
importcom.google.cloud.pubsublite.SubscriptionPath ;
importcom.google.cloud.pubsublite.TopicName ;
importcom.google.cloud.pubsublite.TopicPath ;
importjava.util.List;
publicclass ListSubscriptionsInTopicExample{
publicstaticvoidmain(String...args)throwsException{
// TODO(developer): Replace these variables before running the sample.
StringcloudRegion="your-cloud-region";
charzoneId='b';
longprojectNumber=Long.parseLong("123456789");
StringtopicId="your-topic-id";
// True if using a regional location. False if using a zonal location.
// https://cloud.google.com/pubsub/lite/docs/topics
booleanregional=false;
listSubscriptionsInTopicExample(cloudRegion,zoneId,projectNumber,topicId,regional);
}
publicstaticvoidlistSubscriptionsInTopicExample(
StringcloudRegion,charzoneId,longprojectNumber,StringtopicId,booleanregional)
throwsException{
CloudRegionOrZone location;
if(regional){
location=CloudRegionOrZone .of(CloudRegion .of(cloudRegion));
}else{
location=CloudRegionOrZone .of(CloudZone .of(CloudRegion .of(cloudRegion),zoneId));
}
TopicPath topicPath=
TopicPath .newBuilder()
.setProject(ProjectNumber .of(projectNumber))
.setLocation(location)
.setName(TopicName .of(topicId))
.build();
AdminClientSettings adminClientSettings=
AdminClientSettings .newBuilder().setRegion(CloudRegion .of(cloudRegion)).build();
try(AdminClient adminClient=AdminClient .create(adminClientSettings)){
List<SubscriptionPath>subscriptionPaths=
adminClient.listTopicSubscriptions(topicPath).get();
for(SubscriptionPath subscription:subscriptionPaths){
System.out.println(subscription.toString());
}
if(regional){
System.out.println(
subscriptionPaths.size()
+" subscription(s) listed in the regional topic "
+topicPath);
}else{
System.out.println(
subscriptionPaths.size()+" subscription(s) listed in the zonal topic "+topicPath);
}
}
}
}

Python

Before running this sample, follow the Python setup instructions in Pub/Sub Lite Client Libraries.

fromgoogle.cloud.pubsubliteimport AdminClient
fromgoogle.cloud.pubsublite.typesimport CloudRegion , CloudZone , TopicPath
# TODO(developer):
# project_number = 1122334455
# cloud_region = "us-central1"
# zone_id = "a"
# topic_id = "your-topic-id"
# regional = True
if regional:
 location = CloudRegion(cloud_region)
else:
 location = CloudZone(CloudRegion(cloud_region), zone_id)
topic_path = TopicPath(project_number, location, topic_id)
client = AdminClient(cloud_region)
response = client.list_topic_subscriptions (topic_path)
for subscription_path in response:
 print(subscription_path)
print(f"{len(response)} subscription(s) listed in your topic.")

Delete a Lite subscription

You can delete Lite subscriptions with the Google Cloud console, the Google Cloud CLI, or the Pub/Sub Lite API.

Console

  1. Go to the Lite Subscriptions page.

    Go to Lite Subscriptions

  2. Click the Lite subscription ID.

  3. In the Lite subscription details page, click Delete.

  4. In the dialog that appears, click Delete to confirm that you want to delete the Lite subscription.

gcloud

To delete a Lite subscription, use the gcloud pubsub lite-subscriptions delete command:

  1. Run the delete command:

    gcloudpubsublite-subscriptionsdeleteSUBSCRIPTION_ID\
    --location=LOCATION

    Replace the following:

    • SUBSCRIPTION_ID: the ID of the Lite subscription

    • LOCATION: the name of the location that the Lite subscription is in

  2. To confirm, type Y.

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

Deleted subscription [SUBSCRIPTION_ID].

Protocol

  • To delete a Lite topic, send a DELETE request like the following:
DELETE https://REGION-pubsublite.googleapis.com/v1/admin/projects/PROJECT_NUMBER/locations/LOCATION/subscriptions/SUBSCRIPTION_ID
Authorization: Bearer $(gcloud auth print-access-token)

Replace the following:

  • REGION: the region to store the Lite subscription in

  • PROJECT_NUMBER: the project number of the project with the Lite subscription

  • LOCATION: the name of the location that the Lite subscription is in

  • SUBSCRIPTION_ID: the ID of the Lite subscription

If the request is successful, the response is an empty JSON object.

Go

Before running this sample, follow the Go setup instructions in Pub/Sub Lite Client Libraries.

import(
"context"
"fmt"
"io"
"cloud.google.com/go/pubsublite"
)
funcdeleteSubscription(wio.Writer,projectID,region,location,subIDstring)error{
// projectID := "my-project-id"
// region := "us-central1"
// NOTE: location can be either a region ("us-central1") or a zone ("us-central1-a")
// For a list of valid locations, see https://cloud.google.com/pubsub/lite/docs/locations.
// location := "us-central1"
// subID := "my-subscription"
ctx:=context.Background()
client,err:=pubsublite.NewAdminClient(ctx,region)
iferr!=nil{
returnfmt.Errorf("pubsublite.NewAdminClient: %w",err)
}
deferclient.Close()
err=client.DeleteSubscription(ctx,fmt.Sprintf("projects/%s/locations/%s/subscriptions/%s",projectID,location,subID))
iferr!=nil{
returnfmt.Errorf("client.DeleteSubscription got err: %w",err)
}
fmt.Fprintf(w,"Deleted subscription\n")
returnnil
}

Java

Before running this sample, follow the Java setup instructions in Pub/Sub Lite Client Libraries.

importcom.google.api.gax.rpc.NotFoundException ;
importcom.google.cloud.pubsublite.AdminClient ;
importcom.google.cloud.pubsublite.AdminClientSettings ;
importcom.google.cloud.pubsublite.CloudRegion ;
importcom.google.cloud.pubsublite.CloudRegionOrZone ;
importcom.google.cloud.pubsublite.CloudZone ;
importcom.google.cloud.pubsublite.ProjectNumber ;
importcom.google.cloud.pubsublite.SubscriptionName ;
importcom.google.cloud.pubsublite.SubscriptionPath ;
importjava.util.concurrent.ExecutionException;
publicclass DeleteSubscriptionExample{
publicstaticvoidmain(String...args)throwsException{
// TODO(developer): Replace these variables before running the sample.
StringcloudRegion="your-cloud-region";
charzoneId='b';
// Choose an existing subscription.
StringsubscriptionId="your-subscription-id";
longprojectNumber=Long.parseLong("123456789");
// True if using a regional location. False if using a zonal location.
// https://cloud.google.com/pubsub/lite/docs/topics
booleanregional=false;
deleteSubscriptionExample(cloudRegion,zoneId,projectNumber,subscriptionId,regional);
}
publicstaticvoiddeleteSubscriptionExample(
StringcloudRegion,charzoneId,longprojectNumber,StringsubscriptionId,booleanregional)
throwsException{
CloudRegionOrZone location;
if(regional){
location=CloudRegionOrZone .of(CloudRegion .of(cloudRegion));
}else{
location=CloudRegionOrZone .of(CloudZone .of(CloudRegion .of(cloudRegion),zoneId));
}
SubscriptionPath subscriptionPath=
SubscriptionPath .newBuilder()
.setLocation(location)
.setProject(ProjectNumber .of(projectNumber))
.setName(SubscriptionName .of(subscriptionId))
.build();
AdminClientSettings adminClientSettings=
AdminClientSettings .newBuilder().setRegion(CloudRegion .of(cloudRegion)).build();
try(AdminClient adminClient=AdminClient .create(adminClientSettings)){
adminClient.deleteSubscription(subscriptionPath).get();
System.out.println(subscriptionPath+" deleted successfully.");
}catch(ExecutionExceptione){
try{
throwe.getCause();
}catch(NotFoundException notFound){
System.out.println("This subscription is not found.");
}catch(Throwablethrowable){
throwable.printStackTrace();
}
}
}
}

Python

Before running this sample, follow the Python setup instructions in Pub/Sub Lite Client Libraries.

fromgoogle.api_core.exceptionsimport NotFound
fromgoogle.cloud.pubsubliteimport AdminClient
fromgoogle.cloud.pubsublite.typesimport CloudRegion , CloudZone , SubscriptionPath
# TODO(developer):
# project_number = 1122334455
# cloud_region = "us-central1"
# zone_id = "a"
# subscription_id = "your-subscription-id"
# regional = True
if regional:
 location = CloudRegion(cloud_region)
else:
 location = CloudZone(CloudRegion(cloud_region), zone_id)
subscription_path = SubscriptionPath(project_number, location, subscription_id)
client = AdminClient(cloud_region)
try:
 client.delete_subscription (subscription_path)
 print(f"{subscription_path} deleted successfully.")
except NotFound:
 print(f"{subscription_path} not found.")

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 2025年11月11日 UTC.