Search code examples
gogoogle-cloud-platformgoogle-cloud-pubsub

Google Pub/Sub set enable message retention on topic programatically


In google pub/sub, if topic created, we could set the retention policy

https://console.cloud.google.com/cloudpubsub

list of topics

by clicking, edit, edit topic, update

updating retention policy

is it possible to update this value programmatically?

I see that there is such configuration on subscription level https://github.com/googleapis/google-cloud-go/blob/main/pubsub/subscription.go#L564 but not in the topic level?


Solution

  • Yes, message retention can be configured in the topic programmatically. In Go, you would set the RetentionDuration in the TopicConfig and pass that to CreateTopicWithConfig to do it at create time:

    tc := TopicConfig{
        RetentionDuration = 168 * time.Hour
    }
    topic, err := c.CreateTopicWithConfig(context.Background(), "my-topic", tc)
    

    To do it at update time, you set the property in the TopicConfigToUpdate and pass it to Update:

    topic := client.Topic("my-topic")
    topicConfig, err := topic.Update(ctx, pubsub.TopicConfigToUpdate{
      RetentionDuration = 168 * time.Hour
    })