Pub/Sub in Google Cloud

Pub/Sub in Google Cloud

A friendly, complete guide to Google's global messaging service: how applications pass messages without waiting for each other, how delivery, retries and ordering really work, and how to build systems that stay calm when traffic gets wild.

Imagine you place an order on a shopping app. In the next few seconds many things need to happen: the payment must be confirmed, the stock must be reduced, an email must be sent, the warehouse must be told to pack the parcel, and the analytics team wants to count the sale. If the app had to call each of those systems one by one and wait for every answer, your screen would freeze, and a single slow system could ruin the whole experience.

There is a much better way. The shopping app can simply announce, “A new order was placed”, and move on. Every other system that cares about new orders listens for that announcement and does its own work in its own time. This style is called messaging, and Pub/Sub is Google Cloud’s service for it. This guide explains Pub/Sub from zero. Every new word is explained when it first appears, so you can follow along even if you have never built a distributed system.

WWhat Is Pub/Sub?

Start with the big picture: the idea of publishing and subscribing, and what Google’s service gives you.

Pub/Sub is short for publish and subscribe. It is a fully managed, asynchronous messaging service on Google Cloud. A message is a small package of information, such as “order 4521 was placed”. A publisher is a program that creates messages and sends them. A subscriber is a program that receives and processes them. Between them sits Pub/Sub, which accepts messages, stores them safely and delivers them to everyone who has asked for them.

The word asynchronous means the sender and the receiver do not have to be busy at the same moment. The publisher drops the message off and continues with its work. The subscriber picks the message up whenever it is ready. This is like sending a letter instead of making a phone call: you do not need the other person to be at home when you post it.

“Fully managed” means Google runs all the machinery: the servers, the storage, the copies for safety and the scaling. You do not set up clusters or decide how many machines to use. Pub/Sub is also a global service, which means publishers and subscribers in different parts of the world can use the same topic through Google’s network, while you can still choose where messages are allowed to be stored.

Everyday Analogy

Think of a school notice board. A teacher pins a notice (“Sports day on Friday”) and walks away. Students, parents and the sports staff each read the board at their own time. The teacher does not need to find each person or wait until they read it. The notice board is Pub/Sub, the teacher is the publisher, and every reader is a subscriber.

What Pub/Sub is good at

  • Decoupling: services do not need to know about each other, only about the shared topic.
  • Absorbing bursts: if a thousand messages arrive in one second, Pub/Sub holds them while slower workers catch up.
  • Fan-out: one message can be delivered to many different consumers.
  • Streaming data in: events from apps, devices and logs can flow into analytics tools continuously.
Serverless
no brokers or clusters for you to size or patch
Global
one service reachable from anywhere on Google’s network
Durable
messages are stored on Google’s infrastructure until delivered or expired
i
Tip

Pub/Sub carries messages. It does not run your business logic. Your subscriber programs, such as a Cloud Run service or a Dataflow job, do the real work after a message arrives.

TThe Problem Pub/Sub Solves

Every good tool begins with a pain. Here are the pains of connecting systems directly.

Pain 1: Tight coupling

When System A calls System B directly, A must know B’s address, B’s rules and B’s schedule. If B is slow, A is slow. If B is down, A fails. Add a third and fourth system and the web of connections grows quickly. Changing one system risks breaking the others. This is called tight coupling.

Pain 2: Spikes crush slow systems

Traffic is rarely smooth. A flash sale can send fifty times the normal number of orders in a minute. If the order system forwards each order immediately to a billing system that can handle only a steady trickle, the billing system collapses. A buffer in the middle is needed to smooth the bursts.

Pain 3: One event, many interested parties

Many teams care about the same event. Billing, shipping, email, fraud checks and analytics all want to know about a new order. Without a shared channel, the order system must call every one of them. Each time a new team wants the events, the order system must change.

Pain 4: Lost work when things fail

If a receiver crashes while a request is in flight, the request may be lost forever. A reliable middle layer stores each message until the receiver confirms it finished the work, so a crash simply means the message is tried again.

Pain 5: Moving data into analytics

Companies want clicks, sensor readings and logs to flow continuously into data warehouses and processing engines. Building and running that pipe from scratch is costly. A managed streaming entrance saves much effort.

Everyday Analogy

A busy restaurant kitchen does not have waiters shouting orders directly at each cook and waiting for each one to finish. Instead, orders go onto a rail above the counter. Cooks take tickets when they are free, the rail holds extra tickets during a rush, and the manager can add another cook without telling the waiters. The rail is the buffer and the shared channel.

CCore Concepts You Must Know

Eight building blocks explain almost everything you will see in Pub/Sub.

Channel

Topic

A named channel where publishers send messages. Think of it as the notice board. Publishers talk to topics, never directly to subscribers.

Listener

Subscription

A named link between a topic and a receiving application. Each subscription gets its own copy of every message. Subscribers talk to subscriptions.

Data

Message

The unit of information. It has a data body, optional attributes (small labels), a message ID and a publish time. It may also carry an ordering key.

Sender

Publisher

Any program that sends messages to a topic, such as a web app, a device or another cloud service.

Receiver

Subscriber

Any program that receives messages from a subscription and processes them.

Confirmation

Acknowledgment (Ack)

A “got it and finished” signal from the subscriber. Until a message is acknowledged, Pub/Sub keeps it and may deliver it again.

Timer

Ack Deadline

How long Pub/Sub waits for an acknowledgment before assuming something went wrong and sending the message again.

Safety Net

Dead-Letter Topic

A special topic that collects messages that keep failing, so they do not block the system and can be examined later.

Handy words

