Muhammad Fari Madyan
Hire me
GCP · part 4 of 6

GCP for Backend Engineers Part 4: Availability — Three Layers, Retries with Jitter, Canary on Cloud Run & SLOs

Part four of a GCP for Backend Engineers series that opens with a quiz: availability in three layers, Cloud SQL HA that is not a backup, timeouts and retries with full jitter (a peak of 1,000 down to 135), canaries with revisions and tags on Cloud Run, rollback in seconds, expand-contract migrations, and SLOs with error budgets.

Muhammad Fari Madyan

· 11 min read

Baca dalam Bahasa Indonesia →

Opening: Every Component Is Healthy, Users Still Get Errors

Picture the dashboard on a Monday morning: Cloud Run green, Cloud SQL green, Memorystore green. Yet 30% of users get a 500 error when they open their profile page.

The cause is not a component that died. The cause is the 10 a.m. deploy: the full_name column was renamed to name in the same migration as the new code. Cloud Run is splitting traffic between the old and new revisions, and the old revision is still looking for full_name.

Availability is not just about servers being up. It is about users still being served when some part is broken, including when the "broken" part is our own deploy.


Warm-Up Quiz: Do You Still Remember?

Answer first. All correct? Jump to the Summary. Missed one? Let's refresh the material.

Question 1. Cloud Run is a regional service. What does that mean if one zone in the region goes down?

  • A. The service goes down until the zone recovers
  • B. The service keeps running, because Cloud Run is already spread across several zones
Show the answer to question 1

B. Cloud Run runs instances in several zones within a region with no setup needed. You do not have to think about zones for compute. What you do have to think about are the components that are not automatically regional, such as the database.

Question 2. Cloud SQL without an HA configuration, and its zone goes down. What happens?

  • A. Cloud SQL moves the instance to another zone automatically
  • B. The instance is not recovered automatically. It has to be restored by hand, for example from a backup
Show the answer to question 2

B. The Cloud SQL documentation says instances without HA are not recovered automatically from a zonal outage. With HA (regional), there is a standby in another zone and automatic failover.

Question 3. The SLO is 99.9% of requests successful over 30 days. How long may the service "fail completely" in that period?

  • A. About 4 minutes
  • B. About 43 minutes
  • C. About 7 hours
Show the answer to question 3

B: about 43 minutes. (1 − 0.999) × 30 days × 24 hours × 60 minutes = 43.2 minutes. That is the error budget.

Question 4. 1,000 clients fail at the same time, then all retry exactly 800 ms later. What is the problem?

  • A. None, the server has recovered
  • B. The server that just recovered gets hit by 1,000 requests in the same instant
Show the answer to question 4

B. This is a thundering herd. Retrying with the same delay for everyone just moves the spike to another moment. The fix is jitter: a random delay, so retries spread out. Section 3 has the numbers.

Question 5. Why is renaming a column in the same migration as the code that uses the new name dangerous on Cloud Run?

  • A. Because migrations always fail on Cloud SQL
  • B. Because during a gradual rollout, the old and new revisions run at the same time
Show the answer to question 5

B. Cloud Run can split traffic between revisions, and even without that, there are a few seconds when both are alive. Migrations must be backward compatible: add first, move over, remove last (expand, then contract).

What did you score? Let's take them apart.


1. Three Layers of Availability

Three layers of availability: infrastructure (zones, Cloud SQL HA, Memorystore Standard), application (timeouts, retries with jitter, idempotency, degradation, graceful shutdown), and release practice (revisions, canary, rollback, expand-contract migrations), with SLOs and error budgets as the measure

Click the diagram to see it full size.

Picture a hospital that must keep treating patients:

  • Infrastructure: there is a backup generator and two power lines. If one fails, the lights stay on.
  • Application: doctors do not wait forever for lab results. If the lab is late, there is a fallback procedure.
  • Release practice: a new procedure is tried in one ward first, not the whole hospital at once.

The three layers complete each other. Servers spread over three zones still fall over if the code waits on a third-party API with no timeout.


2. The Infrastructure Layer: Remove Single Points of Failure

A region has several zones, which are separate data centres. The goal: no single zone can stop the service by going down.

