Learnings

Cloud and DevOps

AWS

The AWS services a backend engineer meets first, each with one diagram or table and its Google Cloud equivalent, ending in a reference design for a small bank API. No AWS account was used: every aws command that calls AWS is marked "Not run for this page". What was run: two local Python programs (their output is pasted), every JSON document was parsed, and every CLI flag was checked against the help text of aws-cli 2.31.8. Prices, quotas and limits are approximate; check the docs.

Accounts and regions

Part 1 of 6 · where things live and who pays

Sister pages: the same tour for Google Cloud and Azure.

Accounts and Organizations

Accounts and regions

An account is the hard wall: its own resources, its own IAM, its own bill. Teams use many accounts, grouped by an Organization, so that a mistake in dev cannot touch prod.

One Organization. Accounts sit in organizational units (OUs), and guardrails attach to an OU.
AWSWhat it isGCP equivalent
AccountIsolation and billing unit, 12-digit idProject
Organization, OUTree of accounts, one consolidated billOrganization, folders
Service control policy (SCP)Limits what any identity in an account can do. Grants nothing.Organization Policy, deny policies
Root userThe email login that owns an accountNo direct equivalent
IAM Identity CenterSingle sign-on for people into many accountsCloud Identity, Workforce Identity

Root user: turn on MFA, create no access keys, and do not use it for daily work. SCPs do not restrict the management account, so run no workloads there.

Regions and availability zones

Accounts and regions

A region is a separate copy of AWS in one geography. An availability zone (AZ) is one or more data centres with their own power and network. Spreading over AZs survives a building; spreading over regions survives a geography.

AZs in a region are tens of kilometres apart with low-latency private links between them.
ScopeExamplesGCP note
GlobalIAM, Organizations, Route 53, CloudFrontIAM is global too
RegionalVPC, S3 bucket data, SQS, Lambda, DynamoDB, ECRA GCP VPC is global, its subnets are regional
ZonalSubnet, EC2 instance, EBS volume, NAT gatewayA GCP subnet spans all zones of its region

Trap: AZ names are shuffled per account. Your 1a may be another account's 1b; compare AZ ids (aps1-az1) across accounts.

IAM

Part 2 of 6 · who can do what to which resource

Users, roles and policies

IAM

A user has long-lived credentials. A role has none: something assumes it and gets keys that expire. Prefer roles everywhere.

AWSWhat it isGCP equivalent
IAM userA person or script with a password or access keysGoogle account, service account key
RoleAn identity with no credentials of its own, assumed for a short timeService account
Identity policyJSON attached to a user, group or role: what it may doRole binding on a resource
Resource policyJSON on a bucket, queue or key: who may use itResource-level IAM policy
Trust policyThe resource policy of a role: who may assume itserviceAccountUser, token creator
Permissions boundaryA ceiling on what an identity policy can grantDeny policies, conditions

Difference: in AWS a policy is attached to an identity and lists resources. In GCP a binding is attached to a resource and lists identities.

A policy document

IAM · JSON parsed, not applied to an account

The policy on the role the bank API runs as. Each statement is an effect, a list of actions and the exact resources. 111122223333 is the placeholder account id from the AWS docs.

Least privilege habitWhy
Name actions, not s3:*A leaked key can then read, not delete
Name resource ARNs, not "*"One service cannot read another's bucket
One role per serviceThe blast radius is one service
Start from access denied, add what failsIAM Access Analyzer can also draft a policy from CloudTrail history
Conditions (aws:SourceVpce, aws:PrincipalOrgID)Right identity from the wrong place is still refused

How a request is decided

IAM · Python run locally

Everything starts denied. An explicit deny anywhere wins. Otherwise every layer that applies must allow.

Simplified, for a request inside one account. Across accounts both sides must allow: the caller's identity policy and the resource policy.

The core rule for one policy, as a toy evaluator using the statements above. It is not the AWS engine: no conditions, no NotAction, one policy type.

Real check: aws iam simulate-principal-policy asks the real engine the same question (see the cheat sheet).

Assuming a role

IAM · JSON parsed, not applied

The caller asks STS for the role. STS checks the role's trust policy and returns keys that expire, by default after one hour.

Two checks: the trust policy says who may become the role, the role's policies say what it may do.
Where the code runsHow it gets the roleGCP equivalent
EC2Instance profile: a wrapper that attaches one role to the instance. Keys come from the metadata service (use IMDSv2).Service account attached to the VM
ECS taskTask role (your code) and execution role (pull image, write logs, read secrets)Cloud Run service identity
LambdaExecution roleFunction service account
EKS podPod Identity or IRSAWorkload Identity
Another accountsts:AssumeRole on a role whose trust policy names your accountService account impersonation
CI outside AWSOIDC federation, AssumeRoleWithWebIdentityWorkload Identity Federation

