Learnings

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

The map

Every resource lives in exactly one project. Access and guard rails set higher up flow down the tree.

An allow policy on a folder applies to every project and resource under it.
LevelWhat it isUse it for
OrganisationRoot, tied to a company domainOrg-wide admins, organisation policies ("no public IPs", "only these regions")
FolderGrouping, can nestA team or an environment, with its own access
ProjectThe unit of isolation, quota, API enablement and billingOne 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

The map

A billing account pays for many projects; a project is linked to one billing account. Unlink it and paid services in that project stop.

ToolWhat it gives
Billing accountThe payment method and the invoice. Its own IAM roles, separate from project roles.
BudgetAlerts at thresholds of an amount. An alert, not a cap: see cost control.
Billing exportEvery cost line written to BigQuery, where it can be grouped by project, service, SKU and label

Regions and zones

The map

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.

ScopeSurvivesExamples
ZonalNothing: a zone outage takes it downA VM, a zonal disk, a Cloud SQL instance without HA
RegionalLoss of one zoneCloud Run service, subnet, Cloud SQL with HA, regional GKE cluster, regional bucket
Multi-regionLoss of one regionMulti-region bucket, BigQuery US or EU dataset, multi-region Spanner
GlobalNo location to chooseProject, 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

Identity and access

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.

PieceKindsNote
Principaluser:, group:, serviceAccount:, a whole domain, federated identities, allUsersGrant to groups, not to single users. allUsers means the internet.
Basic roleOwner, Editor, ViewerThousands of permissions across every service. Not for production.
Predefined roleroles/run.invoker, roles/cloudsql.client, roles/storage.objectViewerOne job on one service. The normal choice.
Deny policyExplicit "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

Identity and access

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 runsWhere credentials come from
Cloud Run, GKE, Compute EngineThe attached service account, through the metadata server
Your laptopgcloud auth application-default login, or impersonation of a service account
CI or another cloudWorkload Identity Federation
Last resortA 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

Identity and access

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 pool's attribute conditions decide which repository and branch are trusted.

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

Identity and access

DoInstead of
One service account per serviceThe default compute service account shared by everything (it has often carried Editor)
Grant on the resource: this topic, this secret, this bucketGranting on the whole project
Predefined rolesOwner, Editor
Attached accounts and federationDownloaded keys
Review with the IAM recommender and audit logsGuessing which permissions are unused

Compute and data

Part 3 of 6 · where code runs and where state lives

Which compute

Compute and data

Start at the most managed option and move down only when something forces you to.

Cloud Functions is now called Cloud Run functions and runs on the same platform.
Compute EngineGKECloud RunCloud Run functions
You shipA VM imageContainers and manifestsA containerSource code for one function
You manageOS, patching, scaling groupsWorkloads; nodes too, unless AutopilotNothing below the containerNothing below the function
Scales to zeroNoPods yes, the cluster noYesYes
Reach for it whenSpecial kernel, licence, GPU setup, a legacy appMany services, sidecars, stateful sets, operators, an existing Kubernetes teamStateless HTTP or event-driven servicesGlue: react to a bucket upload or a message

Cloud Run in one page

Compute and data

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.

SettingMeaningTrap
ConcurrencyRequests 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 instancesKept warm to avoid cold startsBilled all day, even idle
Max instancesCeiling on scale-outLeave it unset and a traffic spike becomes a bill and a database overload
CPU allocationBy default CPU is only guaranteed while a request is being handledBackground threads stall after the response is sent
Request timeoutDefault about 5 minutes, up to about 60Longer work belongs in a job or behind Pub/Sub
Ingress and authInternal 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

Compute and data

Buckets hold objects. Colder classes cost less to store and more to read. Unlike some archive tiers elsewhere, every class returns data in milliseconds.

A lifecycle policy for monthly statements. Ages count from object creation.
ClassMinimum storage timeRead aboutBank example
StandardNoneOftenThis month's statements
Nearline30 daysMonthlyLast quarter's statements
Coldline90 daysQuarterlyDatabase backups
Archive365 daysYearly or neverRecords 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 settingWhy
Location: region, dual-region or multi-regionFixed at creation. Same region as the compute avoids transfer charges.
Uniform bucket-level accessIAM only, no per-object ACLs to audit
Public access preventionNobody 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

Compute and data

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.

The bucket stays private. The URL carries the permission.

Not run for this page (needs credentials). The call signature was checked against google-cloud-storage 3.x.

FactConsequence
Anyone holding the URL can use it until it expiresKeep the lifetime short. V4 URLs last at most 7 days.
It cannot be revoked on its ownOnly by removing the signer's access or the object
Signing needs a private keyOn 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

Compute and data

