Google Cloud Tutorial · Storage, Databases and Analytics · Lesson 22 of 27

Pub/Sub

Asynchronous messaging with Pub/Sub: topics and subscriptions, push and pull, acknowledgements, retries, ordering and dead-letter topics.

Members can save this page, take notes and track progress. See membership · Sign in

Topics and subscriptions

Publishers send messages to a topic. Each subscription on the topic receives a copy of every message, so several services can react to the same event independently. Subscribers either pull messages or receive them by push to an HTTPS endpoint (for example a Cloud Run service).

gcloud pubsub topics create orders
gcloud pubsub subscriptions create orders-billing --topic=orders \
  --ack-deadline=30 --dead-letter-topic=orders-dead --max-delivery-attempts=5
gcloud pubsub topics publish orders --message='{"order_id": 42}'

Delivery

  • A subscriber must acknowledge each message before the ack deadline; otherwise Pub/Sub redelivers it.
  • Delivery is at least once (exactly-once delivery is available for pull subscriptions), so consumers must be idempotent.
  • Ordering keys keep messages with the same key in order.
  • After too many failed attempts, a dead-letter topic receives the message for inspection.
  • Messages are retained (7 days by default) so subscribers can catch up after downtime.
At-least-once delivery with an idempotent consumerTry it yourself
import random

random.seed(7)
handled, charged = set(), 0
messages = [{"id": i, "order_id": 100 + i} for i in range(5)]
queue = list(messages)
attempts = 0
while queue:
    msg = queue.pop(0)
    attempts += 1
    if msg["order_id"] not in handled:      # idempotent: charge each order once
        handled.add(msg["order_id"])
        charged += 1
    if random.random() < 0.3:               # the ack got lost: Pub/Sub redelivers
        queue.append(msg)
print(f"{len(messages)} messages, {attempts} deliveries, {charged} charges")

Output

5 messages, 8 deliveries, 5 charges

Test yourself

A subscriber doesn't acknowledge a message before the ack deadline. What happens?

  1. It's deleted
  2. Pub/Sub delivers it again
  3. The topic is paused
  4. It goes to BigQuery
Show answer

Answer: Pub/Sub delivers it again

Unacknowledged messages are redelivered, which is why consumers must be idempotent.

Last reviewed · By the ByteCamel team · How we write content

Was this page helpful?

Report a mistake