Skip to content
Visual explainer 3h 30m to learn 5 steps

Reliable Pub/Sub delivery, retries and dead letters

Trace a message from publish to acknowledgement, add a dead-letter topic and make the subscriber idempotent.

By Invicly Tech, , in Google Cloud Engineering and Services. About 8 minutes to read.

Topic 16 of 32

In short

Pub/Sub carries messages from publishers to subscribers. A subscriber must acknowledge each message; if it does not in time, Pub/Sub sends it again. That gives at-least-once delivery, so handlers must cope with duplicates, and a dead-letter topic catches messages that keep failing.

Think of it like this: Pub/Sub is a postal sorting office that keeps redelivering a parcel until someone signs for it, and sends it to a lost-parcel shelf after too many tries.

Explained simply

Pub/Sub lets one part of a system tell other parts that something happened, without waiting for them. A publisher sends a message to a topic. Each subscription attached to that topic gets its own copy, and a subscriber reads from it.

A subscriber has to say it finished with a message. This is called an acknowledgement, or ack. If no ack arrives before the deadline, Pub/Sub assumes something went wrong and sends the message again. Because of this, a message can arrive more than once.

That is why handlers should be idempotent. Idempotent means doing it twice gives the same result as doing it once. A simple way is to record each message ID and skip any you have already seen.

Some messages never succeed, perhaps because the data is bad. A dead-letter topic collects them after a set number of tries, so they stop blocking the queue and you can look at them later.

Press Play on a diagram to walk through it one step at a time.

SequenceOne message from publish to acknowledgement
Publisher
Pub/Sub
Subscriber
  1. 1Publish order-created
    Publisher to Pub/Sub: Publish order-created
  2. 2Message ID returned
    Pub/Sub to Publisher: Message ID returned
  3. 3Deliver message
    Pub/Sub to Subscriber: Deliver message
  4. 4Acknowledge after work is done
    Subscriber to Pub/Sub: Acknowledge after work is done
  5. 5No ack in time: redeliver
    Pub/Sub to Subscriber: No ack in time: redeliver
FlowFailure path with a dead-letter topic
  1. 1
    Delivery fails

    Handler errors or times out

  2. 2
    Retry with backoff

    Subscription retry policy

  3. 3
    Attempts reach the limit

    Default is 5

  4. 4
    Dead-letter topic

    Message parked for inspection

  5. 5
    Fix and replay

    Republish after the bug is fixed

ComparePull or push for an order consumer
Pull worker
  • Controls its own pace
  • Good for batches and long jobs
  • Extends the ack deadline itself
  • Needs a running process
Push to Cloud Run
  • No polling code
  • Scales with traffic
  • Must answer before the deadline
  • Verify the Pub/Sub token

In depth

Pull and push delivery

With pull, your subscriber asks Pub/Sub for messages and acks them. This suits workers that control their own pace, such as a batch job. With push, Pub/Sub sends each message as an HTTPS request to an endpoint, for example a Cloud Run service. A success response (2xx) counts as an ack.

For push, configure authentication so only Pub/Sub can call your endpoint: give the subscription a service account and make the service check the OIDC token. Never leave the endpoint open to the internet.

  • Pull: you control the pace
  • Push: Pub/Sub calls your HTTPS endpoint
  • Push needs an authenticated, allowed caller
  • A 2xx response acks a push message

Deadlines, retries and dead letters

The ack deadline defaults to 10 seconds and can be set from 10 to 600 seconds. Pull clients can extend it while they work. If the deadline passes, the message is redelivered.

The retry policy controls the wait after a failure: retry immediately, or use exponential backoff between a minimum and maximum delay. A dead-letter policy names a topic and a maximum number of delivery attempts, from 5 to 100. The Pub/Sub service account needs permission to publish to the dead-letter topic and to acknowledge on the subscription. Create a subscription on the dead-letter topic so parked messages are kept.

CycleThe redelivery loop
  1. 1
    Deliver message
  2. 2
    Handler works
  3. 3
    Ack or timeout
  4. 4
    Retry after backoff
  5. Back to step 1

Idempotency and ordering

Pub/Sub delivers at least once by default. Some subscriptions can enable exactly-once delivery for pull, within limits described in the docs, but your handler should still be safe to repeat because the work outside Pub/Sub can fail midway.

Use a natural idempotency key, such as the order ID plus the event type, and record it in the same database transaction as the side effect.