TermWhat it meansEveryday picture
Fan-outOne message goes to many subscriptionsOne announcement read by many departments
PushPub/Sub sends the message to your web addressA courier delivers to your door
PullYour program asks Pub/Sub for messagesYou collect your parcels from the post office
BacklogMessages waiting to be processedThe pile of tickets on the kitchen rail
IdempotentDoing the same action twice has the same result as doing it oncePressing the lift button twice
AttributeA small key and value label on a messageA sticker on a parcel
SchemaA rulebook describing what a valid message looks likeA form with required fields

AArchitecture and Components

See how publishers, topics, subscriptions and subscribers connect.

The central design is simple and elegant. Publishers send messages to a topic. The topic does not deliver messages directly to programs. Instead, you attach one or more subscriptions to the topic. Each subscription receives its own full copy of every message published to the topic. Subscribers then read from their subscription. Because each subscription is independent, one slow subscriber does not hold up the others, and a new subscriber can be added without changing any publisher.

flowchart LR
  P1["Web Application Publisher"] --> T["Topic - Orders"]
  P2["Mobile Backend Publisher"] --> T
  P3["Cloud Service Publisher"] --> T
  T --> S1["Subscription - Billing"]
  T --> S2["Subscription - Shipping"]
  T --> S3["Subscription - Analytics"]
  T --> S4["Subscription - Archive"]
  S1 -->|"Pull"| C1["Billing Service"]
  S2 -->|"Push to HTTPS endpoint"| C2["Shipping Service"]
  S3 -->|"BigQuery subscription"| C3["BigQuery Table"]
  S4 -->|"Cloud Storage subscription"| C4["Cloud Storage Files"]
    
Figure 1: One topic with many independent subscriptions, each delivering in a different style.

Walking through the picture

Three different publishers send “order” messages to one topic. The topic has four subscriptions. The billing team pulls messages at its own pace. The shipping service receives them pushed to its web address. The analytics team has a subscription that writes messages straight into a BigQuery table, and the archive subscription writes them to files in Cloud Storage. Each subscription has its own progress, so billing can be a thousand messages behind while shipping is fully up to date.

The main components

  • Topics: named channels that receive published messages.
  • Subscriptions: independent delivery queues attached to a topic, each with its own settings such as ack deadline, retry policy, filter and dead-letter rule.
  • The Pub/Sub service: Google’s managed system that stores messages durably and tracks which ones each subscription has delivered and acknowledged.
  • Client libraries and APIs: tools in many programming languages that make publishing and receiving easy, including batching and flow control.
  • Schemas: optional rulebooks attached to topics to check messages.
  • Snapshots and seek: features to replay old messages.
Everyday Analogy

A magazine publisher prints one issue (the topic). Each subscriber gets their own copy delivered in their own way: by post, by courier or as a digital download. Whether one reader is slow to open theirs makes no difference to anyone else.

i
Good to Know

If several worker programs read from the same subscription, they share its messages, so each message goes to only one of the workers. This is how you scale up processing. If you want every program to receive every message, give each program its own subscription.

HHow It Works Inside: Publish, Store, Deliver, Acknowledge

Follow a message through its whole life inside the service.

sequenceDiagram
  participant Pub as Publisher
  participant PS as Pub Sub Service
  participant Sub as Subscriber
  Pub->>PS: Publish message to topic
  PS->>PS: Store message durably in several places
  PS-->>Pub: Confirm with message ID
  PS->>Sub: Deliver message from subscription
  Sub->>Sub: Process the message
  Sub->>PS: Acknowledge the message
  PS->>PS: Mark message as done for this subscription
    
Figure 2: A message is confirmed to the publisher after it is stored, and removed from a subscription after it is acknowledged.

Step 1: Publish

The publisher sends one or more messages to a topic. Client libraries usually batch messages, which means they collect several small messages and send them together. Batching is more efficient, but waiting to fill a batch adds a little delay, so libraries let you tune the size and waiting time.

Step 2: Store

Pub/Sub writes the message to durable storage and keeps copies in more than one location within the region before it tells the publisher “success”. This is why a successful publish means the message will not be lost because one machine fails.

Step 3: Fan out to subscriptions

Each subscription attached to the topic now has the new message in its own backlog. From here on, each subscription tracks its own progress independently.

Step 4: Deliver

Messages are delivered to subscribers according to the subscription type. Pull subscribers ask for messages. Push subscriptions send messages to a web address. Export subscriptions write messages into BigQuery or Cloud Storage.

Step 5: Acknowledge or retry

Once a subscriber has finished its work, it acknowledges the message, and Pub/Sub stops delivering it for that subscription. If the ack deadline passes without an acknowledgment, or the subscriber says it failed, Pub/Sub delivers the message again. This is the heart of reliability: a message is never considered done until someone says so.

The “at-least-once” idea

Because Pub/Sub would rather deliver a message twice than lose it, its standard promise is at-least-once delivery. In rare cases, such as when an acknowledgment is lost on the way back, a message may be delivered more than once. Your subscribers should therefore be written so that repeated processing of the same message does not cause harm. That property is called being idempotent.

Everyday Analogy

A courier leaves a parcel and asks for a signature. If no signature comes back, the courier tries again later. Occasionally the signature was given but the paper got lost, so the courier delivers a second time. A careful receiver notices “I already have this parcel” and does not pay twice.

DData Flow and Message Lifecycle

A message is born, waits, is processed and finally leaves. Here is the full story.

1

Created by the publisher

An application builds a message with a body and optional attributes, then sends it to a topic.

2

Validated and stored

If the topic has a schema, the message is checked. Then it is written durably and the publisher receives a message ID.

3

Copied into subscription backlogs

Every subscription whose filter accepts the message receives it into its own backlog.

4

Delivered

The message goes to a subscriber, by pull, push or export. The ack deadline timer starts.

5

Processed

The subscriber does its work. For long jobs it can ask to extend the deadline so the message is not resent too early.

