Field note · GCP · Oct 2026 · 30 min read
Deploying a backend and a frontend on GCP, the enterprise way
No servers to SSH into, no keys in GitHub, no database on the internet. The mindset first, then a blueprint, then the 16 steps I actually ran, and everything that broke along the way.
Why I wrote this
This one is for me more than anyone. I deployed a typical product to a fresh Google Cloud project: a backend API with Postgres and Redis, a background worker for heavy jobs, a server-rendered website, a single-page admin panel, and images the whole internet should load fast. I refused to do it blind. Every resource was created by a command I understood, and checked in the console afterwards. The next time I stand up an environment, I want this page open next to the terminal.
The product handles personal data, so "it works" was never the bar. The bar was: if any one piece is compromised, the damage stays small, it keeps working when traffic grows, and I can prove afterwards what happened.
The mindset
The tools matter less than the rules you hold yourself to. These shaped every decision below, and they carry over to any cloud.
- Private by default. Nothing gets a public IP unless it must. The database and cache live on a private network; services accept traffic only from the load balancer. Exactly one thing faces the internet.
- No long-lived keys, anywhere. No service-account JSON files, no cloud credentials in CI secrets. The pipeline proves its identity with a short-lived signed token; services use their attached identity.
- One identity per workload, least privilege. The API, the worker, the migrator, the admin CLI and each deployer get their own identity with only what they need. A compromised frontend build can redeploy the frontend, and nothing else.
- Secrets are generated, stored, never seen. Passwords are generated by the setup script and piped straight into a secret manager. No human reads them, nothing prints them, and there is no
.env.prodon anyone's laptop. - Defence in depth at the edge. TLS policy, a path allowlist, per-IP rate limiting, WAF rules and DDoS protection, all before a request reaches a container.
- Setup and deploy are different processes. Creating infrastructure is rare, privileged and human. Shipping code is frequent, narrow and automated. They never share a script or a credential.
- Immutable, reproducible releases. Images are deployed by digest (
sha256:…), base images are pinned by digest, CI actions are pinned by commit SHA, and a bot proposes the updates. - Stateless compute, managed state. Containers hold nothing worth keeping, so they can be killed, replaced and multiplied at will. State lives in managed databases, caches and buckets that someone else keeps alive.
- Evidence you can't edit. Every state change writes an audit entry, signed with a KMS key, into a bucket whose retention is locked. Not even the project owner can delete it early.
- No blind work. One step at a time: understand the command, run it, verify it in the console. Idempotent scripts record what was done so the next environment is a repeat, not a rediscovery.
What good looks like
Before any command, this is the target. If a design decision doesn't move towards one of these, it's probably decoration.
| Concern | Backend (API + worker) | Frontends (website + admin) |
|---|---|---|
| Runs as | stateless container, non-root, distroless image | SSR server on distroless, or a static build in a non-root web server |
| Reachable | only through the load balancer | only through the load balancer, cached at the edge |
| Identity | own service account, narrow grants | own service account with no grants at all |
| Secrets | mounted from a secret manager at runtime | none, ever: everything in a frontend build is public |
| Config | one settings file per environment, no secrets in it | build-time public variables only |
| Data | private DB + cache over TLS, encrypted sensitive fields | talks only to its own origin; SSR calls the API over the private network |
| Files | private buckets; paid files only through short-lived signed URLs | published images on a media host, from one public bucket behind a CDN |
| Scales by | instance autoscaling + a queue for heavy work | CDN and immutable, hashed assets |
| Ships via | its own pipeline and deployer, by digest | its own pipeline and deployer, by digest |
| Security headers | strict CORS, no stack traces | CSP, HSTS, frame-deny, nosniff on every response |
Every service and tool
Google Cloud
| Service | What it does here |
|---|---|
| Cloud Run (services) | the API, the website, the admin panel, and an internal-only worker |
| Cloud Run (jobs) | one-off tasks from the API image: DB bootstrap, migrations, an admin CLI |
| Cloud SQL for PostgreSQL | private IP only, TLS required, separate logins per role |
| Memorystore for Redis | sessions and rate limits; AUTH password + in-transit TLS |
| VPC + Private Service Access | private network, peering for managed databases, Private Google Access |
| Secret Manager | every password, connection URL and third-party key; per-secret IAM |
| Cloud KMS | an encryption key for envelope encryption, a signing key for audit entries |
| Cloud Storage | private uploads and generated files, one public bucket for published images, a write-once audit bucket |
| Cloud Tasks | queue for heavy work; calls the worker with a signed OIDC token |
| External Application Load Balancer | global static IP, managed certificate, host and path routing |
| Cloud CDN | caches the website's assets and serves published images from the public bucket |
| Cloud Armor | path allowlist, per-IP throttle, OWASP rules, adaptive L7 DDoS defence |
| Artifact Registry | one container repository per deployable |
| IAM + Workload Identity Federation | keyless CI → cloud, locked to one repo and branch |
| Organization Policy + Tags | domain-restricted sharing everywhere, with one tag-scoped exception for the public bucket |
| Cloud Logging + Audit Logs | request logs from the load balancer, job logs, admin activity |
Everything else
| Tool | Role |
|---|---|
| gcloud CLI | every resource created by a command I could read first |
| Bash (setup.sh, deploy.sh) | an idempotent record of setup, and the deploy script CI runs |
| GitHub Actions | verify (lint, tests, build) → build image → deploy, on push to the deploy branch |
| Dependabot | weekly PRs for packages, base images and pinned actions |
| Docker (multi-stage) | one Dockerfile, one target per deployable |
| Distroless Node (nonroot) | a runtime with no shell and no package manager |
| Next.js (standalone output) | the server-rendered website, shipped on a distroless Node image |
| nginx-unprivileged | serves the admin SPA as non-root, with strict security headers |
| A DNS provider | three A records pointing at the load balancer |
| Third-party APIs | email, SMS and payments; their keys live only in Secret Manager |
The architecture
Three hostnames share one load balancer, one IP and one certificate, and none of them is "the API". Each browser app owns a host and reaches the backend on its own origin:
- app host: the website.
/api/*and the payment webhook go to the backend, everything else to the website. - admin host: the staff panel. Its own API prefix goes to the backend, everything else to the SPA.
- media host: published images, straight from a bucket through Cloud CDN. No container involved.
Same-origin means no CORS to get wrong, cookies stay first-party, and there is no separate API address to find and attack. I started with a public API host too, and retired it once nothing used it: an unused public endpoint is attack surface with no upside. If mobile apps or partners need one later, it comes back with its own path allowlist.
The website renders on the server, so it calls the API itself too. That call doesn't go back out through the internet: the website's container sends all outbound traffic into the VPC (Direct VPC egress) and calls the API's internal address.
And this is the life of one request:
Setup vs deploy
The first decision that mattered. setup.sh creates the environment and runs once, by an owner. deploy.sh runs in CI on every push, as a deployer that can ship images and nothing more: it can't read secrets, change IAM or touch data. Both read one settings file per environment (dev.conf) holding names and sizes but never a secret, so it's safe to commit. Production is a copy called prod.conf in its own project.
The 16 steps
Each step is what to create, why it exists, the commands, and where to check it.$PROJECT, $REGION and the example.com hosts stand in for real values.
One project per environment, and the right account
Why: dev and prod live in separate projects, so a mistake in one can't reach the other and permissions never leak across. Before every session, confirm which account and project the CLI is pointed at: a correct command in the wrong project is the classic expensive mistake.
gcloud auth login
gcloud config set project $PROJECT
gcloud config list --format="value(core.account,core.project)"
gcloud services enable run.googleapis.com sqladmin.googleapis.com redis.googleapis.com \
secretmanager.googleapis.com cloudkms.googleapis.com compute.googleapis.com \
servicenetworking.googleapis.com artifactregistry.googleapis.com cloudtasks.googleapis.com \
iamcredentials.googleapis.com sts.googleapis.comSee it in the console → the project picker in the top bar shows the same ID the CLI prints.
The private network
Why: the database and cache must never have public IPs. A custom VPC with a subnet for Cloud Run's outbound traffic, Private Google Access so Google APIs are reached without the internet, and a peered range for managed services.
gcloud compute networks create app-vpc --subnet-mode=custom
gcloud compute networks subnets create app-run --network=app-vpc --region=$REGION \
--range=10.20.0.0/24 --enable-private-ip-google-access
gcloud compute addresses create app-private-services --global --purpose=VPC_PEERING \
--prefix-length=20 --network=app-vpc
gcloud services vpc-peerings connect --service=servicenetworking.googleapis.com \
--ranges=app-private-services --network=app-vpcSee it in the console → VPC network → app-vpc: one subnet with Private Google Access on, and a private service connection.
One service account per workload
Why: the default compute account has broad Editor rights. Every workload gets its own identity, so permissions are granted narrowly and logs say exactly who did what.
| Service account | Runs | Can reach |
|---|---|---|
| api | the backend | its DB login, cache, buckets, KMS, the task queue |
| worker | heavy background jobs | the buckets it reads and writes, nothing else |
| migrator | migration job | the migration DB login only |
| db-admin | bootstrap job | creates DB roles and logins |
| operator | admin CLI job | the operator DB login only |
| api-deployer | backend CI | deploy the backend services and jobs; push images |
| site | the website (SSR) | nothing but a network path to the API |
| site-deployer | website CI | deploy the website service only |
| web | the admin SPA | nothing; it serves static files |
| web-deployer | admin CI | deploy the admin service only |
for sa in api worker migrator db-admin operator api-deployer site site-deployer web web-deployer; do
gcloud iam service-accounts create $sa
doneSee it in the console → IAM & Admin → Service accounts.
Encryption keys (Cloud KMS)
Why: sensitive fields are encrypted by the app with a data key, and that data key is itself encrypted ("wrapped") by a key that never leaves KMS. A database dump alone is useless. A second, asymmetric key signs audit entries.
gcloud kms keyrings create app --location=$REGION
gcloud kms keys create data-kek --keyring=app --location=$REGION --purpose=encryption \
--rotation-period=90d --next-rotation-time=$(date -u -v+90d +%Y-%m-%dT%H:%M:%SZ)
gcloud kms keys create audit-signing --keyring=app --location=$REGION \
--purpose=asymmetric-signing --default-algorithm=ec-sign-p256-sha256See it in the console → Security → Key Management → your keyring: an encryption key with a rotation period, and a signing key.
Secret Manager: generated, never printed
Why: secrets are stored in your region only, and access is granted per secret, per service account, never project-wide. Generated values go from openssl straight into Secret Manager through a pipe, so they never touch the screen or the disk.
gcloud secrets create redis-auth --replication-policy=user-managed --locations=$REGION
openssl rand -base64 36 | tr -d '\n' | gcloud secrets versions add redis-auth --data-file=-
gcloud secrets add-iam-policy-binding redis-auth \
--member=serviceAccount:api@$PROJECT.iam.gserviceaccount.com \
--role=roles/secretmanager.secretAccessorSee it in the console → Security → Secret Manager: each secret has its own permissions tab.
Managed Postgres: private IP, TLS only
Why: no public IP and encrypted connections only. The app verifies the server certificate against the instance CA (sslmode=verify-ca), so even inside the VPC nobody can impersonate the database. Backups, point-in-time recovery and deletion protection are on from day one.
gcloud sql instances create pg-main --database-version=POSTGRES_17 --edition=enterprise \
--tier=db-g1-small --region=$REGION --network=app-vpc --no-assign-ip --ssl-mode=ENCRYPTED_ONLY \
--backup-start-time=21:00 --enable-point-in-time-recovery --retained-backups-count=7 \
--storage-auto-increase --deletion-protection
gcloud sql databases create app --instance=pg-mainSee it in the console → SQL → instance → Connections: Public IP off, SSL mode 'Encrypted connections only'.
Database roles and least-privilege logins
Why: row-level security only protects you if the app connects as a role that can't bypass it. Group roles are created without login; separate logins exist for the API, the migrator and the admin CLI, each with a generated password stored as a connection URL in Secret Manager. CONNECT on the database is revoked from PUBLIC.
This runs as a Cloud Run job inside the VPC on every deploy. It's idempotent: existing roles only get their password refreshed, so it's safe to repeat.
See it in the console → SQL → Users lists only the expected logins; Secret Manager has one connection URL per login.
Redis with AUTH and TLS
Why: the same rule as the database: private, password-protected, encrypted in transit. The client connects with rediss:// and pins the instance CA.
gcloud redis instances create cache --region=$REGION --tier=basic --size=1 \
--network=app-vpc --connect-mode=private-service-access \
--enable-auth --transit-encryption-mode=server-authenticationSee it in the console → Memorystore → instance: AUTH enabled, in-transit encryption 'Server authentication'.
Storage buckets: one per kind of data
Why: a bucket is the unit of access, so split by who may read, not by feature. Uniform bucket-level access and public-access prevention on every bucket at creation; exactly one is made public later, on purpose (see public media). Bucket names are global, so use a readable environment prefix.
| Bucket | Holds | Read by |
|---|---|---|
| media-private | every uploaded image, drafts included | the API only; staff previews stream through it |
| media-public | copies of published images only | anyone, through the media host |
| originals | large uploads (PDFs) as received | API and worker; the browser writes via a signed URL |
| generated | pages rendered from them, paid content | entitled users, via short-lived signed URLs |
| audit | signed audit entries, retention locked | nobody edits or deletes |
for b in media-private media-public originals generated; do
gcloud storage buckets create gs://myapp-dev-$b --location=$REGION \
--uniform-bucket-level-access --public-access-prevention
doneSee it in the console → Cloud Storage → Buckets: every bucket 'Not public' for now, access control 'Uniform'.
A queue for heavy work
Why: slow or memory-hungry work (rendering, imports, reports) doesn't belong in the request path. The API enqueues a task and returns immediately; Cloud Tasks calls the worker with a Google-signed OIDC token, retries with backoff, and caps concurrency so a burst can't overwhelm anything downstream.
gcloud tasks queues create jobs --location=$REGION \
--max-concurrent-dispatches=2 --max-attempts=3 --min-backoff=30s --max-backoff=300sSee it in the console → Cloud Tasks → queue: max concurrent dispatches and max attempts set.
Cloud Run services as placeholders
Why: service-level IAM and the load balancer both need the service to exist before the first real deploy. The placeholder is Google's hello image; CI replaces it. Ingress is set once here: internal-and-cloud-load-balancing for anything public, internal for the worker.
gcloud run deploy api --image=us-docker.pkg.dev/cloudrun/container/hello --region=$REGION \
--service-account=api@$PROJECT.iam.gserviceaccount.com \
--ingress=internal-and-cloud-load-balancing --no-invoker-iam-check
gcloud run deploy worker --image=us-docker.pkg.dev/cloudrun/container/hello --region=$REGION \
--service-account=worker@$PROJECT.iam.gserviceaccount.com \
--ingress=internal --no-allow-unauthenticatedSee it in the console → Cloud Run → service → Networking: Ingress 'Internal + Cloud Load Balancing'.
Image registry and keyless CI
Why: this replaces the JSON key most tutorials tell you to paste into CI secrets. GitHub signs a token saying "repo X, branch Y"; a Workload Identity provider accepts only that repo and branch, and lets it act as the deployer for about an hour. Each repo gets its own provider and its own deployer.
gcloud artifacts repositories create api --repository-format=docker --location=$REGION
gcloud iam workload-identity-pools create github-actions --location=global
gcloud iam workload-identity-pools providers create-oidc api-dev \
--workload-identity-pool=github-actions --location=global \
--issuer-uri=https://token.actions.githubusercontent.com \
--attribute-mapping="google.subject=assertion.sub,attribute.deploy=assertion.repository + '@' + assertion.ref" \
--attribute-condition="assertion.repository == 'org/api' && assertion.ref == 'refs/heads/dev'"See it in the console → IAM & Admin → Workload Identity Federation → pool → provider: the attribute condition names one repo and one branch.
Cloud Armor: the firewall in front of everything
Why: the cheapest request to handle is the one that never reaches your code. An allowlist rule lets only your own hosts through and answers everything else (scanners hitting the raw IP, old or guessed hostnames) with a 404. A throttle caps any single IP. OWASP rules (SQLi, XSS, LFI, RCE…) start in preview so you can read their logs before they block real users. Adaptive L7 DDoS defence is on.
gcloud compute security-policies create edge
gcloud compute security-policies update edge --enable-layer7-ddos-defense
gcloud compute security-policies rules create 100 --security-policy=edge --action=deny-404 \
--expression="!(request.headers['host'] == 'app.example.com' || request.headers['host'] == 'admin.example.com' || request.headers['host'] == 'media.example.com')"
gcloud compute security-policies rules create 200 --security-policy=edge --action=throttle \
--src-ip-ranges='*' --rate-limit-threshold-count=300 --rate-limit-threshold-interval-sec=60 \
--conform-action=allow --exceed-action=deny-429 --enforce-on-key=IPCloud Armor speaks a subset of CEL: there is no in operator, so a list of hosts is spelled out with ||.
See it in the console → Network security → Cloud Armor policies → your policy → Rules.
The load balancer and managed certificate
Why: a global static IP, a Google-managed certificate that renews itself, an SSL policy that refuses anything older than TLS 1.2, and a port-80 rule whose only job is to redirect to HTTPS. The chain is: forwarding rule → proxy → URL map → backend (with Cloud Armor) → serverless NEG → Cloud Run.
gcloud compute addresses create edge-ip --global
gcloud compute network-endpoint-groups create api-neg --region=$REGION \
--network-endpoint-type=serverless --cloud-run-service=api
gcloud compute backend-services create api-backend --global \
--load-balancing-scheme=EXTERNAL_MANAGED --enable-logging --logging-sample-rate=1
gcloud compute backend-services update api-backend --global --security-policy=edge
gcloud compute backend-services add-backend api-backend --global \
--network-endpoint-group=api-neg --network-endpoint-group-region=$REGION
gcloud compute url-maps create edge --default-service=api-backend --global
gcloud compute ssl-policies create tls-modern --profile=MODERN --min-tls-version=1.2 --global
gcloud compute ssl-certificates create edge-cert-v1 --global \
--domains=app.example.com,admin.example.com,media.example.com
gcloud compute target-https-proxies create edge-https --url-map=edge \
--ssl-certificates=edge-cert-v1 --ssl-policy=tls-modern --global
gcloud compute forwarding-rules create edge-https --global \
--load-balancing-scheme=EXTERNAL_MANAGED --address=edge-ip \
--target-https-proxy=edge-https --ports=443See it in the console → Network services → Load balancing → your load balancer: frontend, routing rules and backends all healthy.
DNS
Why: one A record per host at your DNS provider, all pointing at the same static IP. The managed certificate is issued only once Google sees each domain resolve to its own load balancer, so this step is what unblocks HTTPS.
dig +short app.example.com admin.example.com media.example.com
gcloud compute ssl-certificates describe edge-cert-v1 --global \
--format="value(managed.status,managed.domainStatus)"See it in the console → the certificate shows ACTIVE per domain first, then ACTIVE overall.
Settings, the write-once audit bucket, and the first push
Why: non-secret settings (hosts, sender address, sizes) go in the env file; the third-party keys only you have are typed into Secret Manager through stdin and never saved locally. The audit bucket gets a retention policy that is then locked, which can never be undone. Then a push to the deploy branch, and CI does the rest.
gcloud secrets versions add payment-webhook-secret --data-file=-
gcloud storage buckets create gs://myapp-dev-audit --location=$REGION \
--uniform-bucket-level-access --public-access-prevention --retention-period=1d
gcloud storage buckets update gs://myapp-dev-audit --lock-retention-periodpermissions:
contents: read
id-token: write # lets the job request the OIDC token
steps:
- uses: google-github-actions/auth@<pinned-sha>
with:
workload_identity_provider: projects/<number>/locations/global/workloadIdentityPools/github-actions/providers/api-dev
service_account: api-deployer@<project>.iam.gserviceaccount.com
- run: docker build --target api -t "$IMAGE:$GITHUB_SHA" . && docker push "$IMAGE:$GITHUB_SHA"
- run: ./infra/deploy.sh dev "$GITHUB_SHA" # bootstrap → migrate → deploy by digestSee it in the console → CI: verify and deploy green; Cloud Run → revisions show the image digest; the migration job succeeded.
The frontends, deployed on their own
Each frontend lives in its own repo with its own pipeline, so they deploy independently of the backend and of each other: a push to one never touches the others. Each reuses the edge (same IP, same certificate) and brings its own registry, service accounts, Workload Identity provider and load balancer backend. The two are deliberately different shapes:
| Admin panel (SPA) | Website (server-rendered) | |
|---|---|---|
| Image | static build in nginx-unprivileged | Next.js standalone output on distroless Node |
| Cloud Run | gen1, 256Mi: it only serves files | gen2, 512Mi: it renders pages |
| Talks to the API | from the browser, same origin | from the browser, and from the server over the VPC |
| Outbound network | none needed | Direct VPC egress, all traffic, to the API's internal URL |
| Edge cache | none: staff pages are private | Cloud CDN honouring the app's own Cache-Control |
| Indexing | noindex | SEO is the point |
One routing rule per host joins each to the backend:
gcloud compute backend-services create site-backend --global \
--load-balancing-scheme=EXTERNAL_MANAGED --enable-cdn --cache-mode=USE_ORIGIN_HEADERS
gcloud compute url-maps add-path-matcher edge --global --path-matcher-name=app \
--default-service=site-backend --path-rules='/api/*=api-backend,/webhooks/payments=api-backend' \
--new-hosts=app.example.com
gcloud compute url-maps add-path-matcher edge --global --path-matcher-name=admin \
--default-service=admin-backend --path-rules='/staff-api/*=api-backend' \
--new-hosts=admin.example.com- Its own deployer, scoped to one service. Each frontend deployer gets
run.developeron its own service only, not on the project. A poisoned npm package in a frontend build can redeploy that frontend, not the API that can read the database. - No secrets in the build. Every
NEXT_PUBLIC_*or Vite variable ships to the browser, so only public values go in. The website's server-side settings (like the API's internal URL) are runtime environment variables, not build arguments. - Headers on every response. CSP, HSTS,
X-Frame-Options: DENY,nosniff, a strict referrer policy andnoindexfor internal panels. The admin CSP'sconnect-srclists the storage host, because direct uploads go there. In nginx, repeat headers in everylocationthat sets its own, because nested blocks don't inherit them. - Cache rules that make deploys safe. Hashed assets are
immutablefor a year; HTML isno-cache, so users pick up a new release on the next load.
Public media, done safely
Article images and covers must load for anyone, fast, without a login. Drafts must not. The trick is to never decide "public or private" per file at request time, but by which bucket a file is in:
- Staff upload into the private bucket. The admin panel previews through the API, which checks the staff session and streams the file. Drafts are never reachable any other way.
- Publishing copies the image's renditions into the public bucket; unpublishing deletes them. The public bucket holds published images and nothing else, by construction.
- The media host is a backend bucket with Cloud CDN on the same load balancer, so readers get edge-cached files and the API never sees the traffic.
Getting past your own guardrail, narrowly
A modern organisation enforces domain-restricted sharing: nothing can be granted to anyone outside your Workspace, and allUsers is outside. That is exactly the safety net you want everywhere else, so don't switch it off for the project (I found an older project where someone had: anything in it could be shared with anyone). Instead, make a tag the exception:
gcloud resource-manager tags keys create public-access --parent=organizations/$ORG
gcloud resource-manager tags values create allowed --parent=$ORG/public-access
cat > policy.yaml <<EOF
name: organizations/$ORG/policies/iam.allowedPolicyMemberDomains
spec:
rules:
- values:
allowedValues: [$WORKSPACE_CUSTOMER_ID]
- allowAll: true
condition:
expression: "resource.matchTag('$ORG/public-access', 'allowed')"
EOF
gcloud org-policies set-policy policy.yamlgcloud resource-manager tags bindings create --tag-value=$ORG/public-access/allowed \
--parent=//storage.googleapis.com/projects/_/buckets/myapp-dev-media-public --location=$REGION
gcloud storage buckets update gs://myapp-dev-media-public --no-public-access-prevention
gcloud storage buckets add-iam-policy-binding gs://myapp-dev-media-public \
--member=allUsers --role=roles/storage.legacyObjectReader
gcloud compute backend-buckets create media --gcs-bucket-name=myapp-dev-media-public \
--enable-cdn --cache-mode=CACHE_ALL_STATIC --global
gcloud compute url-maps add-path-matcher edge --global --path-matcher-name=media \
--default-backend-bucket=media --new-hosts=media.example.com- The rule stays on everywhere. Only tagged resources may be public, and only people with Tag User on that one tag can attach it. Who can make something public becomes a single, auditable permission.
- Read, not list.
legacyObjectReaderopens a file by its exact name. The usualobjectVieweralso lets anyone enumerate the whole bucket, which is how "private" drafts in a public bucket leak. - Production inherits it. The policy lives on the organisation, so a new project only tags its own media bucket.
- Paid content stays out. Anything behind a paywall is served by short-lived signed URLs from a private bucket, never from the public one.
What makes it scale
Security was the loud requirement; scale is the quiet one. These are the knobs that matter, and why each one is set the way it is.
| Knob | Setting | Why |
|---|---|---|
| Stateless containers | no local state, sessions in Redis | any instance can serve any request, so scaling out is free |
| Min instances | 1 for the API, 0 for frontend and worker | no cold start on the API; idle things cost nothing |
| Max instances | a deliberate cap | protects the database from a stampede and the bill from a bug |
| Concurrency | ~80 per API instance | fewer instances for I/O-bound work, without starving CPU |
| DB connections | max instances × pool size < max_connections | the most common way serverless breaks a database |
| Queue | bounded concurrency, retries with backoff | bursts become a backlog, not an outage |
| Frontend | CDN + immutable hashed assets | most requests never reach a container |
| Images | public bucket behind Cloud CDN | the heaviest bytes never touch the API at all |
| Edge rate limits | per-IP throttle | one noisy client can't eat everyone's capacity |
| Next steps | HA database, read replicas, a second region | when traffic asks for it, not before |
What went wrong (so I remember)
| Symptom | Cause | Lesson |
|---|---|---|
| Certificate stuck in FAILED_NOT_VISIBLE | one unsupported flag stopped the script, so the URL map, HTTPS proxy and :443 rule were never created | a certificate can't validate without the full load-balancer chain; check every piece exists before blaming DNS |
| allUsers binding refused | organisation policy: domain-restricted sharing | load-balancer-only ingress + --no-invoker-iam-check for services; a tag-scoped exception for the one public bucket |
| Images 403 on the media host | the bucket was private and Cloud CDN's fill agent doesn't exist until signed URLs are set up | decide early whether a bucket is public by design; don't half-build a private CDN origin |
| Big uploads failed in the cloud, worked locally | the bucket's CORS list lacked one signed header (x-upload-content-length) | list every signed header in CORS; local storage drivers can't catch cross-origin bugs |
| A re-run stopped at a bucket grant | a bucket holding conditional grants rejects a grant without an explicit condition | pass --condition=None, and check before granting so re-runs touch nothing |
| Cloud Armor rejected a rule | its CEL subset has no "in" operator | spell out lists with ||; a failed update leaves the policy unchanged |
| An old hostname still answered | the original public API host outlived every client | retire endpoints deliberately: new cert, detach the old, delete it, then the DNS record |
| CI failed at install | a broken package-manager release pinned in the repo | pin known-good versions; let the bot propose upgrades through the same pipeline |
| Frontend deploy: memory < 512Mi not supported | the gen2 execution environment has a 512Mi floor | a static site belongs on gen1 at 256Mi: cheaper, and still sandboxed |
| Transactional email rejected | the verified sender was a subdomain, the config used the root domain | settings like this belong in the env file, so the fix is a one-line commit |
| Pasted commands silently did the wrong thing | zsh treats # comments and ! differently from bash | paste commands without comments; setopt nobanghist before expressions with ! |
| First deploy failed on a missing secret | the secret existed but had no version | the deploy script checks secrets and placeholder values before touching anything |
Checklist for production
- Its own project and its own
prod.conf: regional HA database, standard-tier Redis, HSM-backed KMS keys, long audit retention. - Agree a name for every resource (project, buckets, services, service accounts, certificates, hosts) before creating any of them. Names are the contract between setup and deploy, and most can't be renamed.
- No developer can impersonate a production service account from a laptop.
- Tag only the production media bucket as public; never a project-wide exception.
- A
prodCI environment with a required reviewer, and providers locked to the release branch. - Move WAF rules from preview to enforce after reading a few weeks of dev logs.
- Turn the CLI history into Terraform, so the environment is one reviewed plan.
- Budget alerts, uptime checks and error alerting before the first real user.