Connect services asynchronously with Pub/Sub: create topics and subscriptions, publish and pull messages, push messages to an endpoint, and use it to decouple and buffer work across your system.
Pub/Sub is a messaging service: publishers send messages to a "topic," and subscribers receive them — without the two knowing about each other. Why: it decouples services (one can be down without losing messages) and absorbs spikes (work queues up instead of overwhelming a consumer). It is the backbone of event-driven systems.
Enable the API
gcloud services enable pubsub.googleapis.comList your topics
gcloud pubsub topics listA topic is a named channel publishers send messages to. Why: producers just publish to the topic and move on; they do not care who (if anyone) is listening. One topic can fan out to many subscribers.
Create a topic
gcloud pubsub topics create ordersPublish a message to it
gcloud pubsub topics publish orders \
--message '{"orderId": "order-1", "total": 42.50}'A subscription represents one stream of a topic's messages for one consumer. Why each subscription gets its own copy: two subscriptions on the same topic both receive every message, so you can have, say, a billing service and an analytics service each processing all orders independently.
Create a pull subscription on the topic
gcloud pubsub subscriptions create orders-worker --topic ordersPull and acknowledge a message (acking removes it from the subscription)
gcloud pubsub subscriptions pull orders-worker --auto-ack --limit 5Instead of your consumer pulling, a push subscription has Pub/Sub POST each message to an HTTPS endpoint (like a Cloud Run service or Function). Why: no polling loop to run — your endpoint is invoked as messages arrive, and Pub/Sub retries on failure.
Create a push subscription that delivers to a Cloud Run / function URL
gcloud pubsub subscriptions create orders-push \
--topic orders \
--push-endpoint "https://web-xxxx.run.app/events" \
--ack-deadline 30A consumer must "acknowledge" a message or Pub/Sub redelivers it — guaranteeing at-least-once delivery. A dead-letter topic catches messages that keep failing after N attempts. Why: failed work is not lost or retried forever; it lands somewhere you can inspect and fix.
Add a dead-letter topic: messages failing 5 times go to "orders-dead"
gcloud pubsub topics create orders-deadgcloud pubsub subscriptions update orders-worker \
--dead-letter-topic orders-dead \
--max-delivery-attempts 5