Idempotent consumers and dead-letter topics with Pub/Sub and Cloud Run
A Cloud Run consumer behind a Pub/Sub push subscription sees duplicates with new message IDs. Keep the publisher's key in the same transaction as the change, dead-letter before a week of retries, and snapshot before each deploy so seek can replay.
ON THIS PAGE
A Cloud Run service behind a Pub/Sub push subscription will handle some messages twice, so make the second copy harmless. Key each message on the operation the publisher meant, not its message ID, and store the key in the same transaction as the change. Add a dead-letter topic so a message that can never succeed stops slowing the rest, and snapshot the subscription before every deploy, so a bad release ends in a replay, not a data fix.
Where the second copy comes from#
- The handler outlives the deadline. A push subscription to Cloud Run waits 10 seconds by default and 600 at most, with no per-message extension; Cloud Run's request timeout defaults to five minutes. Pub/Sub gives up first and resends, perhaps to another instance, while the first request may still finish: a caller hanging up does not stop the container.
- The handler fails. Any status except 102, 200, 201, 202 or 204 is a negative acknowledgement.
- The publisher retries. A timed-out publish sent again is a second message with a second ID, even on exactly-once subscriptions.
- You send it back. A dead-letter forward wraps the message in a new one, a republish makes another, and a seek redelivers acknowledged messages.
Only redeliveries are sure to keep the message ID. So the publisher sets the key, before its first attempt, as an attribute: an order ID with the step, a payment request ID, the upstream event's ID.
If a handler needs more than ten minutes, or you want exactly-once delivery, pull from a Cloud Run worker pool instead (see Cloud Run services, jobs, functions or worker pools). Event-driven architecture on Google Cloud shows where Pub/Sub fits.
Keep the key with the write#
Where the key lives matters more than its format: in the database that holds the change, in the same transaction. If the key is claimed before the work, a crash leaves undone work marked done; if it is written after, a crash in between runs the work twice. One transaction rules out both. An upsert that sets state at a version is already idempotent; the table is for changes that are not.
with engine.begin() as tx:
fresh = tx.execute(
text("INSERT INTO handled (op_key) VALUES (:k) ON CONFLICT DO NOTHING"),
{"k": op_key},
).rowcount
if fresh:
apply_change(tx, order)
return "", 204 # acknowledge a duplicate tooFor an effect outside your database, such as a payment, pass the same key as the provider's idempotency key.
Dead-letter after hours of backoff, not after a week#
Without a dead-letter topic, a message that can never succeed is retried until the subscription's retention runs out, seven days by default, and then dropped unprocessed. Meanwhile enough failures on a push subscription trigger push backoff, which applies to the whole subscription: one poison message, retried over and over, can slow every healthy one.
A dead-letter topic ends that after 5 to 100 attempts, if three details are right. The Pub/Sub service agent needs Publisher on the dead-letter topic and Subscriber on the source subscription, or attempts are not even counted. The dead-letter topic needs a subscription before anything fails: a subscription receives only what is published after it exists. And alert someone on subscription/dead_letter_message_count, or it is the same quiet loss with extra steps.
The trap is a downstream outage. With the database down, every message fails, and the default five immediate attempts empty the whole stream into the dead-letter topic. Use exponential backoff and enough attempts to outlast the outages you expect; the count is only approximate, since forwarding is best-effort. Order may not survive the forward either (see ordering and exactly-once in Pub/Sub).
gcloud pubsub subscriptions create orders-run --topic=orders \
--push-endpoint="$SERVICE_URL/pubsub" --push-auth-service-account="$INVOKER_SA" \
--ack-deadline=600 --min-retry-delay=10s --max-retry-delay=600s \
--dead-letter-topic=orders-dead-letter --max-delivery-attempts=20Seek: a replay instead of a data fix#
Before each consumer deploy, snapshot the subscription. If the new revision acknowledges messages it should not (a validator returning 204 on bad input, a swallowed error), roll back and seek to the snapshot: Pub/Sub redelivers everything since, to working code.
The replay repairs only what your idempotency design allows. Work the bad revision skipped never wrote a key, so it runs now. Work it did wrongly is harder: a handled-keys table says "done" and the replay skips it. A handler that sets state from the message instead (an order's status, a stock level at a version) overwrites the bad row. Write state as upserts where you can, and keep the table for effects that cannot be overwritten.
A snapshot lasts at most seven days, less with an old backlog; seeking to a timestamp needs acknowledged-message retention on the subscription or retention on the topic. A seek resets dead-letter attempt counts and can take a minute to settle.
On AWS and Azure#
SQS moves a message to a dead-letter queue after maxReceiveCount receives and has a built-in redrive back, but no seek: replaying deleted work needs an EventBridge archive upstream. Azure Service Bus dead-letters past a maximum delivery count, 10 by default, which you can raise but not switch off; resubmission is manual and a completed message is gone. Everywhere, the consumer still needs the publisher's key.
The diagram#
A push subscription feeds a Cloud Run consumer that writes the key and the change in one Cloud SQL transaction; failures go to a dead-letter topic, and the pre-deploy snapshot is the way back. Open it in archhy and make a copy.