Ordering keys make Pub/Sub deliver messages with the same key in publish order. This needs ordering enabled on the subscription and a regional endpoint for publishing. A failed message can hold up later ones for the same key, so use ordering only where order matters.

Learn it in 5 short steps

About 40m each. Track them with a timer in your plan.

  1. 1
    Publish and subscribe with pull and push~40m
  2. 2
    Set acknowledgement deadlines and retries~40m
  3. 3
    Route failures to a dead-letter topic~40m
  4. 4
    Write an idempotent handler~40m
  5. 5
    Use ordering keys when order matters~40m

Key points

  • Pull subscribers ask for messages; push subscriptions send them to an HTTPS endpoint, such as Cloud Run, using an authenticated request.
  • The acknowledgement deadline defaults to 10 seconds and can be raised up to 600. Acknowledge only after the work succeeds.
  • A dead-letter topic needs a maximum delivery attempts value and IAM permissions for the Pub/Sub service account.
  • Delivery is at least once, so make the handler idempotent: processing the same message twice must give the same result.
  • Ordering keys keep messages with the same key in order, but they limit parallelism. Use them only when order truly matters.

Key terms

Tap a card to flip it. 0/6 known

Examples

python
def handle(message, db):
    order_id = message.attributes["order_id"]
    inserted = db.execute(
        "INSERT INTO processed (message_id) VALUES (%s) "
        "ON CONFLICT DO NOTHING",
        (message.message_id,),
    ).rowcount
    if inserted:
        ship_order(order_id)
    message.ack()  # ack only after the work succeeded

Idempotent handler: a unique message ID guards the side effect.

Run Pub/Sub locally with the emulator

Prerequisite: gcloud with the pubsub emulator component. No cloud project is billed. Evidence: the publish returns a message ID and the pull shows the message. The emulator does not copy every production behaviour, such as IAM and some delivery timing, so test those in a real project.

bash
gcloud beta emulators pubsub start --host-port=127.0.0.1:8085 &
$(gcloud beta emulators pubsub env-init)
export PUBSUB_PROJECT_ID=demo-project
python - <<'EOF'
from google.cloud import pubsub_v1
p = pubsub_v1.PublisherClient()
t = p.topic_path("demo-project", "orders")
p.create_topic(name=t)
print(p.publish(t, b"order-42").result())
EOF

Add a dead-letter topic

Prerequisite: a topic orders and a subscription orders-sub in a test project. Create a dead-letter topic with its own subscription, then update the subscription. Evidence: after five failed attempts a message appears on the dead-letter subscription. Cleanup: delete the test topics and subscriptions.

bash
gcloud pubsub topics create orders-dead
gcloud pubsub subscriptions create orders-dead-sub --topic=orders-dead
gcloud pubsub subscriptions update orders-sub \
  --dead-letter-topic=orders-dead \
  --max-delivery-attempts=5
# grant the Pub/Sub service account publish on orders-dead
# and subscriber on orders-sub (see the dead-letter docs)

Quick reference

  • Default delivery is at least once; expect duplicates.
  • Ack deadline: default 10 seconds, range 10 to 600.
  • Dead-letter max delivery attempts: 5 to 100, default 5.
  • Ack only after the work has succeeded.
  • Push endpoints must verify the Pub/Sub OIDC token.
  • Ordering keys limit parallelism; use only when needed.
  • Emulator: set PUBSUB_EMULATOR_HOST to use it.

Common mistakes

  • Acknowledging first and processing later, which loses messages if the handler crashes.
  • Adding a dead-letter topic but never watching it, so failures pile up unseen.
  • Using ordering keys for every message and losing parallel throughput.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1A handler crashes before acking. What happens?

Question 2

2What makes a handler idempotent?

Question 3

3Which gives you a place to inspect poison messages?

Question 4

4When should you acknowledge a message?

0/4 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    With the emulator running, create a topic and a pull subscription, publish one message, and pull it.

  2. Exercise 2medium

    Make a handler idempotent using a processed table keyed by message ID.

  3. Exercise 3hard

    Design retry and dead-letter settings for a payment-confirmation consumer that calls a slow external API.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Why do I get the same message twice?
Pub/Sub guarantees at-least-once delivery. A slow or lost ack causes a redelivery, so write handlers that can repeat safely.
Is exactly-once delivery available?
It is an option for some pull subscriptions with limits. Even then, design for repeats in the work your handler does elsewhere.
Can I try Pub/Sub for free?
Use the local emulator. For a real project, check current pricing and free allowances, and delete test resources afterwards.

Go deeper

ShareXLinkedInWhatsApp