ComponentSpread automatically?What to do
Cloud RunYes, regionalNothing
Cloud SQLNo--availability-type=REGIONAL (HA), backups + PITR, read replicas
MemorystoreNoThe Standard tier if the data matters. Still never the only support
Cloud StorageDepends on the bucket locationPick region, dual-region or multi-region to fit the need
Pub/SubYesNothing

Two notes people often mix up:

  • HA is not a backup. HA protects against a zone going down. Backups + point-in-time recovery protect against human mistakes, such as deleted data. You need both.
  • Multi-region only when you really need it. The pattern: a global load balancer in front of Cloud Run in two regions. The compute part is easy. The data part is hard: which database is the primary, how do you write from two regions, how far does replication lag. Cost and complexity go up a lot. For most products, one region with several zones is enough.

3. The Application Layer: Withstand Failure

A timeout on every outbound call

Without a timeout, one slow dependency holds the request, the request holds a connection, and held connections fill up the instance. In Part 2 we saw a dead Redis hold a request for 73 seconds. Every outbound call needs a time limit.

Retries with exponential backoff and jitter

Temporary failures (503, 429, timeouts) often go away on a second try. But how you retry matters:

JS
const tunggu = (ms) => new Promise((r) => setTimeout(r, ms));

async function denganRetry(fn, { percobaan = 5, dasarMs = 100, maksMs = 2000, timeoutMs = 1000 } = {}) {
  for (let ke = 1; ; ke++) {
    try {
      return await fn({ signal: AbortSignal.timeout(timeoutMs) }); // a timeout on EVERY attempt
    } catch (err) {
      const bolehUlang = err.name === 'TimeoutError' || err.status === 429 || err.status >= 500;
      if (!bolehUlang || ke >= percobaan) throw err;
      const batas = Math.min(maksMs, dasarMs * 2 ** (ke - 1));  // 100, 200, 400, 800, ...
      const jeda = Math.round(Math.random() * batas);            // full jitter
      console.log(`percobaan ${ke} gagal (${err.message}), tunggu ${jeda} ms (batas ${batas} ms)`);
      await tunggu(jeda);
    }
  }
}

(denganRetry = with retry, percobaan = attempts, bolehUlang = may retry, batas = cap, jeda = delay.) With a fake API that fails the first three times:

TEXT
percobaan 1 gagal (503 Service Unavailable), tunggu 14 ms (batas 100 ms)
percobaan 2 gagal (503 Service Unavailable), tunggu 67 ms (batas 200 ms)
percobaan 3 gagal (503 Service Unavailable), tunggu 214 ms (batas 400 ms)
berhasil pada panggilan ke 4 { status: 'settlement' }

(gagal = failed, tunggu = wait, berhasil pada panggilan ke 4 = succeeded on call 4.) Four things make this retry safe:

  1. Only temporary errors are retried: timeouts, 429 and 5xx. A 400 or 404 will not change on a second try.

  2. The cap doubles (100, 200, 400, ...), with an upper limit. A struggling server gets room to breathe.

  3. Full jitter: a random delay between 0 and the cap. That is the answer to question 4. I simulated 1,000 clients retrying on the fourth attempt (an 800 ms cap):

    TEXT
    tanpa jitter : puncak 1000 request dalam satu jendela 100 ms
    full jitter  : puncak 135 request dalam satu jendela 100 ms
    

    (Without jitter, the peak is 1,000 requests in one 100 ms window. With full jitter, 135.)

  4. Only for idempotent operations. Retrying "create payment" without an idempotency key can charge twice. See Part 12 of the Node.js series.

Graceful degradation

Not every feature matters equally. If the recommendation service is slow, the home page still shows with a cached popular list. If the review service is down, the detail page still shows without reviews. Side features may fail, core features keep working.

A helpful question: "If this dependency is down, what is the most sensible thing to show the user?" Write the answer into the code, rather than working it out during an incident.

Graceful shutdown and min instances

  • Cloud Run sends SIGTERM and gives you 10 seconds. Finish requests in flight, then close connections (details in Part 4 of the Node.js series).
  • --min-instances for important endpoints, so the first spike does not wait for a cold start. Remember, it is billed.

4. The Release Layer: Code Changes Are the Number One Cause of Outages

Most outages do not come from a zone dying, but from changes we ship ourselves. Cloud Run makes gradual releases cheap, because every deploy becomes a stored revision.

