Search code examples
google-cloud-platformgoogle-cloud-pubsubgoogle-cloud-run

What would be a good way to initialize a subscription for pubsub


I am trying to use pubsub for the first time outside of cloud functions in a cloud run service, and I am confused about the use of createSubscription.

I trigger the message from a job in cloud scheduler, and when I set the topic it creates the topic in the project for me if it doesn't exist yet.

Now the cloud run service, when it starts, could call createSubscription, because initially there is no subscription yet. But it seems that createSubscription should only be called once (like createTopic) because after that I get an error saying a subscription with that name already exists.

I could place a try/catch around createSubscription and ignore the error on subsequent service deployments, but that seems a bit odd.

What would be a good way to initialize the subscription?


Solution

  • This is what we do in production - we have a try-catch block, so if the sub is already there, we ignore the exception. Make sure to also check the filters if necessary. They might change (if you change them programmatically, in this case you need to recreate the subscription)

        TopicName topic = TopicName.ofProjectTopicName(projectId, this.topic);
        try {
            client.createSubscription("projects/xxx/subscriptions/" + subscriptionId, topic, PushConfig.getDefaultInstance(), 600);
        } catch (AlreadyExistsException e) {
            // sub is already there. nothing to do
        }