6

Acknowledged or redelivered

A successful acknowledgment ends the message’s journey in that subscription. Failure or timeout leads to redelivery.

7

Retained, replayed or dead-lettered

If retention is turned on, acknowledged messages can be kept for replay. Messages that keep failing can be moved to a dead-letter topic.

When messages expire

An unacknowledged message does not stay forever. Each subscription has a message retention duration, which is how long Pub/Sub keeps messages that have not been acknowledged. The default is about a week, and it can be extended up to a documented maximum. If a subscriber is down longer than the retention time, the oldest unprocessed messages can be lost, so size this setting with outages in mind.

!
Watch Out

A subscription only receives messages published after it was created. If you create a subscription late, it will not see earlier messages unless the topic itself retains them and you replay them. Create subscriptions before you start publishing important data.

SSubscription Types: Pull, Push and Export

Choose how messages reach your application.

Pull subscriptions

With pull, your program asks Pub/Sub for messages and receives them in return. The most efficient way is streaming pull, where your program keeps a long-lived connection open and Pub/Sub streams messages over it as they arrive. Pull gives you strong control: you decide how fast to take messages (this is called flow control), you can run several workers on one subscription, and you can place workers anywhere they can reach Google’s services. Pull is a good default for heavy, steady processing.

Push subscriptions

With push, Pub/Sub sends each message as a web request to an HTTPS address that you provide. Your endpoint replies with a success code to acknowledge. Push suits serverless systems, such as Cloud Run services, where you do not want to keep a connection open and where the platform scales with incoming requests. Push endpoints can be protected by requiring Pub/Sub to attach an identity token that your endpoint verifies.

BigQuery subscriptions

A BigQuery subscription writes messages directly into a BigQuery table without any code of your own. It is a very simple way to land streaming events into a data warehouse for analysis, particularly when message formats match the table.

Cloud Storage subscriptions

A Cloud Storage subscription writes messages into files in a storage bucket, in batches by time or size. It is handy for archives, backups and later batch processing.

flowchart TD
  Start["What Should Happen to Each Message?"] --> Q1{"Need custom processing code?"}
  Q1 -->|"No - just store for analytics"| Q2{"Where should data land?"}
  Q2 -->|"Queryable tables"| BQ["Use a BigQuery Subscription"]
  Q2 -->|"Files for archive"| CS["Use a Cloud Storage Subscription"]
  Q1 -->|"Yes"| Q3{"Does your service have a public or private HTTPS endpoint?"}
  Q3 -->|"Yes and traffic suits request-based scaling"| Push["Use a Push Subscription"]
  Q3 -->|"No or need heavy steady throughput"| Pull["Use a Pull Subscription with Streaming Pull"]
    
Figure 3: A simple way to choose a subscription type.

Comparing the types

TypeWho starts the delivery?Best forMain caution
Pull (streaming)Your subscriberHigh volume, steady workers, flow controlYou manage the workers and connections
PushPub/SubServerless endpoints, simple webhooksEndpoint must respond quickly and handle bursts
BigQueryPub/Sub writes to a tableStreaming events into analytics with no codeMessage format must fit the table design
Cloud StoragePub/Sub writes filesArchives and batch pipelinesFiles are written in batches, not instantly
Everyday Analogy

Pull is like going to the post office to collect your mail whenever you have time. Push is like the postman ringing your doorbell. The BigQuery and Storage styles are like a mail service that files every letter straight into your cabinet while you are away.

DDelivery Guarantees, Ordering and Idempotency

The promises Pub/Sub makes, and how to build safely on top of them.

At-least-once delivery

By default, every message is delivered to each subscription at least once. Duplicates are possible, though uncommon. The safe mindset is: “Assume any message may arrive twice.”

Exactly-once delivery

Pub/Sub also offers an exactly-once delivery option for pull subscriptions. When enabled, once a message has been successfully acknowledged, it will not be redelivered, and acknowledgment results can be confirmed back to the subscriber. This reduces duplicates, but it has conditions, such as applying within one region, and it can add some delay. Even then, your overall system might still process an action twice if your own code retries elsewhere, so end-to-end care is still needed. Check current documentation for the exact conditions.

Message ordering

By default, Pub/Sub does not promise that messages arrive in the order they were published, because it spreads work across many machines for speed. If order matters, you can attach an ordering key to messages, such as a customer ID. Messages with the same ordering key, published to the same region, are delivered in order to subscribers who have ordering enabled. Messages with different keys can still flow in parallel. Ordering is useful for things like “account created” before “account updated”, but it can limit how fast a single key can be processed and has special behavior when failures happen.

Making your code idempotent

An action is idempotent if doing it twice has the same effect as doing it once. Here are ways to achieve it:

  • Use unique IDs: store the ID of each processed message or business event, and skip repeats.
  • Prefer “set” over “add”: “set balance to 50” is safe to repeat. “Add 10 to balance” is not.
  • Use database features: unique constraints or “insert if not present” operations stop duplicates.
  • Make external calls safe: pass an idempotency key to payment or email services so they ignore a repeated request.
Everyday Analogy

A bank sees two copies of the same cheque. A good clerk notes the cheque number and refuses to pay twice. The cheque number is the idempotency key. Ordering keys are like keeping all the pages of one customer’s file in one folder so they are read in sequence, while different customers’ folders can be handled by different clerks at the same time.

i
Tip

Do not turn on ordering or exactly-once delivery “just in case”. Each adds constraints. First ask whether your processing can simply be idempotent and order-tolerant, which is the most scalable design.

HHandling Failure: Deadlines, Retries and Dead Letters

Things go wrong in real systems. Pub/Sub gives you tools to handle that calmly.

The ack deadline