Rule: the SDK finds these credentials by itself. Access keys in environment files or images are the thing to remove.

Compute

Part 3 of 6 · where the code runs

Which compute

Compute

Pick the highest level that fits. Every step down buys control and costs operations work.

A long-running HTTP API in a container with a small team usually lands on ECS on Fargate.
ServiceYou manageBilled byGCP equivalent
EC2OS, patching, scaling groupsInstance secondCompute Engine
ECS on FargateTask definition onlyvCPU and GB per secondCloud Run
EKSKubernetes objects, add-ons, upgradesCluster hour plus nodesGKE
LambdaA functionRequests and GB-secondsCloud Run functions

Rough guide: Fargate costs more per vCPU than EC2, and Lambda more than Fargate at steady high load. Low or spiky traffic reverses that order.

ECS, Fargate and ECR

Compute · Not run for this page

ECR stores the image. A task definition says how to run it, and a service keeps N copies running behind a load balancer.

ECS wordMeaningKubernetes word
ClusterA named group of capacityCluster
Task definitionVersioned recipe: image, CPU, memory, roles, env, logsPod spec
TaskOne running copy, with its own network interface on FargatePod
ServiceKeeps N tasks healthy, rolls out new revisions, registers them with the ALBDeployment plus Service
ECR repositoryPrivate image registry, scan on push, lifecycle rules for old tags (GCP: Artifact Registry)Image registry

Tags: deploy an immutable tag (the commit) or a digest, never latest. Turn on tag immutability on the repository. Image building is covered in Docker.

Lambda

Compute

A function that AWS runs when an event arrives, scaled by running more copies. The first call on a new copy pays a cold start.

The cold path adds roughly 100 ms to a few seconds, depending on runtime and package size.
Trigger typeExamplesOn failure
SynchronousAPI Gateway, ALB, function URLThe caller gets the error
AsynchronousS3 event, SNS, EventBridgeTwo retries, then a failure destination or DLQ if configured
Polled (event source mapping)SQS, Kinesis, DynamoDB StreamsThe batch returns to the source and is retried
Limit (approximate, check the docs)Value
Timeout15 minutes
Memory128 MB to about 10 GB; CPU scales with it
Synchronous request and responseAbout 6 MB
Package250 MB unzipped, or a container image up to 10 GB
Concurrent executions1,000 per region by default, a soft quota
  • Cut cold starts: small package, clients created outside the handler, provisioned concurrency, SnapStart where the runtime supports it.
  • Lambda in front of a relational database opens a connection per copy. Use RDS Proxy or cap concurrency.

Storage, databases and messaging

Part 4 of 6 · S3, RDS, DynamoDB, SQS and SNS

S3 classes, lifecycle and versioning

Storage, databases and messaging · JSON parsed, not applied

S3 stores objects under keys in a bucket. The storage class trades price per GB against retrieval cost and speed, and a lifecycle rule moves objects down as they age.

ClassUse forCatchGCP equivalent
StandardActive dataHighest price per GBStandard
Intelligent-TieringUnknown access patternSmall monitoring fee per objectAutoclass
Standard-IAMonthly accessRetrieval fee, 30-day minimumNearline
Glacier Instant RetrievalQuarterly access, millisecond reads90-day minimumColdline
Glacier Flexible RetrievalBackupsMinutes to hours to restoreArchive (reads are instant there)
Glacier Deep ArchiveCompliance copiesAbout 12 hours to restore, 180-day minimumArchive
The rule below, for monthly statements. Minimum durations are approximate; check the docs.
  • Versioning keeps every overwrite, and a delete only adds a delete marker. It protects against mistakes and is required for replication.
  • Old versions are billed in full. Always pair versioning with NoncurrentVersionExpiration.

Presigned URLs

Storage, databases and messaging · Python run locally

The API signs a URL with its own credentials and hands it to the client, who talks to S3 directly. Signing is local arithmetic; S3 is not contacted until the client uses the URL.

Large files never pass through the API. The same works for uploads with a presigned PUT.

What the SDK does, using the example key pair and request published in the AWS Signature Version 4 docs. The last line confirms the result equals the signature printed there.

  • In real code: boto3 generate_presigned_url, or aws s3 presign. Maximum lifetime is 7 days, and the URL dies earlier if the role session that signed it expires.
  • Anyone holding the URL has that one permission. Keep the lifetime in minutes.
  • GCP equivalent: signed URLs on Cloud Storage.

