Modern systems rarely do everything in one request. A web app accepts an upload, a worker resizes images later, and an analytics pipeline counts events hours after they arrive. Google Cloud PubSub is the managed messaging service that connects those pieces: publishers send messages to a topic, and subscribers receive them independently, at their own pace, without either side knowing about the other. This guide covers the basics end to end, from creating a topic and subscription to publishing, pulling, and acknowledging messages.

Everything below uses Google Cloud PubSub with the gcloud CLI, so you can follow along in any project. By the end, you will be able to set up a working publish and pull flow with the gcloud CLI, explain the difference between push and pull delivery, and handle the common problems that trip up first-time users, such as unacknowledged messages piling up and permission errors.
What Is Google Cloud PubSub?
Pub/Sub follows the publish-subscribe pattern. A publisher sends a message to a topic, which is a named channel. A subscription is attached to a topic, and each subscription receives its own copy of every message published to that topic. Two subscriptions on the same topic each get the full stream, which makes it easy to fan out one event to several consumers: one subscriber writes to a database, another triggers a notification, and a third feeds an analytics pipeline.
Messages are not queues in the traditional sense. A message stays available on a subscription until a subscriber acknowledges it or until the subscription’s retention period expires, which defaults to seven days. If a subscriber crashes before acknowledging, Pub/Sub redelivers the message after the acknowledgement deadline passes. That at-least-once delivery guarantee is central to how you should design consumers: message handlers must be idempotent, meaning processing the same message twice produces the same result as processing it once.
Pub/Sub is fully managed, so there are no brokers to patch or scale. You pay for message volume and storage, and Google handles availability and throughput. That makes it a good default choice for decoupling services on Google Cloud.
Prerequisites
- A Google Cloud project with billing enabled, and the Pub/Sub API enabled. Enable it with
gcloud services enable pubsub.googleapis.comif it is not already on. - The gcloud CLI installed and authenticated with an account that has permission to manage Pub/Sub resources in the project. If you have not set up the CLI yet, follow our guide to install the gcloud CLI on Linux and run your first commands.
- Either the Owner or Editor role on the project, or the more specific
roles/pubsub.adminrole, for the setup steps below. - A shell with the gcloud CLI available, and a project selected with
gcloud config set project PROJECT_ID.
All commands in this guide use the default region-independent Pub/Sub service, so there is no region or zone to choose. Topics and subscriptions are global resources within a project.
Creating a Topic and a Pull Subscription
Start by creating a topic. Topic IDs must be unique within the project and are typically written in lowercase with hyphens.
gcloud pubsub topics create orders-events
Next, create a pull subscription attached to that topic. A pull subscription means your code explicitly requests messages, which is the simplest model for scripts, workers, and testing from the command line.
gcloud pubsub subscriptions create orders-worker \
--topic=orders-events \
--ack-deadline=60
The acknowledgement deadline is how long a subscriber has to acknowledge a message before Pub/Sub redelivers it. The default is 10 seconds, which is too short for most real work, so this example sets 60 seconds. Choose a value comfortably longer than your slowest expected processing time.
Verify both resources exist:
gcloud pubsub topics list
gcloud pubsub subscriptions list
You can also inspect a subscription’s configuration at any time with gcloud pubsub subscriptions describe orders-worker, which shows the topic, acknowledgement deadline, and retention settings.
Publishing Messages with Google Cloud PubSub
Publish a message with the publish command. The message data is passed as a string, and Pub/Sub assigns it a message ID, which the command prints.
gcloud pubsub topics publish orders-events \
--message="order-1001 created"
Publish a few more messages so the pull step has something to show:
gcloud pubsub topics publish orders-events \
--message="order-1002 created"
gcloud pubsub topics publish orders-events \
--message="order-1003 cancelled"
Messages can also carry attributes, which are key-value metadata that subscribers can filter on. Attributes are useful when consumers only care about a subset of messages, for example only cancellations:
gcloud pubsub topics publish orders-events \
--message="order-1004 cancelled" \
--attribute=event-type=cancelled,region=eu
Note that message data is limited to 10 MB per message. If you need to move larger payloads, store the payload in Cloud Storage and send only a reference in the message. Our guide to creating a Cloud Storage bucket with permissions and lifecycle rules covers the storage side of that pattern.
Pulling and Acknowledging Messages
Pull messages from your Google Cloud PubSub subscription. The --auto-ack flag acknowledges each message as soon as it is delivered, which is convenient for testing but not what you want in production code, where you should acknowledge only after successful processing.
gcloud pubsub subscriptions pull orders-worker \
--auto-ack \
--limit=10
Without --auto-ack, the output includes an acknowledgement ID for each message. Acknowledge a message explicitly with that ID:
gcloud pubsub subscriptions pull orders-worker --limit=5
gcloud pubsub subscriptions ack orders-worker \
--ack-ids=ACK_ID_FROM_OUTPUT
In application code, the same flow applies through the client libraries: pull or receive, process, then acknowledge. If processing fails, do not acknowledge; let the deadline expire so Pub/Sub redelivers the message. If a message keeps failing, it will be redelivered repeatedly, which is why dead-letter handling, covered below, matters for production systems.
To extend the deadline while a long task is still running, subscribers can call modify acknowledgement deadline, exposed in the client libraries as a lease extension. This prevents a slow but healthy consumer from receiving duplicates of a message it is still processing.
Push Versus Pull Delivery
Pull delivery suits workers, scripts, and services that want to control their own pace. Push delivery suits web services: Pub/Sub sends each message as an HTTPS POST to an endpoint you provide, and a 2xx response counts as acknowledgement. Choosing between them is one of the first design decisions for a Pub/Sub architecture.
| Aspect | Pull delivery | Push delivery |
|---|---|---|
| Flow control | Subscriber decides when to request messages | Pub/Sub pushes as messages arrive |
| Endpoint | None needed; any environment can pull | Public HTTPS endpoint required |
| Best for | Workers, batch jobs, private services | Webhooks, Cloud Run, App Engine services |
| Failure handling | Unacked messages redeliver after the deadline | Non-2xx responses trigger redelivery with backoff |
| Ordering | Available with ordering keys | Available with ordering keys |
Create a push subscription by adding an endpoint instead of pulling:
gcloud pubsub subscriptions create orders-webhook \
--topic=orders-events \
--push-endpoint=https://example.com/pubsub-handler \
--ack-deadline=30
Push endpoints must be publicly reachable over HTTPS and should verify the request, for example by checking the token Pub/Sub can attach, before trusting the payload. Never expose a push endpoint that processes messages without authentication in production.
Ordering and Dead-Letter Basics
By default, Google Cloud PubSub does not guarantee the order in which messages are delivered. When order matters, such as a sequence of updates to the same order record, enable message ordering on the subscription and publish messages with the same ordering key. Messages sharing a key are delivered in publish order; messages with different keys can still arrive out of order relative to each other.
gcloud pubsub subscriptions create orders-sequenced \
--topic=orders-events \
--enable-message-ordering
Ordering keys must be set by the publisher, which the gcloud CLI does not support directly for individual messages, so ordering is normally used through the client libraries rather than the CLI. Keep this in mind when prototyping: the CLI is excellent for learning the concepts, but production publishers use a client library.
Dead-letter topics catch messages that fail repeatedly. After a configurable number of delivery attempts, Pub/Sub forwards the message to a dead-letter topic instead of redelivering it forever, and you can inspect or replay those messages later.
gcloud pubsub subscriptions create orders-worker-dlq \
--topic=orders-events \
--dead-letter-topic=orders-dead-letter \
--max-delivery-attempts=5
The dead-letter topic must exist before you create the subscription, and Pub/Sub’s service account needs publish permission on it. Five delivery attempts is a reasonable starting point; tune it based on how often your failures are transient.
Troubleshooting Google Cloud PubSub
Permission denied when publishing or pulling
Publishing requires the roles/pubsub.publisher role on the topic, and pulling requires roles/pubsub.subscriber on the subscription. A common mistake is granting a role on the project but testing with a different project selected in gcloud, or granting the role to a service account while authenticated as a personal account. Check the active account with gcloud auth list and the active project with gcloud config get-value project before changing IAM bindings.
Messages are delivered more than once
Duplicates are expected behavior, not a bug. At-least-once delivery means a message can arrive twice if an acknowledgement is lost or a deadline expires while processing is still running. Make handlers idempotent, for example by recording processed message IDs or by making the operation itself safe to repeat, such as an upsert keyed on the order ID.
Unacknowledged messages keep building up
Check the subscription’s backlog in the console or with gcloud pubsub subscriptions describe. A growing backlog usually means the consumer is down, too slow, or crashing before it acknowledges. Also check whether the acknowledgement deadline is shorter than the processing time, which causes redelivery storms: each redelivery adds work, which makes the backlog grow faster. Raising the deadline and scaling the consumer are the usual fixes.
Pull returns no messages even though you published
Confirm you are pulling from a subscription on the right topic, and that the messages were published after the subscription was created. Subscriptions only receive messages published after their creation; earlier messages are not replayed unless you use the seek feature with a snapshot. Also check that you are not pulling from a different project than the one holding the topic.
Conclusion
Google Cloud PubSub gives you a simple, durable way to decouple services: publishers write to a topic, subscriptions deliver to independent consumers, and acknowledgement controls redelivery. The core workflow is short, create a topic, create a subscription, publish, pull, acknowledge, but the details around deadlines, ordering, and dead-letter handling are what make a system reliable in production.
Start with a pull subscription and the gcloud CLI to learn the mechanics, then move to a client library for real publishers and subscribers. Add ordering only where sequence genuinely matters, set up a dead-letter topic before your first production deploy, and design every handler to be idempotent. For the full API reference, quotas, and advanced features such as schemas and exactly-once delivery, see the Google Cloud Pub/Sub documentation.