Updated Dec 1, 20266 min read

Create Google Cloud Pub/Sub Topics Without Terraform

How to create a Pub/Sub topic and subscription with gcloud, which ack deadline, retry policy, dead-letter topic and IAM grants a production subscription needs, what the same setup looks like in Terraform, and how to declare topics and subscribers in application code.

Illustration for Create Google Cloud Pub/Sub Topics Without Terraform

A Google Cloud Pub/Sub topic takes one gcloud command, and the subscription behind it decides how production behaves: how long a handler has before redelivery, how retries back off, where a message goes after the last attempt and which service account may read it.

This guide sets those up with gcloud, then in Terraform, then declares the topic and its subscribers in application code.

What does a Pub/Sub topic need?

PieceWhat to decide
TopicA name, and an optional message retention on the topic for replay
Subscription per consumerOne for each service that handles the event, since each receives every message
Ack deadlineSeconds the handler has before redelivery, 10 by default
Retry policyExponential backoff between a minimum and maximum delay, each up to 600 seconds
Dead-letter topicWhere a message goes after 5 to 100 failed deliveries, with its own subscription
IAMPublisher on the topic for the producer, subscriber on each subscription for its consumer
Service agent grantsThe Pub/Sub service account needs publisher on the dead-letter topic and subscriber on the subscription

The dead-letter settings and the service agent grants are covered in the guide to handling message failures, and the Pub/Sub access control page lists the roles that can be granted on a single topic or subscription.

What are the options besides Terraform?

The console creates a topic with a default subscription in one form, and the settings above take a few more gcloud commands, with the grants at the end:

~
$ gcloud pubsub topics create order-placed$ gcloud pubsub topics create send-receipt-dead-letter$ gcloud pubsub subscriptions create send-receipt-dead-letter --topic=send-receipt-dead-letter$ gcloud pubsub subscriptions create send-receipt --topic=order-placed \ --ack-deadline=60 --min-retry-delay=10s --max-retry-delay=600s \ --dead-letter-topic=send-receipt-dead-letter --max-delivery-attempts=5$ gcloud pubsub topics add-iam-policy-binding order-placed \ --member=serviceAccount:orders@my-project.iam.gserviceaccount.com \ --role=roles/pubsub.publisher$ gcloud pubsub subscriptions add-iam-policy-binding send-receipt \ --member=serviceAccount:receipts@my-project.iam.gserviceaccount.com \ --role=roles/pubsub.subscriber$ PUBSUB_AGENT=serviceAccount:service-123456789@gcp-sa-pubsub.iam.gserviceaccount.com$ gcloud pubsub topics add-iam-policy-binding send-receipt-dead-letter \ --member=$PUBSUB_AGENT --role=roles/pubsub.publisher$ gcloud pubsub subscriptions add-iam-policy-binding send-receipt \ --member=$PUBSUB_AGENT --role=roles/pubsub.subscriber

The flags are documented in the gcloud pubsub subscriptions create reference, and the service agent address uses the project number, not the project ID. A second consumer of the same event repeats the subscription, its dead-letter topic and four grants, and a second environment repeats everything, which is the part Terraform turns into code.

What does the Terraform look like?

The same setup is two topics, a subscription with retry and dead-letter policies, and IAM members for the services and the Pub/Sub service agent:

data "google_project" "current" {} locals { pubsub_agent = "serviceAccount:service-${data.google_project.current.number}@gcp-sa-pubsub.iam.gserviceaccount.com" } resource "google_pubsub_topic" "order_placed" { name = "order-placed" } resource "google_pubsub_topic" "send_receipt_dead_letter" { name = "send-receipt-dead-letter" } resource "google_pubsub_subscription" "send_receipt_dead_letter" { name = "send-receipt-dead-letter" topic = google_pubsub_topic.send_receipt_dead_letter.id } resource "google_pubsub_subscription" "send_receipt" { name = "send-receipt" topic = google_pubsub_topic.order_placed.id ack_deadline_seconds = 60 retry_policy { minimum_backoff = "10s" maximum_backoff = "600s" } dead_letter_policy { dead_letter_topic = google_pubsub_topic.send_receipt_dead_letter.id max_delivery_attempts = 5 } } resource "google_pubsub_topic_iam_member" "orders_publish" { topic = google_pubsub_topic.order_placed.id role = "roles/pubsub.publisher" member = "serviceAccount:orders@my-project.iam.gserviceaccount.com" } resource "google_pubsub_subscription_iam_member" "receipts_consume" { subscription = google_pubsub_subscription.send_receipt.id role = "roles/pubsub.subscriber" member = "serviceAccount:receipts@my-project.iam.gserviceaccount.com" } resource "google_pubsub_topic_iam_member" "agent_dead_letter" { topic = google_pubsub_topic.send_receipt_dead_letter.id role = "roles/pubsub.publisher" member = local.pubsub_agent } resource "google_pubsub_subscription_iam_member" "agent_ack" { subscription = google_pubsub_subscription.send_receipt.id role = "roles/pubsub.subscriber" member = local.pubsub_agent }