Bucket policy and public access

Storage, databases and messaging · JSON parsed, not applied

A bucket policy is a resource policy. This one refuses plain HTTP for everyone and lets one role in an audit account (444455556666) read one prefix.

Public-access mistakeDo this instead
Turning off Block Public Access to host a site or share a fileKeep it on at account level. Serve through CloudFront with origin access control, or presign.
"Principal": "*" with Allow and no conditionName the role, or add aws:PrincipalOrgID
Granting s3:ListBucket to the worldReaders who know a key do not need to list
Object ACLs set to public-readLeave ACLs disabled (the default for new buckets)
Presigned URLs valid for days, pasted in chatsMinutes, generated per request

Encryption: objects are encrypted at rest by default (SSE-S3). Use a KMS key when you need to control or audit who can decrypt.

RDS and Aurora

Storage, databases and messaging

RDS runs PostgreSQL or MySQL for you: backups, patching, failover. Aurora is AWS's own storage layer under the same wire protocols.

Multi-AZ is for availability: the standby takes over on failure. A read replica is for scale, and it lags.
RDSAurora
StorageEBS volume per instanceShared cluster volume, six copies over three AZs
FailoverAbout one to two minutesUsually under a minute
Read replicasA few, each with its own storage and lagUp to 15, same storage, small lag
CostLower at small sizeHigher base, I/O priced separately unless I/O-Optimized
GCP equivalentCloud SQLAlloyDB (Spanner for global writes)

Both: point-in-time restore within the backup window (up to about 35 days) creates a new instance; it does not rewind the old one. Numbers approximate.

DynamoDB and ElastiCache

Storage, databases and messaging

DynamoDBElastiCache
WhatServerless key-value and document tableManaged Valkey, Redis OSS or Memcached
AccessBy partition key, optional sort key, secondary indexesBy key, plus Redis data types
Pay forRequests (on-demand) or provisioned capacity, plus storageNode hours, or serverless usage
Good forIdempotency keys, sessions, ledgers by account idCache, rate limits, locks
Bad forAd hoc queries and joins; items over about 400 KBThe only copy of data
GCP equivalentFirestore, BigtableMemorystore

DynamoDB rule: list the queries first, then design the keys. Patterns for the cache are in Caching Strategies.

SQS: standard and FIFO

Storage, databases and messaging

A queue between the API and its workers. The API returns at once; workers pull at their own pace.

StandardFIFO (name ends .fifo)
DeliveryAt least once, duplicates possibleDuplicates removed within a 5-minute window
OrderBest effortStrict inside one MessageGroupId
ThroughputPractically unlimitedAbout 300 calls per second per API action, more with batching or high-throughput mode
Use forEmails, statements, anything idempotentTransfers per account: group id = account id
Setting (from the CLI help)DefaultRange
Visibility timeout30 s0 to 12 hours
Retention4 days1 minute to 14 days
Maximum message size1 MiB1 KiB to 1 MiB
Receive wait (long polling)0 s0 to 20 s
Delay0 s0 to 15 minutes

GCP equivalent: a Pub/Sub pull subscription, or Cloud Tasks. Queue patterns in depth: Task Queues.

Visibility timeout and dead-letter queue

Storage, databases and messaging · JSON parsed, not applied

Receiving does not remove a message, it hides it. The worker deletes it after success. If the worker dies, the message reappears when the timeout ends.

Set the timeout above the slowest processing time, or a second worker starts the same job.
A poison message stops cycling after maxReceiveCount and waits where a person can look at it.
  • Handlers must be idempotent: at-least-once means a transfer message can arrive twice. Carry a transfer id and check it.
  • Long jobs extend their own timeout with ChangeMessageVisibility.
  • Give the DLQ the longest retention and an alarm on any visible message.

SNS and fan-out

Storage, databases and messaging

SNS pushes one published message to every subscriber. Put a queue per consumer behind the topic and each one gets its own copy, its own retries and its own DLQ.

Adding a fourth consumer is a new subscription. The publisher does not change.

GCP equivalent: Pub/Sub does both jobs: a topic with one subscription per consumer. Also: EventBridge routes events by content rules and suits many event types from many sources. Kinesis and MSK are ordered logs you can replay.

Networking

Part 5 of 6 · VPC, firewalls, load balancers

VPC, subnets and gateways

Networking

A VPC is a private address range in one region. A subnet is a slice of it in one AZ, and its route table decides whether it is public.