When a message is delivered, a timer starts. If your subscriber does not acknowledge before the ack deadline, Pub/Sub assumes the delivery failed and sends it again. The deadline can be set per subscription, within documented limits, and well-behaved client libraries automatically extend the deadline while your code is still working. Choose a deadline that matches your typical processing time with some margin.

Negative acknowledgment

If your subscriber knows it cannot process a message right now, it can send a negative acknowledgment (often called a nack). This tells Pub/Sub to redeliver sooner, instead of waiting for the deadline.

Retry policy

By default, a failed message may be redelivered quickly. For a struggling downstream system, instant retries can make things worse. A retry policy with exponential backoff makes Pub/Sub wait longer between each attempt, such as a few seconds, then more, up to a maximum, giving the downstream system time to recover.

Dead-letter topics

Some messages can never succeed, for example because they contain bad data that crashes your code. These are called poison messages. If they are retried forever, they waste effort and may hide real problems. A dead-letter topic collects messages that have failed a set number of delivery attempts, within documented limits. You can then inspect them, fix the bug or the data, and replay them later.

flowchart TD
  M["Message Delivered to Subscriber"] --> Work{"Processing Succeeds?"}
  Work -->|"Yes"| Ack["Acknowledge - Message Done"]
  Work -->|"No or Timeout"| Wait["Wait According to Retry Policy"]
  Wait --> Count{"Max Delivery Attempts Reached?"}
  Count -->|"No"| M
  Count -->|"Yes"| DLT["Move to Dead-Letter Topic"]
  DLT --> Review["Engineers Inspect and Fix"]
  Review --> Replay["Republish After the Fix"]
    
Figure 4: Failed messages are retried with backoff, and persistent failures are parked in a dead-letter topic.

Setting up dead-letter handling safely

  • Give the dead-letter topic its own subscription, so parked messages are actually kept and visible.
  • Grant Pub/Sub the permission it needs to publish to the dead-letter topic and to acknowledge from the original subscription.
  • Alert on the dead-letter backlog. A growing pile means something is broken.
  • Choose the attempt count with care. Too low sends temporary failures to the dead-letter topic. Too high delays discovery of real problems.
Everyday Analogy

A post office tries to deliver a parcel a few times, waiting longer between visits. If nobody ever answers, the parcel goes to a “undeliverable items” shelf where staff can look at the address, fix it and send it again, instead of the postman carrying it around forever.

!
Watch Out

If a subscriber acknowledges a message before the work is finished, and then crashes, the message is lost. Acknowledge only after the work is safely completed, and rely on idempotency to handle the repeats.

FFiltering, Schemas and Message Design

Good messages are small, clear and predictable.

Subscription filters

A filter is a rule on a subscription that lets only matching messages in, based on their attributes. Suppose a topic carries all orders, with an attribute “region”. The Europe warehouse subscription can use a filter so it only receives messages where region is Europe. This saves processing and money, since filtered-out messages are not delivered to that subscription. Filters only look at attributes, so put the fields you may want to filter on into attributes.

Schemas

A schema describes the exact structure of a message, such as “an order has an ID (text), an amount (number) and a time”. Pub/Sub supports common schema formats such as Avro and Protocol Buffers. When a schema is attached to a topic, Pub/Sub rejects messages that do not follow it. This protects subscribers from surprises, because every message that arrives is known to be shaped correctly. Schemas can evolve over time with revisions, but changes should be made carefully so older and newer programs keep understanding each other.

Designing a good message

  • Keep it small. Messages can be quite large within documented limits, but small messages are faster, cheaper and easier to retry.
  • Describe an event, not a command. “OrderPlaced” is better than “SendEmailNow”. Events let many consumers decide what to do.
  • Include a unique ID and timestamp. They help with duplicates and troubleshooting.
  • Carry references for large data. Instead of putting a big video in a message, store it in Cloud Storage and send its location.
  • Plan for change. Add new fields instead of renaming old ones, and keep a version number.
  • Avoid secrets and unneeded personal data. Messages may be stored, logged and copied to several places.
Everyday Analogy

A parcel label has a standard layout: name, address, weight. Because everyone agrees on the layout (schema), any courier can read it. Stickers on the parcel such as “Fragile” or “Express” (attributes) let sorting staff route it without opening the box.

i
Good to Know

Pub/Sub also lets you add simple transformations to messages as they pass through in some configurations, and the list of such features grows over time. Check the current documentation for the latest options before building your own conversion step.

RRetention, Replay, Snapshots and Seek

Sometimes you need to go back in time and process messages again.

Normally, once a message is acknowledged on a subscription, it is gone from that subscription. But mistakes happen. A bug might have processed a day of messages wrongly. A new analytics system might want last week’s events. Pub/Sub offers tools for such cases.

Subscription retention of acknowledged messages

You can tell a subscription to retain acknowledged messages for a period of time. They stay available for replay even though they were already processed.

Topic retention

A topic can also keep messages for a chosen period after they are published, up to a documented maximum. This lets new subscriptions, created later, start from older messages, and lets existing ones replay. It acts like a short history of the channel.

Snapshots

A snapshot records the acknowledgment state of a subscription at a moment in time. It is like a bookmark: “everything before this point was handled”. Before a risky deployment, you can create a snapshot, and if something goes wrong, you can rewind to it.

Seek

The seek operation moves a subscription to a snapshot or to a timestamp. After a seek, messages after that point are delivered again. This is a powerful repair tool, but use it carefully, because it causes reprocessing, and your processing code must be ready for repeats.

Everyday Analogy

A video streaming app remembers where you stopped watching. If you want to see the last ten minutes again, you drag the progress bar back. Seek is that progress bar for your message stream, and a snapshot is a saved “continue from here” marker.

!
Watch Out