Managed PostgreSQL, MySQL or SQL Server: Google does the patching, backups and failover; you still own the schema, the queries and the connection count.

HA means a standby in another zone of the same region. It serves no reads.
FeatureWhat it doesWhat it does not do
High availabilityAutomatic failover to the standby, usually in about a minuteSurvive a region outage, or keep connections alive during failover
Read replicaScales reads, can sit in another region, can be promotedGive fresh data: it lags
Backups and point-in-time recoveryRestore to a moment before the bad DELETERestore in place: it creates a new instance
Private IPReachable only from your VPCWork 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

Compute and data

Default to Cloud SQL. Move only when one of these rows describes a problem you actually have.

ServiceModelStrengthWeak spotBank example
Cloud SQLRelational, one writerPlain PostgreSQL or MySQL, joins, transactionsWrites scale up, not outAccounts and transfers
SpannerRelational, distributedStrongly consistent transactions across regions, scales writes outCost, and schema and key design matterA ledger served from several continents
FirestoreDocumentsServerless, live listeners for mobile and web, strong consistencyEvery query needs an index; no joinsApp settings, notification inbox
BigtableWide-column, one row keyHuge write volume, low-latency reads by key or key rangeNo joins, no secondary indexes by default, bad keys cause hot spotsCard swipe events, fraud features
MemorystoreIn-memory (Redis, Valkey, Memcached)Sub-millisecond cache and countersSize is bounded by memory; treat as losableSessions, rate limits, balance cache

Messaging and analytics

Part 4 of 6 · Pub/Sub and BigQuery

Pub/Sub: topics and subscriptions

Messaging and analytics

Publishers write to a topic. Every subscription gets its own copy of every message; subscribers on the same subscription share the work.

Three subscriptions: fan-out. Two workers on one subscription: load sharing.
PropertyDefaultOption
DeliveryAt least once: duplicates happenExactly-once delivery on pull subscriptions. Handlers should still be idempotent.
OrderNoneAn ordering key (the account id) keeps order per key, at some cost in throughput
RetentionUnacked messages kept about 7 daysLonger 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

Messaging and analytics

A message stays in the subscription until it is acknowledged. If the ack deadline passes without one, it is delivered again.

Without a dead-letter topic, one poison message is retried until it expires.
PullPush
Who connectsThe worker opens a stream to Pub/SubPub/Sub sends an HTTPS POST to your URL
Ack isAn explicit ack() callA success status (2xx). Anything else is a nack.
Flow controlThe worker decides how many it holdsPub/Sub adjusts the rate from your responses
FitsLong-running workers on GKE or VMs, high throughputCloud Run: scales from zero on demand
AuthThe worker's service account has roles/pubsub.subscriberPub/Sub attaches an OIDC token; the endpoint requires roles/run.invoker
KnobRange (approximate)Guidance
Ack deadline10 s default, up to 600 sLonger than the slowest normal handler. Pull client libraries extend it while your callback runs; push cannot.
Retry policyImmediate, or backoff from 10 s to 600 sUse backoff, or a failing dependency is hammered
Max delivery attempts5 to 100Small. 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

Messaging and analytics

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.

Two prunings decide the bill: which partitions, then which columns.

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).

IdeaMeaning
PartitioningSplits a table by a date, timestamp or integer column. A filter on it skips whole partitions.
ClusteringSorts data inside each partition by up to four columns, so filters on them read fewer blocks
LIMIT 10Does not reduce bytes read on an unclustered table. The scan happens first.
Dry runReports the bytes a query would read, for free, before you run it
Maximum bytes billedA per-query cap: the query fails instead of costing more
On-demand or capacityPay per TiB read, or reserve slots (compute units) for a flat rate
Not forServing 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

Network and operations

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.

Nothing here has a public address. Outbound internet goes through Cloud NAT.
Firewall rule factDetail
Implied rulesDeny all ingress, allow all egress, at the lowest priority
Priority0 to 65535. Lower number wins.
StatefulReplies to an allowed connection are allowed automatically
TargetAll instances, a network tag, or a service account (harder to spoof than a tag)
NameSolves
Private Google AccessA VM with no public IP calling Google APIs (Storage, Pub/Sub). A switch on the subnet.
Private services accessA private IP for a Google-managed service in your VPC, such as Cloud SQL
Cloud NATOutbound internet for resources with no public IP. Billed per GB processed.
Direct VPC egress, or a connectorCloud 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

Network and operations

Three questions pick one: is it HTTP, is the client on the internet, and do you need one address worldwide.

Application means layer 7. Network means layer 4.

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

Network and operations

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.

A sink is a filter plus a destination. Retention shown is the usual default.

