Cloud and DevOps
Google Cloud (GCP)
A map of Google Cloud for a backend engineer: how projects, identity, compute, storage, messaging, networking and cost fit together, ending with a bank API on Cloud Run, Cloud SQL and Pub/Sub. This is a concepts page. There was no GCP account and no gcloud on the machine it was written on, so every gcloud and bq command and every client-library call is marked "Not run for this page"; only two small standard-library Python programs (a push handler and a cost sum) were run, and their output is pasted from those runs. Prices, quotas and limits are approximate: check the docs.
The map
Part 1 of 6 · where resources live and who pays
Organisation, folder, project
Every resource lives in exactly one project. Access and guard rails set higher up flow down the tree.
| Level | What it is | Use it for |
|---|---|---|
| Organisation | Root, tied to a company domain | Org-wide admins, organisation policies ("no public IPs", "only these regions") |
| Folder | Grouping, can nest | A team or an environment, with its own access |
| Project | The unit of isolation, quota, API enablement and billing | One per service per environment is a common shape |
Three names: a project has a display name (changeable), a project ID (bank-prod, globally unique, fixed for life) and a project number (assigned by Google). Commands take the ID.
Billing
A billing account pays for many projects; a project is linked to one billing account. Unlink it and paid services in that project stop.
| Tool | What it gives |
|---|---|
| Billing account | The payment method and the invoice. Its own IAM roles, separate from project roles. |
| Budget | Alerts at thresholds of an amount. An alert, not a cap: see cost control. |
| Billing export | Every cost line written to BigQuery, where it can be grouped by project, service, SKU and label |
Regions and zones
A region is a geographic area (asia-south1, Mumbai). A zone is one isolated failure domain inside it (asia-south1-a). Most regions have three zones.
| Scope | Survives | Examples |
|---|---|---|
| Zonal | Nothing: a zone outage takes it down | A VM, a zonal disk, a Cloud SQL instance without HA |
| Regional | Loss of one zone | Cloud Run service, subnet, Cloud SQL with HA, regional GKE cluster, regional bucket |
| Multi-region | Loss of one region | Multi-region bucket, BigQuery US or EU dataset, multi-region Spanner |
| Global | No location to choose | Project, IAM, VPC network, global load balancer, Pub/Sub topic |
Pick a region by: distance to users, data residency law, price and whether the service exists there.
Identity and access
Part 2 of 6 · who can do what on which resource
Principals, roles, policies
An allow policy is a list of bindings. Each binding says who (principals) gets what (a role) and the policy's resource says where. A role is a bundle of permissions such as pubsub.topics.publish. Policies are inherited down the hierarchy.
| Piece | Kinds | Note |
|---|---|---|
| Principal | user:, group:, serviceAccount:, a whole domain, federated identities, allUsers | Grant to groups, not to single users. allUsers means the internet. |
| Basic role | Owner, Editor, Viewer | Thousands of permissions across every service. Not for production. |
| Predefined role | roles/run.invoker, roles/cloudsql.client, roles/storage.objectViewer | One job on one service. The normal choice. |
| Deny policy | Explicit "never" | Checked before allow policies, and wins |
Interview point: allow policies are additive. A grant at folder level cannot be taken away lower down; only a deny policy or removing the grant does that.
Service accounts
A service account is the identity of a program. Code on Cloud Run, GKE or a VM gets short-lived tokens for its attached account from the metadata server, with no key file anywhere.
| Where the code runs | Where credentials come from |
|---|---|
| Cloud Run, GKE, Compute Engine | The attached service account, through the metadata server |
| Your laptop | gcloud auth application-default login, or impersonation of a service account |
| CI or another cloud | Workload Identity Federation |
| Last resort | A downloaded JSON key in GOOGLE_APPLICATION_CREDENTIALS |
Trap: a service account key is a long-lived password in a file. It leaks through repos, images and laptops, and it does not expire unless you make it. Also: a service account is a resource too, so "who may act as it" (roles/iam.serviceAccountUser, roles/iam.serviceAccountTokenCreator) is a privilege path worth reviewing.
Workload Identity, in brief
Workload Identity Federation lets a workload outside Google swap the identity token it already has for a short-lived Google token. No key is stored in the CI system.
The same idea inside GKE (Workload Identity Federation for GKE) lets a Kubernetes service account in a pod act as an IAM principal.
Trap: a pool with no attribute condition trusts every repository on that CI provider, not only yours.
Least privilege in practice
| Do | Instead of |
|---|---|
| One service account per service | The default compute service account shared by everything (it has often carried Editor) |
| Grant on the resource: this topic, this secret, this bucket | Granting on the whole project |
| Predefined roles | Owner, Editor |
| Attached accounts and federation | Downloaded keys |
| Review with the IAM recommender and audit logs | Guessing which permissions are unused |
Compute and data
Part 3 of 6 · where code runs and where state lives
Which compute
Start at the most managed option and move down only when something forces you to.
| Compute Engine | GKE | Cloud Run | Cloud Run functions | |
|---|---|---|---|---|
| You ship | A VM image | Containers and manifests | A container | Source code for one function |
| You manage | OS, patching, scaling groups | Workloads; nodes too, unless Autopilot | Nothing below the container | Nothing below the function |
| Scales to zero | No | Pods yes, the cluster no | Yes | Yes |
| Reach for it when | Special kernel, licence, GPU setup, a legacy app | Many services, sidecars, stateful sets, operators, an existing Kubernetes team | Stateless HTTP or event-driven services | Glue: react to a bucket upload or a message |
Cloud Run in one page
A service is a URL in front of immutable revisions. Each deploy makes a revision; traffic is split between revisions by percentage; instances are added and removed with load.
| Setting | Meaning | Trap |
|---|---|---|
| Concurrency | Requests one instance handles at once (default about 80) | Each instance opens its own database pool: instances times pool size must fit under the database limit |
| Min instances | Kept warm to avoid cold starts | Billed all day, even idle |
| Max instances | Ceiling on scale-out | Leave it unset and a traffic spike becomes a bill and a database overload |
| CPU allocation | By default CPU is only guaranteed while a request is being handled | Background threads stall after the response is sent |
| Request timeout | Default about 5 minutes, up to about 60 | Longer work belongs in a job or behind Pub/Sub |
| Ingress and auth | Internal only or public; IAM roles/run.invoker or open | --allow-unauthenticated makes it public to the internet |
Contract: listen on $PORT, log to stdout, handle SIGTERM, keep nothing on local disk. The same rules as the Docker page.
Cloud Storage: classes and lifecycle
Buckets hold objects. Colder classes cost less to store and more to read. Unlike some archive tiers elsewhere, every class returns data in milliseconds.
| Class | Minimum storage time | Read about | Bank example |
|---|---|---|---|
| Standard | None | Often | This month's statements |
| Nearline | 30 days | Monthly | Last quarter's statements |
| Coldline | 90 days | Quarterly | Database backups |
| Archive | 365 days | Yearly or never | Records kept for the regulator |
The policy in the diagram. The JSON was parsed with Python here; applying it was not run for this page: gcloud storage buckets update gs://bank-prod-statements --lifecycle-file=lifecycle.json.
| Bucket setting | Why |
|---|---|
| Location: region, dual-region or multi-region | Fixed at creation. Same region as the compute avoids transfer charges. |
| Uniform bucket-level access | IAM only, no per-object ACLs to audit |
| Public access prevention | Nobody can grant allUsers by mistake |
Trap: deleting or moving an object before its minimum storage time is billed as if it had stayed. Colder classes also charge per GB read. Cold storage for data that is read daily costs more than Standard.
Signed URLs
A signed URL lets someone without a Google identity read or write one object for a short time. The file bytes never pass through your API.
Not run for this page (needs credentials). The call signature was checked against google-cloud-storage 3.x.
| Fact | Consequence |
|---|---|
| Anyone holding the URL can use it until it expires | Keep the lifetime short. V4 URLs last at most 7 days. |
| It cannot be revoked on its own | Only by removing the signer's access or the object |
| Signing needs a private key | On Cloud Run there is no key file: the library must call the IAM signBlob API, which needs the Token Creator role on the service account and extra arguments (service_account_email, access_token) |
Cloud SQL
Managed PostgreSQL, MySQL or SQL Server: Google does the patching, backups and failover; you still own the schema, the queries and the connection count.
| Feature | What it does | What it does not do |
|---|---|---|
| High availability | Automatic failover to the standby, usually in about a minute | Survive a region outage, or keep connections alive during failover |
| Read replica | Scales reads, can sit in another region, can be promoted | Give fresh data: it lags |
| Backups and point-in-time recovery | Restore to a moment before the bad DELETE | Restore in place: it creates a new instance |
| Private IP | Reachable only from your VPC | Work from a laptop without a proxy or VPN |
Trap: the instance has a hard connection limit tied to its memory. A Cloud Run service scaling to 50 instances with a pool of 10 asks for 500. Cap max instances, keep pools small, or put a pooler in front.
The other databases
Default to Cloud SQL. Move only when one of these rows describes a problem you actually have.
| Service | Model | Strength | Weak spot | Bank example |
|---|---|---|---|---|
| Cloud SQL | Relational, one writer | Plain PostgreSQL or MySQL, joins, transactions | Writes scale up, not out | Accounts and transfers |
| Spanner | Relational, distributed | Strongly consistent transactions across regions, scales writes out | Cost, and schema and key design matter | A ledger served from several continents |
| Firestore | Documents | Serverless, live listeners for mobile and web, strong consistency | Every query needs an index; no joins | App settings, notification inbox |
| Bigtable | Wide-column, one row key | Huge write volume, low-latency reads by key or key range | No joins, no secondary indexes by default, bad keys cause hot spots | Card swipe events, fraud features |
| Memorystore | In-memory (Redis, Valkey, Memcached) | Sub-millisecond cache and counters | Size is bounded by memory; treat as losable | Sessions, rate limits, balance cache |
Messaging and analytics
Part 4 of 6 · Pub/Sub and BigQuery
Pub/Sub: topics and subscriptions
Publishers write to a topic. Every subscription gets its own copy of every message; subscribers on the same subscription share the work.
| Property | Default | Option |
|---|---|---|
| Delivery | At least once: duplicates happen | Exactly-once delivery on pull subscriptions. Handlers should still be idempotent. |
| Order | None | An ordering key (the account id) keeps order per key, at some cost in throughput |
| Retention | Unacked messages kept about 7 days | Longer retention, and replay to a timestamp with seek |
Trap: a subscription created after a message was published does not get that message. Create subscriptions before the first publish.
Push, pull, ack deadline, dead letters
A message stays in the subscription until it is acknowledged. If the ack deadline passes without one, it is delivered again.
| Pull | Push | |
|---|---|---|
| Who connects | The worker opens a stream to Pub/Sub | Pub/Sub sends an HTTPS POST to your URL |
| Ack is | An explicit ack() call | A success status (2xx). Anything else is a nack. |
| Flow control | The worker decides how many it holds | Pub/Sub adjusts the rate from your responses |
| Fits | Long-running workers on GKE or VMs, high throughput | Cloud Run: scales from zero on demand |
| Auth | The worker's service account has roles/pubsub.subscriber | Pub/Sub attaches an OIDC token; the endpoint requires roles/run.invoker |
| Knob | Range (approximate) | Guidance |
|---|---|---|
| Ack deadline | 10 s default, up to 600 s | Longer than the slowest normal handler. Pull client libraries extend it while your callback runs; push cannot. |
| Retry policy | Immediate, or backoff from 10 s to 600 s | Use backoff, or a failing dependency is hammered |
| Max delivery attempts | 5 to 100 | Small. Then the message goes to the dead-letter topic. |
A push handler has to decode an envelope and be safe against duplicates. This one is plain Python and was run here (Python 3.9); the output is real.
Read the last line again: a message that can never succeed is being retried. That is exactly what the dead-letter topic is for. The Pub/Sub service agent needs publish rights on the dead-letter topic and subscribe rights on the source subscription, or forwarding silently does not happen. And someone must alert on, and read, the dead-letter subscription.
BigQuery
A serverless columnar warehouse for analytics over large tables. Storage and compute are billed separately, and on-demand queries are billed by the bytes they read, not by the rows they return.
Not run for this page. A transfers table partitioned by day, clustered by account, that refuses queries with no date filter:
The arithmetic, run here as plain Python. The assumptions are in the code: a 2 TiB table, 730 daily partitions, 20 equal columns, and an on-demand price of about 6.25 US dollars per TiB (check the docs).
| Idea | Meaning |
|---|---|
| Partitioning | Splits a table by a date, timestamp or integer column. A filter on it skips whole partitions. |
| Clustering | Sorts data inside each partition by up to four columns, so filters on them read fewer blocks |
LIMIT 10 | Does not reduce bytes read on an unclustered table. The scan happens first. |
| Dry run | Reports the bytes a query would read, for free, before you run it |
| Maximum bytes billed | A per-query cap: the query fails instead of costing more |
| On-demand or capacity | Pay per TiB read, or reserve slots (compute units) for a flat rate |
| Not for | Serving API requests, single-row updates, anything needing millisecond answers |
Network and operations
Part 5 of 6 · VPC, load balancers, logs, secrets
VPC, subnets, firewall, private access
A VPC network is global. Its subnets are regional and span every zone in their region. Resources in one VPC reach each other on private addresses across regions with no extra peering.
| Firewall rule fact | Detail |
|---|---|
| Implied rules | Deny all ingress, allow all egress, at the lowest priority |
| Priority | 0 to 65535. Lower number wins. |
| Stateful | Replies to an allowed connection are allowed automatically |
| Target | All instances, a network tag, or a service account (harder to spoof than a tag) |
| Name | Solves |
|---|---|
| Private Google Access | A VM with no public IP calling Google APIs (Storage, Pub/Sub). A switch on the subnet. |
| Private services access | A private IP for a Google-managed service in your VPC, such as Cloud SQL |
| Cloud NAT | Outbound internet for resources with no public IP. Billed per GB processed. |
| Direct VPC egress, or a connector | Cloud Run reaching private addresses in the VPC |
Coming from AWS: there a VPC is regional and a subnet sits in one zone. Here the VPC is global and a subnet is regional. A new project's default network has a subnet in every region and permissive rules; production projects use a custom-mode VPC.
Load balancers
Three questions pick one: is it HTTP, is the client on the internet, and do you need one address worldwide.
The global external Application LB gives one anycast IP worldwide, routes to the nearest healthy region and carries managed TLS, Cloud CDN and Cloud Armor (WAF, rate limits). A passthrough LB is regional and does not terminate the connection.
Cloud Run: a service already has an HTTPS URL. Put an Application LB in front (through a serverless network endpoint group) when you need a custom domain with Cloud Armor, CDN, or several regions behind one address. Then set the service's ingress to "internal and load balancing" so the LB cannot be bypassed.
Cloud Logging and Monitoring
Anything a Cloud Run or GKE container writes to stdout becomes a log entry. The Log Router then decides where each entry goes, and what is dropped before you pay to store it.
Print one JSON object per line: severity sets the level and the other keys become searchable fields.
| Piece | Use |
|---|---|
| Cloud Monitoring metrics | Built-in per service (request count, latency, instance count, Cloud SQL connections, Pub/Sub backlog), plus your own |
| Audit logs | Admin Activity (who changed what) is always on. Data Access (who read what) is mostly off by default and can be large. |
Two alerts worth having first: the age of the oldest unacked message on each subscription, and any message arriving on a dead-letter subscription. The wider picture is on the observability page.
Secret Manager
A secret is a name with numbered, immutable versions. Access is an IAM role on that one secret, and every read lands in the audit log if Data Access logs are on.
Rotation: add version 2, move readers to it, disable version 1, wait, then destroy it. Disable is reversible; destroy is not.
Not run for this page.
| Choice | Trade-off |
|---|---|
| Pin a version number | Deploys are repeatable; rotation needs a new deploy |
Use latest | Rotation needs no config change; a bad new version reaches every new instance |
| Cloud Run env var from a secret | Simple; read once when the instance starts |
| Cloud Run mounted file | Can pick up a new version without a redeploy when latest is used |
Trap: echo adds a newline to the secret; printf '%s' does not. And a secret printed in a log line is now stored in Cloud Logging, by default for about 30 days.
Cost and a reference design
Part 6 of 6 · the bill, the bank API, and the recap
Cost control
A budget only sends alerts. Nothing stops spending unless you build it, so the real controls are quotas, max instances, per-query caps and someone reading the export.
| Lever | How it helps |
|---|---|
| Budgets with alerts | Email or Pub/Sub at 50, 90, 100 percent of actual or forecast spend |
| Labels and billing export | Labels such as service=bank-api appear in the export, which answers "which service and team spent this" |
| Committed use discounts | Commit to one or three years of a resource or a spend level for a large discount. You pay whether you use it or not. |
| Spot VMs | Much cheaper, can be taken away at short notice: batch work only |
| Common bill surprise | Why it happens | Guard |
|---|---|---|
| Network egress | Data leaving to the internet or another region is billed per GB | Same region for chatty services, CDN for downloads |
| Cloud NAT | Billed per GB processed, including image pulls and API calls that could have stayed private | Private Google Access |
| Logging | Ingestion is billed per GB beyond a free allowance; debug logs and health checks add up | Exclusion filters, sample noisy logs |
| BigQuery | SELECT * on a big table, a dashboard refreshing every minute | Partition filter required, maximum bytes billed |
| Cloud SQL | Runs all day; HA roughly doubles it; each replica is another instance; storage auto-grows and never shrinks | Small dev instances, stopped when idle |
| Leftovers | Unattached disks, snapshots, reserved IPs, old container images, forgotten test projects | Labels with an owner, delete whole projects |
| Retry loops | A poison message or a crash loop runs compute around the clock | Dead-letter topic, max instances |
Reference architecture: the bank API
One region, one project per environment. The API commits the transfer to Cloud SQL and publishes an event; slow work happens behind Pub/Sub.
| Identity | Role | On |
|---|---|---|
bank-api | roles/cloudsql.client | The project (this role is project-level) |
roles/pubsub.publisher | Topic transfers | |
roles/secretmanager.secretAccessor | Secret db-password | |
bank-worker | roles/cloudsql.client | The project |
roles/storage.objectCreator | Bucket bank-prod-statements | |
pubsub-push | roles/run.invoker | Service bank-worker |
| Question an interviewer asks | Answer in this design |
|---|---|
| The publish fails after the commit? | The outbox row is still there; a relay publishes it later. Never publish first and commit second. |
| The same event arrives twice? | The worker writes with a unique key and treats a conflict as success |
| A zone goes down? | Cloud Run is regional; Cloud SQL fails over to the standby; clients retry with the same idempotency key |
| A region goes down? | Not covered. It needs a cross-region replica, a second Cloud Run region behind the global LB, and a decision about lost writes. |
| Traffic grows ten times? | Cloud Run scales out; the database connection limit is hit first. Pooler, read replica, then consider Spanner. |
Deploying it
Not run for this page. The shape of the two commands that matter; in a real team this lives in Terraform and a CI pipeline (see the CI/CD page).
Why these flags: the commit tag makes rollback a traffic move to the previous revision; --service-account avoids the default compute account; --max-instances protects the database and the bill; the push auth account lets the worker stay private. A public API would sit behind the load balancer and check its own user tokens.
GCP, AWS and Azure names
Nearest equivalents, not exact matches. Sister pages: AWS and Azure.
| Need | GCP | AWS | Azure |
|---|---|---|---|
| Isolation and billing unit | Project | Account | Subscription, resource group |
| Identity for a workload | Service account | IAM role | Managed identity |
| Virtual machines | Compute Engine | EC2 | Virtual Machines |
| Managed Kubernetes | GKE | EKS | AKS |
| Serverless containers | Cloud Run | ECS on Fargate, App Runner | Container Apps |
| Functions | Cloud Run functions | Lambda | Azure Functions |
| Object storage | Cloud Storage | S3 | Blob Storage |
| Managed relational | Cloud SQL | RDS | Azure SQL, Azure Database for PostgreSQL |
| Globally distributed database | Spanner | Aurora DSQL, DynamoDB global tables | Cosmos DB |
| Managed Redis | Memorystore | ElastiCache | Azure Cache for Redis |
| Messaging | Pub/Sub | SNS with SQS | Service Bus, Event Grid |
| Warehouse | BigQuery | Redshift, Athena | Synapse, Fabric |
| Private network | VPC (global) | VPC (regional) | Virtual Network (regional) |
| Layer 7 load balancer | Application Load Balancer | ALB | Application Gateway, Front Door |
| Logs and metrics | Cloud Logging, Cloud Monitoring | CloudWatch | Azure Monitor |
| Secrets and keys | Secret Manager, Cloud KMS | Secrets Manager, KMS | Key Vault |
Cheat sheet: gcloud
Not run for this page. PROJECT, REGION and the resource names are placeholders.
| Task | Command |
|---|---|
| Log in as yourself | gcloud auth login |
| Credentials for local code | gcloud auth application-default login |
| Set the default project | gcloud config set project PROJECT |
| Who has access | gcloud projects get-iam-policy PROJECT |
| Grant a role on a project | gcloud projects add-iam-policy-binding PROJECT --member=group:team@example.com --role=roles/viewer |
| List services | gcloud run services list |
| Roll back | gcloud run services update-traffic bank-api --to-revisions=REVISION=100 |
| Recent errors | gcloud logging read 'resource.type="cloud_run_revision" AND severity>=ERROR' --limit=20 --freshness=1h |
| Publish a test message | gcloud pubsub topics publish transfers --message='{"transfer_id":"T-1","amount":500}' |
| Read a secret | gcloud secrets versions access latest --secret=db-password |
| Estimate a query | bq query --dry_run --use_legacy_sql=false 'SELECT ...' |
Habit: pass --project explicitly in scripts. The configured default is how a command meant for dev lands in prod.
Interview questions
| Question | Short answer |
|---|---|
| How does IAM inheritance work? | Allow policies at organisation, folder, project and resource are added together. A lower level cannot remove a higher grant; a deny policy can. |
| Why avoid service account keys, and what replaces them? | They are long-lived secrets that leak. On GCP the attached service account gets short-lived tokens from the metadata server; in CI, Workload Identity Federation exchanges the CI's own OIDC token. |
| Is Pub/Sub exactly once? | At least once by default, so consumers must be idempotent. Exactly-once delivery exists for pull subscriptions, but side effects in your own systems still need idempotency. |
| What happens when a subscriber does not ack? | After the ack deadline the message is redelivered, with backoff if configured, until it expires or reaches max attempts and goes to the dead-letter topic. |
| How do you cut a BigQuery bill? | Partition and cluster, require a partition filter, select only needed columns, dry-run, cap bytes billed, consider capacity pricing for steady load. |
| Does Cloud SQL HA protect against a region failure? | No. HA is a standby in another zone. Region failure needs a cross-region replica that you promote, accepting some lost writes. |
| How is a GCP VPC different from an AWS VPC? | It is global, with regional subnets, so regions talk privately without peering. Firewall rules attach to the network and target tags or service accounts. |
| The bill doubled. Where do you look? | Billing export grouped by service, SKU and label. Usual causes: egress, NAT, logging volume, BigQuery scans, forgotten instances, a retry loop. |
Back to Cloud and DevOps.