Retention has a price, since stored messages are billed. Keep retention only as long as you truly need replay ability. Also note that replaying into systems that are not idempotent can cause double charges or double emails.

PPerformance and Scalability

How Pub/Sub grows with you, and what you still need to tune.

Scaling you do not manage

With a typical message system, you must choose how many machines or partitions to have, and rebalance them as traffic grows. Pub/Sub hides this. It automatically scales its internal capacity to handle more publishers, more subscribers and higher message rates. There are documented quotas, such as limits on throughput per region and on request sizes, but they are large, and many can be raised by request.

Scaling publishers

  • Batch messages so that fewer, larger requests are sent.
  • Use many publisher instances and keep client objects alive instead of creating new ones for every message.
  • Publish to a nearby region using regional endpoints, to cut delay and meet data location rules.

Scaling subscribers

  • Add more workers to the same subscription. They share the messages automatically.
  • Autoscale on backlog. Watch the number and age of unacknowledged messages, and add workers when they grow.
  • Use flow control so each worker takes only as many messages as it can handle at once.
  • Keep processing fast. Do slow work asynchronously and extend ack deadlines where needed.

Latency

Pub/Sub is designed for good throughput and reasonably low delay, but it is not an instant function call. End-to-end latency is usually measured in milliseconds to a few hundred milliseconds under normal conditions, and depends on your batching, region choices and subscriber speed. If you need a response from another system immediately, to continue the user’s request, use a direct call instead and use Pub/Sub for follow-up work.

Hot keys and ordering

When ordering is used, all messages with the same key must be handled in sequence. If one key receives a huge share of traffic, such as a single very popular customer, that key becomes a bottleneck. Choose ordering keys that spread load evenly.

Everyday Analogy

A post office that magically adds sorting tables whenever more mail arrives is Pub/Sub’s side. Your side is the number of postmen who deliver. If mail piles up, you hire more postmen, and they share the pile fairly.

i
Tip

The most important health number for a subscription is the age of the oldest unacknowledged message. If it keeps growing, your workers are not keeping up, no matter how healthy everything else looks.

AAvailability, Durability and Data Location

How Pub/Sub keeps messages safe, and how you control where they live.

Durability

Pub/Sub stores each message in multiple places within the region before confirming the publish. If a machine or even a whole zone has trouble, the message remains available. Because the service is built on Google’s large infrastructure, you do not have to configure replication yourself.

Availability

Pub/Sub is a global service with regional storage and endpoints. Google publishes an availability commitment for it in its service level agreement, which you should check for exact terms. Clients automatically retry on temporary errors, which smooths over short problems.

Where messages are stored

By default, Pub/Sub chooses storage locations near the publisher. If you have rules about where data may live, such as keeping it inside one country or region, you can set a message storage policy on a topic that lists the allowed regions. Pub/Sub then stores messages only in those places. Publishers and subscribers can use regional endpoints to keep their traffic in the chosen area.

Designing for regional problems

A single region is a single point of risk. For very important systems, teams sometimes publish to topics in more than one region, or maintain a plan to switch publishers and subscribers to another region if the first has trouble. This adds complexity, since messages may need to be de-duplicated, so it should be a deliberate choice based on business need.

Everyday Analogy

Important papers are kept in a fireproof cabinet and copied to a second room in the building. The company can also decide that no copies may leave the country, and tell the archive team to use only offices in that country.

i
Good to Know

Pub/Sub Lite, an older low-cost zonal sibling of Pub/Sub, was announced for retirement. If you see it in older material, confirm its current status in Google’s documentation and plan to use standard Pub/Sub or another suitable service for new work.

SSecurity in Pub/Sub

Messages often carry valuable data. Protect the whole path.

Who may do what (IAM)

Access is controlled by Google Cloud Identity and Access Management (IAM). There are roles for publishing, for subscribing, for viewing and for administering. A publishing application should receive only the publisher role on its topic. A processing application should receive only the subscriber role on its subscription. This is the principle of least privilege: give only the permissions actually needed. Use a separate service account for each application, so a problem in one does not give access to everything.

Encryption

  • In transit: connections to Pub/Sub use encryption.
  • At rest: messages are encrypted when stored, by default with keys managed by Google.
  • Customer-managed keys: if your rules require, you can use your own keys through Cloud Key Management Service, which lets you control and revoke them.

Securing push endpoints

For push subscriptions, your endpoint must be reachable over HTTPS. To prevent strangers from posting fake messages to it, enable authentication so that Pub/Sub attaches a signed identity token, and have your service verify it. Never rely on a secret web address alone.

Network boundaries

For sensitive environments, Google Cloud provides perimeter controls such as VPC Service Controls, which can restrict where Pub/Sub data may be accessed from and reduce the risk of data leaving a protected boundary. Private connectivity options let workloads reach Google services without public internet exposure.

Auditing

Cloud Audit Logs record administrative actions, such as creating topics or changing permissions, and can record data access if enabled. These logs are valuable for investigations and compliance.

Protecting message content

  • Do not put passwords, keys or unnecessary personal data in messages.
  • If sensitive fields must travel, consider encrypting them at the application level too.
  • Remember that dead-letter topics and retained messages hold copies, so protect those too.
  • Validate incoming messages in subscribers. Never trust content blindly just because it came from your own topic.
Everyday Analogy

A mailroom in a company has rules: only authorized staff may drop off mail, only the right department may collect from its own pigeonhole, parcels are sealed, and a logbook records who did what. Pub/Sub’s IAM, encryption and audit logs correspond to these rules.

MMonitoring, Logging and Metrics

You cannot fix what you cannot see. Know your dashboards before trouble starts.

Pub/Sub reports metrics to Cloud Monitoring automatically. Metrics are numbers over time, logs are records of events, and alerts notify people when numbers cross a limit.