Print one JSON object per line: severity sets the level and the other keys become searchable fields.

PieceUse
Cloud Monitoring metricsBuilt-in per service (request count, latency, instance count, Cloud SQL connections, Pub/Sub backlog), plus your own
Audit logsAdmin 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

Network and operations

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.

ChoiceTrade-off
Pin a version numberDeploys are repeatable; rotation needs a new deploy
Use latestRotation needs no config change; a bad new version reaches every new instance
Cloud Run env var from a secretSimple; read once when the instance starts
Cloud Run mounted fileCan 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

Cost and a reference design

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.

LeverHow it helps
Budgets with alertsEmail or Pub/Sub at 50, 90, 100 percent of actual or forecast spend
Labels and billing exportLabels such as service=bank-api appear in the export, which answers "which service and team spent this"
Committed use discountsCommit 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 VMsMuch cheaper, can be taken away at short notice: batch work only
Common bill surpriseWhy it happensGuard
Network egressData leaving to the internet or another region is billed per GBSame region for chatty services, CDN for downloads
Cloud NATBilled per GB processed, including image pulls and API calls that could have stayed privatePrivate Google Access
LoggingIngestion is billed per GB beyond a free allowance; debug logs and health checks add upExclusion filters, sample noisy logs
BigQuerySELECT * on a big table, a dashboard refreshing every minutePartition filter required, maximum bytes billed
Cloud SQLRuns all day; HA roughly doubles it; each replica is another instance; storage auto-grows and never shrinksSmall dev instances, stopped when idle
LeftoversUnattached disks, snapshots, reserved IPs, old container images, forgotten test projectsLabels with an owner, delete whole projects
Retry loopsA poison message or a crash loop runs compute around the clockDead-letter topic, max instances

Reference architecture: the bank API

Cost and a reference design

One region, one project per environment. The API commits the transfer to Cloud SQL and publishes an event; slow work happens behind Pub/Sub.

Every arrow out of a Cloud Run box is one IAM role on one resource.
Money moves in the database transaction. Pub/Sub only carries the news.
IdentityRoleOn
bank-apiroles/cloudsql.clientThe project (this role is project-level)
roles/pubsub.publisherTopic transfers
roles/secretmanager.secretAccessorSecret db-password
bank-workerroles/cloudsql.clientThe project
roles/storage.objectCreatorBucket bank-prod-statements
pubsub-pushroles/run.invokerService bank-worker
Question an interviewer asksAnswer 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

Cost and a reference design

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

Cost and a reference design

Nearest equivalents, not exact matches. Sister pages: AWS and Azure.

NeedGCPAWSAzure
Isolation and billing unitProjectAccountSubscription, resource group
Identity for a workloadService accountIAM roleManaged identity
Virtual machinesCompute EngineEC2Virtual Machines
Managed KubernetesGKEEKSAKS
Serverless containersCloud RunECS on Fargate, App RunnerContainer Apps
FunctionsCloud Run functionsLambdaAzure Functions
Object storageCloud StorageS3Blob Storage
Managed relationalCloud SQLRDSAzure SQL, Azure Database for PostgreSQL
Globally distributed databaseSpannerAurora DSQL, DynamoDB global tablesCosmos DB
Managed RedisMemorystoreElastiCacheAzure Cache for Redis
MessagingPub/SubSNS with SQSService Bus, Event Grid
WarehouseBigQueryRedshift, AthenaSynapse, Fabric
Private networkVPC (global)VPC (regional)Virtual Network (regional)
Layer 7 load balancerApplication Load BalancerALBApplication Gateway, Front Door
Logs and metricsCloud Logging, Cloud MonitoringCloudWatchAzure Monitor
Secrets and keysSecret Manager, Cloud KMSSecrets Manager, KMSKey Vault

Cheat sheet: gcloud

Cost and a reference design

Not run for this page. PROJECT, REGION and the resource names are placeholders.

TaskCommand
Log in as yourselfgcloud auth login
Credentials for local codegcloud auth application-default login
Set the default projectgcloud config set project PROJECT
Who has accessgcloud projects get-iam-policy PROJECT
Grant a role on a projectgcloud projects add-iam-policy-binding PROJECT --member=group:team@example.com --role=roles/viewer
List servicesgcloud run services list
Roll backgcloud run services update-traffic bank-api --to-revisions=REVISION=100
Recent errorsgcloud logging read 'resource.type="cloud_run_revision" AND severity>=ERROR' --limit=20 --freshness=1h
Publish a test messagegcloud pubsub topics publish transfers --message='{"transfer_id":"T-1","amount":500}'
Read a secretgcloud secrets versions access latest --secret=db-password
Estimate a querybq 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

Cost and a reference design

QuestionShort 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.