One AZ shown. Repeat the three subnets in at least two AZs.
SubnetRoute for 0.0.0.0/0Holds
PublicInternet gatewayLoad balancers, NAT gateways
PrivateNAT gatewayTasks, instances, Lambda
IsolatedNoneDatabases, caches
AWSWhat it doesGCP equivalent
Internet gatewayTwo-way door for resources with public IPsDefault internet gateway route
NAT gatewayOutbound-only internet for private subnets, one per AZCloud NAT
VPC endpointPrivate path to S3, SQS, ECR without NATPrivate Google Access, Private Service Connect

Related: CIDR, routing and NAT themselves are in Linux Networking.

Security groups and NACLs

Networking

Security groupNetwork ACL
Attached toA network interface (task, instance, RDS, ALB)A subnet
StateStateful: replies are allowed automaticallyStateless: allow the return ports too
RulesAllow onlyAllow and deny
EvaluationAll rules togetherBy rule number, first match wins
Source can beCIDR or another security groupCIDR only

Chain groups by reference, not by IP: the database group allows 5432 only from the task group, and the task group allows 8000 only from the ALB group.

GCP equivalent: VPC firewall rules. They are stateful, support allow and deny with priorities, and target tags or service accounts.

ALB and NLB

Networking

Application LBNetwork LB
Layer7: HTTP, HTTPS, gRPC, WebSocket4: TCP, UDP, TLS
Routes byHost, path, header, methodPort
AddressDNS name, IPs changeOne static IP per AZ
Client IPIn X-Forwarded-ForPreserved at the socket
ExtrasWAF, redirects, OIDC login, Lambda targetsVery high throughput, PrivateLink
Use forThe bank APIDatabases, MQTT, anything not HTTP, fixed IP allow-lists
GCP equivalentApplication Load BalancerNetwork Load Balancer
  • Targets sit in a target group with a health check. A failing target stops receiving traffic.
  • Set the deregistration delay and handle SIGTERM so deploys do not drop requests.
  • Algorithms and health checks in depth: Nginx and Load Balancing.

Operate and design

Part 6 of 6 · watch it, keep its secrets, pay for it

CloudWatch

Operate and design

PartWhat it holdsGCP equivalent
LogsLog groups of streams. Retention is "never expire" until you set it.Cloud Logging
MetricsNumbers by namespace and dimensions, one-minute by defaultCloud Monitoring
AlarmsA metric against a threshold: OK, ALARM, INSUFFICIENT_DATA. Actions go to SNS or auto scaling.Alerting policies
CloudTrail (separate service)Who called which AWS API, and whenCloud Audit Logs
Alarm for the bankMetric
API errorsALB HTTPCode_Target_5XX_Count
API slowALB TargetResponseTime, p99
Workers falling behindSQS ApproximateAgeOfOldestMessage
Poison messagesDLQ ApproximateNumberOfMessagesVisible above 0
Database fillingRDS FreeStorageSpace, DatabaseConnections

Related: what to measure and how to set thresholds is in Observability.

Secrets Manager and Parameter Store

Operate and design

Secrets ManagerParameter Store (SSM)
ForDatabase passwords, API keysConfig values, feature flags, some secrets
RotationBuilt in, managed for RDSNone; do it yourself
SizeAbout 64 KB4 KB standard, 8 KB advanced
Price (approximate)About $0.40 per secret per month plus API callsStandard tier free
GCP equivalentSecret ManagerParameter Manager
  • ECS injects either one as an environment variable through secrets in the task definition (see below). The execution role needs read access.
  • An injected value is read at task start. After a rotation, restart tasks or fetch the secret in code with a short cache.

Cost control

Operate and design · all prices approximate, us-east-1, check the docs

ToolWhat it doesGCP equivalent
Tagsservice, env, team on everything. Activate them as cost allocation tags or they do not appear on the bill.Labels
BudgetsAlert on actual or forecast spend. An alert does not stop spending.Billing budgets
Savings PlansCommit to dollars per hour for 1 or 3 years. Compute plans cover EC2, Fargate and Lambda.Committed use discounts
SpotSpare capacity at a deep discount, reclaimed with two minutes' noticeSpot VMs
Bill surpriseWhyFix
NAT gatewayAbout $0.045 per hour each, plus about $0.045 per GB through itVPC endpoints for S3, ECR, SQS, logs; one NAT in non-prod
Data transfer outAbout $0.09 per GB to the internetCloudFront, compression
Cross-AZ trafficAbout $0.01 per GB each wayKeep chatty services in the same AZ where safe
CloudWatch LogsIngestion per GB, kept forever by defaultSet retention, drop debug logs
Public IPv4Every address is billed per hourPrivate subnets behind one ALB
Idle resourcesUnattached EBS volumes, old snapshots, forgotten load balancersTag, then review untagged spend
S3 leftoversOld versions and incomplete multipart uploadsThe lifecycle rule