The subscription arguments are listed in the google_pubsub_subscription documentation.

How does Encore create Pub/Sub from code?

Encore brings infrastructure from code, so a topic is declared in the service that publishes it, each subscription in the service that handles it, and a deploy to your own Google Cloud project creates the topics, subscriptions and dead-letter topics, as the GCP infrastructure docs describe. Each service gets its own service account with only the Pub/Sub permissions it needs. The ack deadline and retry policy are fields on the subscription in code, so the settings from the gcloud commands above live next to the handler they apply to.

Application code passes through Encore and infrastructure guardrails to resources provisioned in your own AWS or GCP account.

Set up the app

Get started
brew install encoredev/tap/encore &&
encore app create
Copy

Run in your terminal to get started locally.

~
$ encore app create shop --example=hello-world$ cd shop && mkdir orders receipts

The orders service declares the topic and publishes from its endpoint:

// orders/orders.go package orders import ( "context" "encore.dev/beta/errs" "encore.dev/pubsub" ) type OrderPlaced struct { OrderID string `json:"order_id"` Email string `json:"email"` Cents int64 `json:"cents"` } var OrderPlacedTopic = pubsub.NewTopic[*OrderPlaced]("order-placed", pubsub.TopicConfig{ DeliveryGuarantee: pubsub.AtLeastOnce, }) type PlaceResponse struct { MessageID string `json:"message_id"` } //encore:api public method=POST path=/orders func Place(ctx context.Context, o *OrderPlaced) (*PlaceResponse, error) { if o.OrderID == "" || o.Email == "" || o.Cents <= 0 { return nil, &errs.Error{Code: errs.InvalidArgument, Message: "order_id, email and a positive amount are required"} } id, err := OrderPlacedTopic.Publish(ctx, o) if err != nil { return nil, err } return &PlaceResponse{MessageID: id}, nil }

The receipts service subscribes with the same ack deadline and backoff as the gcloud example, and passes the order ID as the idempotency key to the email provider, so a redelivered message cannot send a second receipt:

// receipts/receipts.go package receipts import ( "context" "time" "encore.app/orders" "encore.dev/pubsub" "encore.dev/rlog" ) // sendEmail stands in for your email provider, which must deduplicate on the key. func sendEmail(ctx context.Context, idempotencyKey, to, body string) error { rlog.Info("sending receipt", "key", idempotencyKey, "to", to) return nil } var _ = pubsub.NewSubscription(orders.OrderPlacedTopic, "send-receipt", pubsub.SubscriptionConfig[*orders.OrderPlaced]{ Handler: func(ctx context.Context, o *orders.OrderPlaced) error { return sendEmail(ctx, "receipt-"+o.OrderID, o.Email, "Thanks for your order") }, AckDeadline: 60 * time.Second, RetryPolicy: &pubsub.RetryPolicy{ MinBackoff: 10 * time.Second, MaxBackoff: 10 * time.Minute, MaxRetries: 5, }, }, )

encore run runs both services and the topic locally. A POST /orders is how you exercise that path: the orders service publishes the event and the receipt handler calls sendEmail, which logs the receipt, and a handler that returns an error is retried with the policy from code. The Pub/Sub docs cover delivery guarantees, ordering and the dead-letter queue, and a topic you already run can be attached with Import an existing Pub/Sub topic. To deploy, follow Connect your cloud account for a Google Cloud project and push.

An AI coding agent adding a second consumer, such as a loyalty points service, writes one more subscription in that service, and the new subscription and its dead-letter topic come from the same change instead of a separate infrastructure pull request.

Best fit: Teams on Google Cloud that want topics, subscriptions and retry settings declared next to the handlers and created in their own project.

Frequently asked questions

How do I create a Pub/Sub subscription with a dead-letter topic using gcloud?

Create the main topic and a dead-letter topic, then run gcloud pubsub subscriptions create with --topic, --dead-letter-topic and --max-delivery-attempts between 5 and 100. Grant the Pub/Sub service agent the publisher role on the dead-letter topic and the subscriber role on the subscription, or messages are never forwarded.

What ack deadline and retry settings should a Pub/Sub subscription use?

Set the ack deadline a little above the slowest normal run of the handler, since the default is 10 seconds, and set an exponential retry policy with --min-retry-delay and --max-retry-delay, each between 0 and 600 seconds. Unacknowledged messages are kept for 7 days by default and up to 31 days.

Which IAM roles does a service need to use Pub/Sub?

The publishing service needs roles/pubsub.publisher on the topic and the consuming service needs roles/pubsub.subscriber on its subscription. Granting them on the resource instead of the project keeps one service from reading another service's messages.

How do I create Pub/Sub topics from application code?

Declare a topic and its subscriptions in code with Encore, run encore run to test the handlers locally and deploy to your own Google Cloud project. Encore creates the topic, the subscriptions and dead-letter topics, and applies the retry policy set in code.

Deploy to your cloud on AWS and Google Cloud without managing infrastructure

Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.

~/orders — claude
Claude Code
Claude Code v2.1.180Opus 5.5~/orders