Opening: A Checkout That Does Six Things at Once
Picture a very diligent POST /checkout endpoint. In one request, it:
- saves the order,
- sends a confirmation email,
- updates sales statistics,
- syncs data to the search engine,
- sends a push notification to the app,
- calls a partner's webhook.
The buyer waits for all of it. The p95 is 2.4 seconds. And one afternoon, the email service is having an outage: every checkout fails, even though the orders themselves are fine.
The buyer only needs to wait for one thing: the order being saved. The other five can happen a second, a minute or an hour later. This part is about GCP's tools for "do it later": Pub/Sub, Cloud Tasks, Cloud Scheduler and Eventarc, and then one reference architecture that ties everything together.
Warm-Up Quiz: Do You Still Remember?
Answer first. All correct? Jump to the Summary. Missed one? Let's refresh the material.
Question 1. By default, what does Pub/Sub guarantee about message delivery?
- A. Exactly-once: every message exactly once
- B. At-least-once: every message at least once, possibly more
Show the answer to question 1
B. A message can be delivered more than once, even after it has been acked. There is an exactly-once delivery option, but only for pull subscriptions and within one region. So consumers must be idempotent, as in Part 12 of the Node.js series.
Question 2. For a push subscription, how does Pub/Sub know a message was processed successfully?
- A. Your endpoint answers with a 2xx code
- B. Your endpoint calls a separate
ackAPI
Show the answer to question 2
A. A 2xx response (for example 200 or 204) counts as an ack. Any other code, or a timeout, makes Pub/Sub redeliver with growing delays.
Question 3. You need to call a payment gateway API for 50,000 refunds, and that API allows 100 requests per second. What is the best fit?
- A. Pub/Sub
- B. Cloud Tasks
Show the answer to question 3
B: Cloud Tasks. Cloud Tasks is built for explicit calls to one endpoint with rate control: --max-dispatches-per-second, concurrency and retry rules. Pub/Sub focuses on reliable delivery to many receivers, with no rate brake on the sending side.
Question 4. One "payment succeeded" event must be handled by three services: email, statistics and search. What is the right Pub/Sub design?
- A. One topic, one subscription, three consumers competing for messages
- B. One topic, three subscriptions, each getting a copy of the message
Show the answer to question 4
B. Each subscription gets a copy of every message. Several consumers on one subscription share its messages (each gets a portion), which suits splitting load, not fan-out.
Question 5. What is the maximum dispatch rate of one Cloud Tasks queue?
- A. 500 per second per queue
- B. Unlimited
Show the answer to question 5
A: 500 per second per queue, according to the comparison table in Google's documentation. Need more? Split across several queues, or consider Pub/Sub if what you need is not rate control.
What did you score? Let's take them apart.
1. Separate What Must Happen Now from What Can Wait
Back to checkout. The question for every step: "If this is a minute late, is the buyer worse off?"
| Step | Must finish before answering? | Tool |
|---|---|---|
| Save the order | Yes | Cloud SQL, inside the request |
| Confirmation email | No | Pub/Sub → worker |
| Sales statistics | No | Pub/Sub → worker (or straight to BigQuery) |
| Search sync | No | Pub/Sub → worker |
| Push notification | No | Pub/Sub → worker |
| Partner webhook (limited to 10/second) | No | Cloud Tasks |
Now checkout only saves the order and publishes one payment.succeeded message. If the email service is down, its messages wait in Pub/Sub and get processed when it recovers. Checkout keeps working.
One important detail: saving the order and publishing the message are two separate steps. If the process dies between them, the order is saved but the message is never published. For events that must not be lost, use the outbox pattern from Part 12 of the Node.js series: save "the message to publish" in the same database transaction, and let a worker publish it.
2. Pub/Sub: One Event, Many Receivers
Click the diagram to see it full size.
The vocabulary:
- Topic: where messages are published. The publisher does not know who is listening.
- Subscription: a "mailbox" for one receiver. Each subscription gets a copy of every message.
- Push or pull: Pub/Sub calls your endpoint, or your worker fetches messages.
- Ack: the signal that a message is done. Unacked messages are kept (7 days by default) and redelivered.
That is a big difference from the Redis Pub/Sub we used as a WebSocket bus in Part 3 of the Node.js series. Redis Pub/Sub stores nothing: a receiver that is down misses the message. Cloud Pub/Sub keeps messages until they are acked, so it suits events that must not be lost.
Idempotent consumers
Because delivery is at-least-once, a handler must be safe to receive the same message many times. Here is an endpoint for a push subscription, using messageId as the idempotency key:
// The endpoint a Pub/Sub push subscription calls.
const server = http.createServer(async (req, res) => {
let body = '';
for await (const potong of req) body += potong;
const { message } = JSON.parse(body);
const event = JSON.parse(Buffer.from(message.data, 'base64').toString());
// Pub/Sub is at-least-once: the same messageId can arrive again.
const pertama = await redis.set(`pubsub:${message.messageId}`, '1', 'EX', 7 * 24 * 3600, 'NX');
if (pertama === 'OK') {
try {
await kirimEmailTiket(event.pesananId);
} catch (err) {
await redis.del(`pubsub:${message.messageId}`); // failed: release the key so a redelivery is processed
res.statusCode = 500; // non-2xx = Pub/Sub will redeliver
return res.end();
}
}
res.statusCode = 204; // 2xx = ack
res.end();
});
(pertama = first, kirimEmailTiket = send ticket email, pesananId = order ID.) I sent the same envelope three times, exactly what happens when Pub/Sub redelivers:
pengiriman 1: HTTP 204
pengiriman 2: HTTP 204
pengiriman 3: HTTP 204
email terkirim: 1
(pengiriman = delivery, email terkirim = emails sent.) All three were acked, but the email went out only once.
A note: messageId is good for filtering Pub/Sub's own redeliveries. If the publisher itself can publish the same event again (for example after a retry), the messageId will differ. For that, use a business key such as orderId + event type, plus a unique constraint in the database.
Poison messages and a dead-letter topic
What about a message that always fails, for example because its data is broken? Without a safety net, it is redelivered forever and eats resources. Add a dead-letter topic:
gcloud pubsub subscriptions create ticket-email \
--topic=payment-succeeded \
--push-endpoint=https://worker-xxxx.a.run.app/pubsub/email \
--push-auth-service-account=pubsub-invoker@PROJECT.iam.gserviceaccount.com \
--dead-letter-topic=payment-succeeded-dlq \
--max-delivery-attempts=10
After 10 failures, the message moves to payment-succeeded-dlq. Put an alert there, inspect, fix, then republish. --push-auth-service-account makes Pub/Sub send a token, so the worker endpoint does not have to be public.
3. Cloud Tasks: When You Set the Pace
Pub/Sub says "here is what happened, whoever cares can handle it". Cloud Tasks says "call this endpoint, at this rate, retry with these rules". Google calls this implicit versus explicit invocation.
gcloud tasks queues create partner-webhook \
--location=asia-southeast2 \
--max-dispatches-per-second=10 \
--max-concurrent-dispatches=5 \
--max-attempts=8 \
--min-backoff=2s \
--max-backoff=300s
| Pub/Sub | Cloud Tasks | |
|---|---|---|
| Style | An event for many receivers | A command to one endpoint |
| Many receivers per message | Yes | No |
| Rate control on the queue side | No (pull clients can use flow control) | Yes, per queue |
| Delivery at a scheduled time | No | Yes |
| Deduplication on creation | No | Yes, by task name |
| Maximum rate | No upper limit, regional quotas apply | 500 per second per queue |
Typical Cloud Tasks uses: a webhook to a rate-limited partner, "send a reminder 24 hours before the event", or spreading 50,000 refunds so they do not hit the payment gateway's API limit.
4. Cloud Scheduler and Eventarc
Cloud Scheduler is managed cron. In Part 3 of the Node.js series we saw a setInterval running on four instances send four emails. Cloud Scheduler calls one endpoint once, on schedule:
gcloud scheduler jobs create http daily-reminder \
--location=asia-southeast2 \
--schedule="0 7 * * *" \
--time-zone="Asia/Jakarta" \
--uri=https://worker-xxxx.a.run.app/tasks/reminder \
--http-method=POST \
--oidc-service-account-email=scheduler-invoker@PROJECT.iam.gserviceaccount.com
Eventarc connects events from GCP services to Cloud Run: a new file in Cloud Storage, a change in Firestore, or an audit log entry (for example "someone changed IAM"). The buatThumbnail function in Part 1 is triggered through Eventarc.
5. A Reference Architecture: Ten Components
Click the diagram to see it full size.
How to walk through it in two minutes, from the outside in:
- Clients (mobile and web apps) come in by two routes.
- Big files (audio, images) come from Cloud Storage through Cloud CDN. Most bytes stop here and never touch a server.
- API requests come through a load balancer with Cloud Armor (WAF and per-IP rate limiting).
- A stateless Cloud Run API handles requests. It reads and writes Cloud SQL (regional HA) and uses Memorystore as a cache that is allowed to fail.
- Non-urgent work is published to Pub/Sub and handled by a Cloud Run worker.
- Rate-limited calls to third-party APIs go through Cloud Tasks.
- Scheduled jobs are triggered by Cloud Scheduler.
- Reporting data flows into BigQuery.
If someone asks "where is this most likely to hit a wall?", the answer is almost always Cloud SQL. That is why it has a different colour in the diagram, and why Part 6 spends a lot of time on it.
6. Three Messaging Traps
Trap 1: consumers that are not idempotent
That is question 1. At-least-once means duplicates are normal, not a rare bug. A handler that sends email, adds to a balance or issues a ticket must be safe to repeat.
Trap 2: acking before you are done
On a pull subscription, calling ack() at the start of the handler and processing afterwards means the message is lost if the process dies halfway. Ack after the work is saved.
Trap 3: Pub/Sub for work that needs a brake
Publishing 50,000 refund messages to Pub/Sub with a push subscription to a worker that calls the payment gateway: Cloud Run scales out to process them as fast as possible, and the partner API rejects you with 429. When what you need is a controlled rate to one destination, that is Cloud Tasks' job.
Summary
- Separate what must happen now from what can wait. The buyer only waits for the order to be saved.
- Pub/Sub: one topic, many subscriptions, each with its own copy. At-least-once, so consumers must be idempotent. Push: 2xx = ack.
- A dead-letter topic +
--max-delivery-attemptsfor poison messages. - Cloud Tasks: commands to one endpoint with rate control, scheduling and deduplication. At most 500 per second per queue.
- Cloud Scheduler for cron that runs once, Eventarc for events from GCP services.
- The reference architecture: a CDN for big bytes, stateless Cloud Run, Cloud SQL as the likeliest bottleneck, Pub/Sub for non-urgent work.
Closing & What's Next
The checkout from the opening now only saves the order and publishes one message. When the email service has an outage, buyers notice nothing, and the emails still go out once it recovers.
The architecture is drawn. The next question: how do you make sure it stays up when a zone dies, when a dependency is slow, or when a deploy ships a bug? That is the next part: availability.
Grab your coffee, see you in the next part!

Written by Muhammad Fari Madyan
Senior Backend Engineer and co-founder of LampungDev. I write up what I build so others can learn from it.