Order of work: tag, look at Cost Explorer, delete idle things, right-size, and only then commit to a Savings Plan.

Reference architecture

Operate and design · a design, not deployed; JSON keys checked against the CLI skeleton

The bank API: transfers are accepted by the API, queued, and applied by workers inside a database transaction.

Two ECS services from one image. Workers scale on queue depth, the API on CPU or request count.
DecisionReason
Fargate, two AZs, at least two tasks eachNo hosts to patch; survives one AZ
Queue between API and ledgerSpikes are absorbed; a worker crash loses nothing
Transfer id as idempotency key, unique in the databaseSQS can deliver twice
Balance change in one SQL transactionThe database, not the queue, guards the money
Task role and execution role separateApp code cannot pull images or read other secrets

In practice: all of this is written as Terraform or CloudFormation, not clicked. On GCP the same shape is Cloud Run, Cloud SQL, Pub/Sub and Cloud Storage.

CLI cheat sheet

Operate and design · Not run for this page; flags checked against aws help

Every command takes --profile, --region, --output json|table|text and --query (a JMESPath filter).

TaskCommand
Who am Iaws sts get-caller-identity
Set up and log in with SSOaws configure sso, then aws sso login --profile bank-dev
Would this be allowedaws iam simulate-principal-policy --policy-source-arn ROLE_ARN --action-names s3:GetObject --resource-arns OBJECT_ARN
List, copy, syncaws s3 ls s3://bank-statements/, aws s3 cp f.pdf s3://bank-statements/, aws s3 sync ./out s3://bank-statements/out --delete
Presign for 5 minutesaws s3 presign s3://bank-statements/a.pdf --expires-in 300
Block public accessaws s3api put-public-access-block --bucket bank-statements --public-access-block-configuration BlockPublicAcls=true,IgnorePublicAcls=true,BlockPublicPolicy=true,RestrictPublicBuckets=true
Roll an ECS serviceaws ecs update-service --cluster bank --service bank-api --force-new-deployment
Shell into a taskaws ecs execute-command --cluster bank --task TASK_ID --container api --interactive --command /bin/sh
Follow logsaws logs tail /ecs/bank-api --follow --since 10m
Queue depthaws sqs get-queue-attributes --queue-url URL --attribute-names ApproximateNumberOfMessages
Redrive a DLQaws sqs start-message-move-task --source-arn DLQ_ARN
Read a secretaws secretsmanager get-secret-value --secret-id bank/db --query SecretString --output text
Spend by serviceaws ce get-cost-and-usage --time-period Start=2026-11-01,End=2026-12-01 --granularity MONTHLY --metrics UnblendedCost --group-by Type=DIMENSION,Key=SERVICE

Interview questions

Operate and design

QuestionShort answer
User versus role?A user has long-lived credentials. A role is assumed and yields temporary ones. Workloads and people should both use roles. More
An identity policy allows it and the call is denied. Why?An explicit deny somewhere, an SCP, a permissions boundary, a missing resource policy across accounts, or a KMS key policy. More
Task role versus execution role?Execution role: ECS pulls the image, writes logs, reads secrets. Task role: what your code may call. More
Lambda or Fargate for an API?Lambda for spiky or low traffic and short work. Fargate for steady load, long requests, many database connections. More
Let a browser upload a 2 GB file?Presigned PUT or multipart URLs straight to S3; the API only signs and records. More
Multi-AZ versus read replica?Multi-AZ is a synchronous standby for failover. A replica is asynchronous, for read scale, and can lag. More
How do you avoid applying a transfer twice from SQS?Idempotent handler: unique transfer id in the database, checked in the same transaction. FIFO narrows duplicates but does not remove the need. More
SQS, SNS or both?SQS for one consumer group and buffering. SNS to copy an event to many. Fan-out is SNS into one queue per consumer. More
Security group versus NACL?Stateful allow-list on an interface, versus stateless ordered allow and deny on a subnet. More
The bill doubled. Where do you look?Cost Explorer by service and usage type: NAT gateway bytes, data transfer, log ingestion, idle resources. More

Back to Cloud and DevOps. Next: Google Cloud and Azure.