MetricWhy it mattersA warning sign
Oldest unacknowledged message ageShows how far behind processing isKeeps growing over time
Number of unacknowledged messagesShows the size of the backlogRises steadily and never drains
Publish request count and errorsShows publisher healthRising error rate
Delivery and ack ratesShows whether subscribers keep upDelivery high but acks low
Expired ack deadlinesShows messages being resent because processing is too slowFrequent expirations
Dead-letter backlogShows poison or broken messagesAny sustained growth
Push endpoint response codesShows whether the target is failingMany error responses
Retained storage bytesDrives costUnexpected growth

Practical alerts to set up first

  • Oldest unacknowledged message age above the amount of delay your business can tolerate.
  • Any messages in the dead-letter subscription.
  • Publish error rate above normal.
  • Push endpoint failure rate above normal.

Tracing messages end to end

When one user action flows through many services via Pub/Sub, finding where time was lost can be hard. A good habit is to include a trace or correlation ID in message attributes, and log it in each service. Then one search reveals the whole journey.

Everyday Analogy

A mailroom manager watches how many letters are waiting and how old the oldest letter is. If the oldest letter is three days old, something is badly wrong, even if the room looks tidy.

CCost: Understanding the Bill

Pub/Sub bills by data volume. Know what counts and how to control it.

Pub/Sub pricing is usage-based and set by Google, with a monthly free allowance at the time of writing. Exact prices change and vary by use, so always use the official pricing page and calculator. The key is to understand which activities add to the bill.

Input

Data Published

The amount of message data sent into topics, usually measured in bytes with small minimums per request.

Output

Data Delivered

The amount of data delivered to each subscription. If you have four subscriptions, one message is delivered four times.

Storage

Retained Messages and Snapshots

Messages kept for replay, topic retention and snapshot storage are billed for the space they use over time.

Network

Data Transfer

Traffic that leaves a region or goes outside Google Cloud can be charged. Keep publishers and subscribers close together.

Ways to keep the bill sensible

  • Keep messages lean. Send IDs and references, not huge documents.
  • Batch publishing. It improves efficiency and reduces overhead per message.
  • Use filters. A filtered-out message is not delivered to that subscription, saving delivery cost.
  • Delete unused subscriptions. Forgotten subscriptions keep collecting backlog and cost money until the retention period ends.
  • Limit retention. Keep replay windows only as long as you truly need.
  • Avoid retry storms. Use backoff so failing messages are not delivered thousands of times.
  • Label resources. Make it easy to see which team spends what.
Everyday Analogy

A courier charges for the weight of each parcel and for each delivery address. Sending one heavy parcel to five addresses costs more than five light notes. Sending a light note with a pointer to a document stored elsewhere is far cheaper.

!
Watch Out

A subscription that nobody reads still accumulates messages up to its retention limit. An abandoned test subscription can quietly store and bill for a week of traffic. Clean up tests promptly.

IIntegrations and Common Architectures

Pub/Sub is the glue of many Google Cloud designs. Here are the most common pictures.

Architecture 1: Event-driven applications

A service publishes events such as “UserSignedUp”. Several other services, perhaps running on Cloud Run, Cloud Run functions or Google Kubernetes Engine, subscribe and react: one sends a welcome email, another creates a profile, another updates analytics. Adding a new reaction means adding a new subscription, with no change to the publisher.

Architecture 2: Streaming analytics

Events from apps, devices and logs flow into a topic. A Dataflow job reads from a subscription, cleans and groups the data, and writes results to BigQuery for dashboards. Dataflow is Google’s managed service for processing streams and batches of data, and it works closely with Pub/Sub.

Architecture 3: Load leveling for a slow system

A front end accepts many requests quickly and publishes jobs to a topic. A group of workers processes them at a steady speed. During a rush, the backlog grows instead of the system collapsing, and later it drains. Users see quick acknowledgments such as “your report is being prepared”.

Architecture 4: Fan-out to many consumers

A single “PaymentCompleted” event reaches billing, loyalty points, receipts and fraud analysis through separate subscriptions. Each team owns its own subscription and failure handling.

Architecture 5: Change data and log pipelines

Changes in databases or application logs are published to topics and flow to search indexes, caches or archives, keeping several systems in sync without tight links.

Architecture 6: Cloud events and automation

Many Google Cloud services can emit events, for example a file being uploaded or a resource changing. Pub/Sub is often the transport. Services such as Eventarc build on messaging to route such events to Cloud Run and other targets, so you can often react to cloud events without writing the plumbing yourself.

Pairing with scheduled and queued work

Cloud Scheduler can publish a message to a topic on a timetable, which is a simple way to trigger regular jobs. For work that must be delivered to one specific target with controlled rates and scheduled delivery times, Cloud Tasks may be a better fit. The comparison table in the next chapter helps with the choice.

Everyday Analogy

Pub/Sub is like the pipework of a building. Taps, showers and washing machines (your services) are very different, but they all connect to the same water supply without needing to know about each other.

AAdvantages, Disadvantages and Trade-offs

No tool is perfect. A good architect weighs both sides before choosing.

Advantages

  • Fully managed and serverless, with nothing to size, patch or rebalance
  • Scales automatically with traffic spikes
  • Durable storage with replication handled for you
  • Fan-out through independent subscriptions
  • Flexible delivery: pull, push, BigQuery and Cloud Storage
  • Dead-letter topics, retry policies, filters and schemas built in
  • Replay through retention, snapshots and seek
  • Deep integration with Dataflow, Cloud Run, BigQuery and IAM
  • Optional exactly-once delivery and message ordering when needed