BASH
# 1. Deploy the new version with no traffic, tagged so it can be tested directly
gcloud run deploy api --image=asia-southeast2-docker.pkg.dev/PROJECT/app/api:1.5.0 \
  --region=asia-southeast2 --no-traffic --tag=canary

# 2. Send 5% of traffic to the new version (canary), watch error rate and latency
gcloud run services update-traffic api --region=asia-southeast2 --to-tags=canary=5

# 3a. Looks good? Move all traffic to the latest revision
gcloud run services update-traffic api --region=asia-southeast2 --to-latest

# 3b. Trouble? Send 100% back to the old revision, within seconds
gcloud run services update-traffic api --region=asia-southeast2 --to-revisions=api-00041-xyz=100

With --tag=canary, the new revision also gets its own URL, so the team can test it directly before any user is sent there.

Backward-compatible migrations

A gradual release means two versions of the code live at the same time, and both use the same database. The opening story is avoided by splitting the change across several releases (expand, then contract):

ReleaseDatabase changeCode change
1 (expand)Add a name column (nullable)Write to full_name and name, read from full_name
2Fill name for existing rows (backfill)Read from name
3 (contract)Drop full_nameStop writing to full_name

Every release is safe to roll back, because the previous version still finds the column it needs. Slower, but no 10 a.m. full of errors.


5. SLOs: Measuring "Available Enough"

No system is 100% available. The question is: how much is enough, and how do you measure it?

  • SLI (service level indicator): what you measure. For example the percentage of requests that succeed and take under 300 ms.
  • SLO (objective): the target. For example 99.9% over 30 days.
  • Error budget: what is left that may fail.
TEXT
SLO 99    % → error budget  432.0 menit per 30 hari
SLO 99.5  % → error budget  216.0 menit per 30 hari
SLO 99.9  % → error budget   43.2 menit per 30 hari
SLO 99.99 % → error budget    4.3 menit per 30 hari

(menit per 30 hari = minutes per 30 days.) Every extra 9 cuts the budget tenfold, and the cost rises much faster than that.

An error budget turns the "ship or stabilise?" argument into a number. With plenty of budget left, the team can ship more boldly. If this month's budget is gone, the team stops shipping features and focuses on stability. Cloud Monitoring can track SLOs and alert when the budget burns too fast (burn rate). More on that in the next part.


6. Three Availability Traps

Trap 1: retries with no timeout, or retries for everything

A retry with no per-attempt timeout can wait forever on the first attempt. Retrying a 400 just wastes time. Retrying a non-idempotent operation can charge twice. And layered retries (client, API and worker all retrying 3 times) can produce 27 attempts for one user action.

Trap 2: thinking HA equals backup

An accidental DELETE FROM orders is replicated to the standby within milliseconds. HA does not help. PITR does, and only if the restore process has actually been practised.

Trap 3: multi-region too early

Multi-region solves a rare problem (a whole region down) by adding a daily one (data in two places). Get the three layers above right in one region first.


Summary

  • Availability: users are still served when some part breaks. Three layers: infrastructure, application, release practice.
  • Infrastructure: Cloud Run is already regional. Cloud SQL needs HA + backups + PITR. HA is not a backup.
  • Application: a timeout on every call, retries with backoff and full jitter only for temporary errors and idempotent operations, graceful degradation, graceful shutdown.
  • The jitter test: 1,000 clients, a peak of 1,000 without jitter vs 135 with full jitter.
  • Releases: revisions, --no-traffic --tag, a 5% canary, rollback in seconds. Expand, then contract migrations.
  • A 99.9% SLO = about 43 minutes of error budget per 30 days.

Closing & What's Next

The 10 a.m. from the opening did not have to happen: add the column first, drop it later, and a 5% canary would have shown the problem before 30% of users felt it.

But all of that depends on one thing: you knowing when something starts to break. How do you find out before a user tells you? That is the next part: observability.

Grab your coffee, see you in the next part!

ShareLinkedInXWhatsApp

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.

Work with me
← part 3Messaging and a Reference Architecturepart 5 →Observability

Muhammad Fari Madyan

Senior Backend Engineer building real-time, high-concurrency systems that hold up in production. Co-founder of LampungDev. Based in Bandar Lampung, Indonesia (UTC+7), working remote.

Work

Case studiesCahTixExam platform, 4 stacksOpen source

© 2026 Muhammad Fari Madyan

Designed and built by Muhammad Fari Madyan