Disadvantages

  • Default at-least-once delivery means duplicates are possible, so consumers must be idempotent
  • No global ordering. Ordering exists only per ordering key
  • Not a request and response tool, so unsuitable for immediate answers
  • Less low-level control than self-run log systems, such as direct partition control
  • Costs scale with volume and with the number of subscriptions
  • Tied to Google Cloud for the managed service
  • Debugging asynchronous flows takes extra care and good tracing
  • Replay and retention windows are limited to documented maximums

How it compares with its neighbors

QuestionPub/SubSelf-run or managed Apache KafkaCloud Tasks
Main ideaTopic and subscription messaging with fan-outPartitioned, replayable log with consumer groupsQueue of tasks sent to one specific target
Capacity managementNone, scales automaticallyYou plan brokers and partitions, even with managed offeringsNone, but with queue-level rate settings
Fan-out to many consumersNatural, through subscriptionsNatural, through consumer groupsNot its purpose
OrderingPer ordering keyPer partitionNot guaranteed in general
Control of delivery rate and timing to one targetLimited, mainly flow control and retry policyConsumer controls paceStrong, including scheduling and rate limits
Best fitEvent distribution, streaming ingest, decouplingHeavy log-style streaming where Kafka tools and protocols are requiredControlled background jobs to a known handler
i
Good to Know

Choose Kafka mainly when you need its protocol, its ecosystem or its exact log model, for example for existing applications built for Kafka. Choose Pub/Sub when you want the simplest managed path inside Google Cloud.

The main trade-offs, in plain words

  • Simplicity versus control: you give up low-level tuning to avoid running infrastructure.
  • Decoupling versus visibility: services are free from each other, but flows are harder to follow without good tracing.
  • Reliability versus duplicates: never losing a message means occasionally seeing one twice.
  • Order versus speed: strict order for a key limits parallel processing for that key.

DDesign Patterns and Anti-patterns

A pattern is a proven way to solve a common problem. An anti-pattern is a tempting mistake that causes pain later.

Helpful patterns

Pattern

Event Notification

Publish small events that say what happened, and let interested services fetch details if needed.

Pattern

Competing Consumers

Run many identical workers on one subscription so they share the load, and scale them with the backlog.

Pattern

Idempotent Receiver

Record processed message IDs or use safe operations so repeats do no harm.

Pattern

Dead-Letter Queue

Park poison messages for inspection, and alert on the pile.

Pattern

Claim Check

Store large payloads in Cloud Storage and send only a reference in the message.

Pattern

Outbox

Write the business change and the outgoing event into the same database transaction, then publish from that table. This avoids saving data but failing to announce it, or the reverse.

Anti-patterns to avoid

ANTI-PATTERN 01 Avoid
What people do

They assume each message arrives exactly once and in order, and write code that breaks when a duplicate or a late message appears.

Why it hurts

Double charges, double emails and corrupted counts appear in production, usually at the worst time.

Better approach

Design consumers to be idempotent and tolerant of order changes. Use ordering keys or exactly-once delivery only where truly needed.

ANTI-PATTERN 02 Avoid
What people do

They acknowledge a message first and do the work afterwards.

Why it hurts

If the program crashes in between, the message is gone and the work is never done.

Better approach

Acknowledge only after the work is safely saved. Use idempotency to handle repeats.

ANTI-PATTERN 03 Avoid
What people do

They use Pub/Sub as a request and response channel, publishing a request and waiting for a reply message in the same user interaction.

Why it hurts

It adds delay and complexity, and loses the simplicity of a direct call.

Better approach

Use a direct call for immediate answers. Use messages for follow-up work and notifications.

ANTI-PATTERN 04 Avoid
What people do

They retry forever with no dead-letter topic, so one bad message loops endlessly.

Why it hurts

Workers waste effort, backlog metrics become confusing and real problems stay hidden.

Better approach

Set a dead-letter topic with a sensible attempt limit, use backoff and alert on the dead-letter backlog.

ANTI-PATTERN 05 Avoid
What people do

They put huge payloads or secrets inside messages, and share one topic for unrelated event types with no schema.

Why it hurts

Costs and delay rise, sensitive data spreads to many copies and consumers break when formats change without warning.

Better approach

Send references for big data, keep secrets out, use clear topics and schemas, and version your messages.

BBest Practices and Common Mistakes

A checklist you can follow from the first day.

Best practices

  1. Create subscriptions before publishing. New subscriptions do not see earlier messages by default.
  2. Design for duplicates. Use unique IDs and idempotent operations.
  3. Acknowledge after success. Never before the work is safely done.
  4. Always configure a dead-letter topic and a retry policy. Alert on the dead-letter backlog.
  5. Set the ack deadline to fit your processing time. Let client libraries extend it for long jobs.
  6. Use flow control. Prevent workers from taking more than they can handle.
  7. Autoscale workers on backlog and message age. These are the truest signals of falling behind.
  8. Use schemas and versioning. Protect consumers from bad or surprising messages.
  9. Apply least privilege. Separate service accounts and narrow roles for each application.
  10. Use filters and small messages. They save money and effort.
  11. Add correlation IDs. Make flows traceable across services.
  12. Clean up and label resources. Delete unused subscriptions and track ownership.
  13. Check the latest documentation. Limits, features and defaults change over time.

Common mistakes

1

Too short an ack deadline

Messages are redelivered while the first attempt is still running, creating duplicates and extra load.

2

One subscription shared by different teams

Teams split the messages instead of each getting a full copy. Each independent consumer needs its own subscription.

3

Forgetting dead-letter permissions

A dead-letter topic is configured but Pub/Sub lacks permission to use it, so failing messages keep looping instead of moving.

4

Push endpoint that is too slow or not authenticated

Slow replies cause retries and pile-ups. Missing authentication lets outsiders send fake messages.

5

Replaying without a plan

A seek to the past triggers reprocessing of thousands of messages into systems that cannot handle repeats.

6

Ignoring the oldest message age

Teams watch CPU and memory but not backlog age, and discover a day of delay only when customers complain.

RReal-World Usage Scenarios

Four illustrative stories show where Pub/Sub fits. The companies below are imaginary examples to teach the ideas.

Scenario 1: A food delivery app during dinner rush

An app receives a huge wave of orders between seven and nine every evening. Each order is published to a topic. Separate subscriptions feed the restaurant tablets, the driver assignment service, the payment service and the analytics pipeline. When the driver assignment service slows down, its backlog grows but the other systems carry on. After the rush, extra workers drain the backlog, and nobody lost an order.

Scenario 2: A smart-home device company

Millions of devices send small status messages. A gateway publishes them to Pub/Sub. A Dataflow job cleans and groups the data, and a BigQuery subscription stores a copy of raw events for later investigation. An alerting service uses a filtered subscription that only receives messages with a “fault” attribute, so it processes a tiny part of the traffic.

Scenario 3: A bank sending account events

A bank publishes “TransactionPosted” events with the account number as an ordering key, so events for one account arrive in order while different accounts flow in parallel. The fraud team, notifications team and statements team each have their own subscription and dead-letter topic. Consumers record transaction IDs, so repeated deliveries never change a balance twice.

Scenario 4: A media company processing uploads

When a video is uploaded to Cloud Storage, a notification message is published. Worker services pull messages, create smaller versions and thumbnails, and publish “VideoReady” events when done. Because the heavy work happens behind the scenes, the upload page responds instantly, and the team can add more workers on busy days.

The best systems do not wait for each other. They leave good notes and trust the notice board.

When Pub/Sub is a strong choice

  • You want services to be independent and able to scale on their own.
  • Traffic is bursty and you need a buffer.
  • Many teams or systems need the same events.
  • You want to stream data into analytics with little plumbing.
  • You prefer a fully managed service with no cluster to run.

When to think twice

  • You need an immediate response to continue a user request, so a direct call is better.
  • You need strict global ordering of all messages.
  • You depend on Kafka-specific tools and protocols.
  • You need precise scheduling and rate control for calls to one target, where Cloud Tasks may suit better.

FFrequently Asked Questions

Quick answers to questions that beginners ask most often.

Q1What is the difference between a topic and a subscription?
A topic is where publishers send messages. A subscription is a separate delivery point attached to a topic, from which a subscriber receives messages. Each subscription gets its own copy of every message.
Q2Can the same message be delivered twice?
Yes. The default promise is at-least-once delivery, so duplicates are possible, though uncommon. Exactly-once delivery is available as an option for pull subscriptions under certain conditions, but you should still make your processing safe to repeat.
Q3Are messages delivered in order?
Not by default. If you need order for related messages, use an ordering key and enable ordering. Messages with the same key are then delivered in order.
Q4Should I use push or pull?
Pull is a good default for high-volume steady workers and gives flow control. Push suits serverless HTTPS endpoints. If you only want to store data, BigQuery or Cloud Storage subscriptions need no code at all.
Q5What happens if my subscriber is down?
Messages wait in the subscription backlog until the subscriber returns, up to the retention period. After that, unacknowledged messages may expire, so choose retention with outages in mind.
Q6What is a dead-letter topic?
It is a topic where messages are sent after failing a set number of delivery attempts. It keeps poison messages from looping forever and lets you examine and fix them later.
Q7Can I replay old messages?
Yes, within limits. You can retain acknowledged messages on a subscription, use topic retention, and use snapshots or timestamps with the seek operation to move back in time.
Q8Can I send large files through Pub/Sub?
Messages have a documented size limit, and large messages are not efficient. A better approach is to store the file in Cloud Storage and send its location in the message.
Q9Is Pub/Sub the same as a queue?
It can act like one when several workers share a single subscription. It also supports fan-out to many subscriptions, which a simple queue does not, so it is more flexible than a basic queue.
Q10How do I keep data in one country?
Set a message storage policy on the topic listing the allowed regions, and use regional endpoints for your clients. Then check that all related services also follow your location rules.
Q11How do I know if my subscribers are keeping up?
Watch the oldest unacknowledged message age and the number of unacknowledged messages. If they keep growing, add workers or speed up processing.
Q12How is it different from Kafka?
Pub/Sub is serverless and needs no capacity planning, using topics and subscriptions. Kafka is a partitioned log with its own protocol and ecosystem, giving more low-level control but requiring more operations, even in managed forms.
Q13What is the easiest way to try it?
Create a topic and a pull subscription in a test project, publish a few messages with the console, then pull and acknowledge them. Next try leaving one unacknowledged to watch it come back. Delete the test resources afterwards.

SSummary and Key Takeaways

Remember These Points

  • What it is: Pub/Sub is Google Cloud’s fully managed, global messaging service. Publishers send messages to topics, and subscribers receive them through independent subscriptions.
  • Why it helps: it decouples services, absorbs traffic spikes, fans one event out to many consumers and streams data into analytics.
  • How delivery works: a message is stored durably, delivered, and kept until acknowledged. The default promise is at-least-once, so write idempotent consumers.
  • Choose the right style: pull for steady heavy workers, push for serverless endpoints, and BigQuery or Cloud Storage subscriptions for code-free storage.
  • Plan for failure: set sensible ack deadlines, retry with backoff, add a dead-letter topic and alert on its backlog.
  • Use special features with care: ordering keys, exactly-once delivery, filters, schemas and replay are powerful, but each adds rules, so use them only where needed.
  • Protect and watch: apply least-privilege IAM, encryption and push authentication, and monitor the oldest unacknowledged message age above all.
  • Mind the cost and the facts: costs follow data published and delivered, so keep messages small and clean up unused subscriptions, and always check Google’s latest documentation for current limits and features.