CL·90
Cloud Architecture
One cloud learned deeply (AWS) and the others mapped onto it: IAM, VPC, EC2, ALB/NLB, ECS/EKS, Lambda, S3, RDS and Aurora, DynamoDB, ElastiCache, MSK, CloudFront, Route 53, SQS/SNS/EventBridge, CloudWatch, Secrets Manager and KMS, each with its model, sweet spot and pitfalls; then Azure and GCP equivalents service by service; reference architectures for a web application on each cloud; and multi-cloud trade-offs, with CDK, Bicep and gcloud examples.
Start here: one application, drawn as cloud services
From boxes to services
Every web application has roughly the same shape: an entry point, stateless compute, a database, files, asynchronous work, and the identity, network and monitoring around them. On a cloud you choose a managed service for each box:
| Box | AWS | Azure | Google Cloud |
|---|---|---|---|
| CDN | CloudFront | Front Door | Cloud CDN |
| Objects | S3 | Blob Storage | Cloud Storage |
| Load balancer (L7) | Application Load Balancer | Application Gateway / Front Door | External Application Load Balancer |
| Serverless containers | ECS on Fargate, App Runner | Container Apps | Cloud Run |
| Kubernetes | EKS | AKS | GKE |
| Functions | Lambda | Functions | Cloud Run functions |
| PostgreSQL | RDS, Aurora | Azure Database for PostgreSQL | Cloud SQL, AlloyDB |
| Queue / pub-sub | SQS / SNS, EventBridge | Service Bus / Event Grid | Pub/Sub, Eventarc |
| Secrets / keys | Secrets Manager / KMS | Key Vault | Secret Manager / Cloud KMS |
| Identity | IAM, IAM Identity Center | Entra ID, Azure RBAC | Cloud IAM |
| Monitoring | CloudWatch, X-Ray | Azure Monitor, App Insights | Cloud Monitoring, Cloud Trace |
| Infrastructure as code | CloudFormation, CDK | Bicep, ARM | Infrastructure Manager (Terraform) |
How much infrastructure is that?
About 30 lines of CDK describe the diagram (VPC with two zones, a load-balanced Fargate service with autoscaling, a Multi-AZ PostgreSQL instance whose secret the service may read, a queue with a dead-letter queue the service may send to, a private bucket behind CloudFront). Synthesised:
52 CloudFormation resources from about 30 lines of CDK (nat_gateways=2); template 18 KB
4 AWS::EC2::Subnet
4 AWS::EC2::RouteTable
4 AWS::EC2::SubnetRouteTableAssociation
4 AWS::EC2::Route
3 AWS::EC2::SecurityGroup
2 AWS::EC2::EIP
2 AWS::EC2::NatGateway
2 AWS::IAM::Role
2 AWS::IAM::Policy
… (VPC, gateway, ECS cluster, task definition, service, load balancer, listener, target group,
scaling target and policy, log group, DB subnet group, secret, DB instance, two queues,
bucket and policy, CloudFront distribution and origin access control)
WARNING StorageEncrypted: RDS instance should have StorageEncrypted set to true (CloudFormation Validate)
Fifty-two resources, each with its own settings, for a modest three-tier application: this is why infrastructure is written as code, reviewed like code, and why higher-level constructs (CDK patterns, Terraform modules, Bicep modules) are worth using. It's also why you must read what they generate: the synthesiser itself warned that the database's storage wasn't encrypted, a default the lab examines along with others.
Learn one cloud deeply
The concepts in chapters 85–89 are shared; the names, defaults and limits differ. The fastest route is to learn one provider's core services well enough to build and debug this diagram, then map the others with tables like the one above, paying attention to where they genuinely differ (Azure's resource groups and Entra ID; Google Cloud's global VPCs and project hierarchy; AWS's account-per-workload model).
How deep to go in cloud architecture
Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere, and its lab at L4.
| Level | What you can do |
|---|---|
| L1 | Map the boxes of an application to managed services on one cloud |
| L2 | Build the reference architecture with IaC on one cloud and operate it |
| L3 | Explain each service's limits, defaults and failure modes; map equivalents across clouds |
| L4 | Diagnose problems across services: networking, IAM, quotas, scaling, cost anomalies |
| L5 | Design architectures for requirements: multi-region, compliance, cost, portability |
| L6 | Set platform standards: landing zones, golden paths, reference architectures, multi-cloud strategy |
Learning one cloud deeply
The roadmap's advice is sound: learn one cloud deeply, then map the others onto it. The concepts (chapters 85–89) are shared; names, defaults and sharp edges differ. This chapter uses AWS as the deep reference because it's the largest and has the most granular services, then gives Azure and Google Cloud equivalents.
AWS services in depth
IAM, VPC, EC2, load balancers
Chapters 86–89 covered the foundations:
- IAM: roles everywhere, Identity Center for humans, Organizations with SCPs/RCPs, Access Analyzer.
- VPC: three-tier subnets per AZ, endpoints, security groups referencing each other, Transit Gateway for many VPCs.
- EC2: instance families, Graviton, golden AMIs, ASGs, IMDSv2, spot.
- ALB (L7: HTTP routing, gRPC, WebSockets, OIDC/Cognito authentication, WAF, Lambda targets) and NLB (L4: static IPs, very high throughput, client IP preservation, PrivateLink services). ALB idle timeout (60 s default) and deregistration delay (300 s default; usually lower it to 30–60 s) frequently need tuning.
ECS and EKS
| ECS | EKS | |
|---|---|---|
| What | AWS-native container orchestrator | Managed Kubernetes |
| Concepts | Cluster, task definition (containers, CPU/memory, IAM task role and execution role, logging), service (desired count, deployment config, load balancer), capacity providers (Fargate, Fargate Spot, EC2 ASGs) | Standard Kubernetes; managed control plane; node groups, Fargate profiles, or EKS Auto Mode; add-ons; Pod Identity |
| Deployments | Rolling with deployment circuit breaker (auto rollback), blue/green via CodeDeploy, built-in blue/green and canary/linear strategies (2025) | Kubernetes strategies + Argo Rollouts/Flagger |
| Strengths | Simpler, deep AWS integration, no control-plane fee, fast to learn | Ecosystem, portability, extensibility (operators, Helm, GitOps) |
| Pitfalls | AWS lock-in; fewer extension points | Upgrades every ~4 months, add-on maintenance, more expertise needed |
ECS Service Connect adds service discovery and an Envoy-based proxy (retries, metrics) between ECS services. Both pull images from ECR (private registry with scanning, immutability, replication, pull-through cache).
Lambda
Covered in chapter 86: event sources, execution environments, cold starts and SnapStart, concurrency controls, limits, Managed Instances and durable functions. Companions:
- API Gateway (REST and HTTP APIs, WebSocket APIs; throttling, authorisers, usage plans) or function URLs.
- Step Functions (state-machine orchestration with retries, error handling, parallel and map states; Standard for long workflows, Express for high-volume short ones).
- EventBridge Scheduler for scheduled invocations.
- Powertools for AWS Lambda (Python, TypeScript, Java, .NET) for logging, tracing, metrics, idempotency and batch handling.
S3
Chapter 88 in depth. Key AWS-specific features:
- strong consistency and conditional writes;
- storage classes including Intelligent-Tiering and Express One Zone;
- lifecycle, versioning and Object Lock;
- CRR/SRR replication;
- Block Public Access, access points and Access Grants;
- event notifications;
- S3 Tables (managed Apache Iceberg tables) and S3 Vectors (vector storage and similarity search directly in S3, generally available since December 2025, for low-cost retrieval-augmented generation (RAG) and semantic search).
RDS and Aurora
Amazon RDS runs PostgreSQL, MySQL, MariaDB, Oracle, SQL Server and Db2 as managed instances:
- Multi-AZ: a synchronous standby in another AZ with automatic failover (typically 60–120 s; DNS endpoint flips). Multi-AZ DB clusters (two readable standbys, faster failover) for PostgreSQL and MySQL.
- Read replicas (asynchronous, also cross-region) for read scaling and DR.
- Automated backups with point-in-time recovery (up to 35 days), snapshots, cross-region/account copies.
- Parameter groups, maintenance windows, Performance Insights / Database Insights, RDS Proxy (connection pooling, faster failover, IAM auth; essential for Lambda).
- Blue/green deployments for major version upgrades with a quick switchover.
Aurora (PostgreSQL- and MySQL-compatible) separates compute from a distributed storage layer that keeps six copies across three AZs, with quorum writes (4 of 6) and reads (3 of 6). Results:
- Faster failover (typically under 30 s), up to 15 low-lag replicas sharing the same storage.
- Storage grows automatically, up to 256 TiB in recent versions.
- Aurora Serverless v2 scales capacity in fine increments (including to zero for idle databases).
- Global Database gives cross-region replication with ~1 s lag and fast regional failover.
- Aurora I/O-Optimized pricing for I/O-heavy workloads.
- Aurora DSQL (announced re:Invent 2024, generally available 2025) is a distributed, active-active, serverless PostgreSQL-compatible database with strong consistency across regions, with some PostgreSQL feature restrictions.
Pitfalls: connection limits (pool!), failover handling in clients (retry on connection errors; use the cluster endpoint and drivers with fast failover support, such as the AWS Advanced JDBC/Python/Go wrappers), storage I/O cost on standard Aurora, and long-running transactions blocking vacuum (Vol. 4 ch. 59).
DynamoDB
A fully managed, serverless key-value and document database with single-digit-millisecond latency at any scale (Vol. 4 ch. 60 covers modelling):
- Tables with a partition key (and optional sort key); items up to 400 KB; GSIs (global secondary indexes, eventually consistent) and LSIs.
- Capacity modes: on-demand (pay per request; the default choice now) or provisioned with auto scaling.
- Reads are eventually consistent by default; strongly consistent reads within a region; transactions (up to 100 items); conditional writes for optimistic concurrency and idempotency.
- DynamoDB Streams (change data capture to Lambda, Kinesis), TTL (automatic expiry), PITR, global tables (multi-region active-active, LWW by default; multi-region strong consistency generally available since June 2025).
- Single-table design with composite keys, driven by access patterns, is idiomatic; hot partitions (skewed keys) and scans are the main pitfalls.
// Java: DynamoDB conditional put (idempotent create) with the enhanced client
DynamoDbTable<Order> table = DynamoDbEnhancedClient.create().table("orders", TableSchema.fromBean(Order.class));
try {
table.putItem(PutItemEnhancedRequest.builder(Order.class)
.item(order)
.conditionExpression(Expression.builder().expression("attribute_not_exists(pk)").build())
.build());
} catch (ConditionalCheckFailedException e) {
// already exists: treat as a successful duplicate
}
ElastiCache
Managed in-memory caches and data stores: Valkey (the Linux Foundation fork of Redis, now ElastiCache's recommended and lower-cost engine), Redis OSS and Memcached:
- Cluster mode with sharding and replicas across AZs, automatic failover, ElastiCache Serverless (no capacity planning), encryption, IAM authentication.
- Uses: caching (cache-aside with TTLs, stampede protection), sessions, rate limiters, leaderboards, pub/sub, distributed locks (efficiency only, Vol. 5 ch. 77).
- MemoryDB is a durable Valkey/Redis-compatible database (multi-AZ transaction log) for when the data must not be lost.
MSK
Amazon MSK runs Apache Kafka (Vol. 5 ch. 67):
- Provisioned clusters (you choose broker sizes and storage, with tiered storage) and Express brokers (generally available since November 2024: much faster scaling and recovery, no storage management, higher throughput per broker).
- MSK Serverless (pay per throughput, automatic scaling, with some limits).
- MSK Connect (managed Kafka Connect, e.g. Debezium).
- IAM authentication for clients, private connectivity, multi-VPC access.
- Alternatives on AWS: Kinesis Data Streams (AWS-native streaming with shards; simpler, less ecosystem), Confluent Cloud and Redpanda via the marketplace.
CloudFront and Route 53
- CloudFront: global CDN (chapter 87) with Origin Access Control for S3, cache policies, CloudFront Functions and Lambda@Edge, WAF and Shield integration, signed URLs/cookies, HTTP/3, VPC origins (private ALBs/instances as origins without public exposure), and mutual TLS.
- Route 53: authoritative DNS with a 100% data-plane SLA, alias records, health checks, routing policies (weighted, latency, geo, failover), private hosted zones, Resolver endpoints and DNS Firewall, plus domain registration. Route 53 Application Recovery Controller provides highly reliable routing controls and readiness checks for region failover.
SQS, SNS and EventBridge
| Service | Model | Use |
|---|---|---|
| SQS | Queue (Vol. 5 ch. 66): standard (at-least-once, best-effort order, nearly unlimited throughput) or FIFO (ordered per message group, deduplication) | Decoupling, work queues, buffering, Lambda triggers; DLQs and redrive |
| SNS | Pub/sub topics fanning out to SQS, Lambda, HTTP, email, SMS, mobile push; FIFO topics | Fan-out (SNS → many SQS queues), notifications |
| EventBridge | Event bus with content-based routing rules (JSON pattern matching), schema registry, archive and replay, cross-account buses, Pipes (point-to-point source → filter → enrich → target) and Scheduler | Event-driven architectures, SaaS events, AWS service events (e.g. EC2 state changes) |
Rule of thumb: SQS when one consumer group must process work reliably; SNS + SQS for simple fan-out; EventBridge for routing heterogeneous events between many producers and consumers by content; MSK/Kinesis for high-volume ordered streams and replay.
CloudWatch
AWS's observability service (Vol. 9 goes deeper):
- Metrics (service metrics automatically; custom metrics via API, Embedded Metric Format in logs, or the CloudWatch agent; high-resolution 1 s metrics), alarms (static, anomaly detection, composite), dashboards.
- Logs (log groups and streams; retention settings, which default to never expire, so set them; Logs Insights query language; subscription filters to stream logs elsewhere; data protection masking).
- Traces via X-Ray / Application Signals (OpenTelemetry-based APM with SLOs), synthetic canaries, RUM, Container Insights, Lambda Insights.
- CloudTrail (separate service) records API calls for audit: enable an organisation trail to a locked-down log-archive account.
- Cost pitfalls: log ingestion volume, custom metric cardinality (each unique dimension combination is a metric), and high-frequency
GetMetricDatacalls.
Secrets Manager and Parameter Store
- AWS Secrets Manager stores secrets (database credentials, API keys) encrypted with KMS, with fine-grained IAM and resource policies, automatic rotation (built-in for RDS, Aurora, Redshift, DocumentDB; Lambda-based for others), cross-region replication, versioning (
AWSCURRENT,AWSPREVIOUS), and audit via CloudTrail. - Systems Manager Parameter Store: hierarchical configuration and secrets (
SecureString), cheaper, no built-in rotation. - Access patterns: fetch at startup and cache with refresh (AWS caching clients, Lambda extension), inject into ECS task definitions/EKS via the Secrets Store CSI driver or External Secrets Operator; never bake into images or environment files in source control.
KMS
AWS Key Management Service manages encryption keys in FIPS 140-3 validated HSMs:
- AWS managed keys (per service, e.g.
aws/s3) versus customer managed keys (your key policy, rotation, aliases, grants, cross-account use). AWS owned keys are used invisibly by some services. - Symmetric (AES-256-GCM) by default; asymmetric keys for signing (RSA, ECC, and post-quantum ML-DSA support) and HMAC keys.
- Envelope encryption (chapter 88):
GenerateDataKey/Decrypt; services integrate natively. - Key policies are the primary control (a key policy that doesn't allow the account root or administrators can make a key unmanageable); grants delegate temporary use to services.
- Automatic rotation (yearly by default, configurable) keeps old key material for decrypting old data.
- Multi-region keys for cross-region decryption; CloudHSM for dedicated single-tenant HSMs; External Key Store (XKS) for keys held outside AWS.
- Cost and limits: per-key monthly fees and per-request charges; request-rate quotas (use S3 Bucket Keys and data-key caching for high-volume encryption).
Azure and GCP equivalents
| Capability | AWS | Azure | Google Cloud |
|---|---|---|---|
| Identity directory and SSO | IAM Identity Center + IdP | Microsoft Entra ID | Cloud Identity / Workspace |
| Resource access control | IAM policies | Azure RBAC, Azure Policy | Cloud IAM, Org Policy |
| Workload identity | IAM roles | Managed identities | Service accounts |
| Virtual network | VPC | VNet | VPC (global) |
| VMs | EC2 | Virtual Machines, VM Scale Sets | Compute Engine, managed instance groups |
| Managed Kubernetes | EKS | AKS | GKE (Standard / Autopilot) |
| Serverless containers | ECS Fargate, App Runner | Container Apps | Cloud Run |
| Functions | Lambda | Azure Functions | Cloud Run functions (formerly Cloud Functions) |
| PaaS web apps | Elastic Beanstalk, App Runner | App Service | App Engine (legacy), Cloud Run |
| Object storage | S3 | Blob Storage (storage accounts) | Cloud Storage |
| Block storage | EBS | Managed Disks | Persistent Disk / Hyperdisk |
| File storage | EFS, FSx | Azure Files, NetApp Files | Filestore |
| Relational (managed) | RDS, Aurora | Azure SQL Database, SQL Managed Instance, Azure Database for PostgreSQL / MySQL (Flexible Server) | Cloud SQL, AlloyDB (PostgreSQL-compatible), Spanner |
| Globally distributed NoSQL | DynamoDB | Cosmos DB (multiple APIs, five consistency levels) | Firestore, Bigtable, Spanner |
| In-memory cache | ElastiCache (Valkey/Redis/Memcached) | Azure Managed Redis (Azure Cache for Redis tiers are being retired) | Memorystore (Valkey, Redis, Memcached) |
| Queues | SQS | Service Bus queues, Storage Queues | Pub/Sub, Cloud Tasks |
| Pub/sub and events | SNS, EventBridge | Service Bus topics, Event Grid | Pub/Sub, Eventarc |
| Streaming | MSK, Kinesis | Event Hubs (Kafka-compatible endpoint) | Managed Service for Apache Kafka, Pub/Sub |
| Workflows | Step Functions | Logic Apps, Durable Functions | Workflows |
| L7 load balancing | ALB | Application Gateway | Cloud Load Balancing (Application LB) |
| Global edge / CDN | CloudFront (+ Global Accelerator) | Front Door | Cloud CDN + global external Application LB |
| DNS | Route 53 | Azure DNS, Traffic Manager | Cloud DNS |
| Monitoring and logs | CloudWatch, X-Ray | Azure Monitor (Log Analytics with KQL, Application Insights) | Cloud Monitoring, Cloud Logging, Cloud Trace |
| Audit | CloudTrail | Activity Log, Entra audit logs | Cloud Audit Logs |
| Secrets | Secrets Manager, Parameter Store | Key Vault (secrets, keys, certificates) | Secret Manager |
| Keys / HSM | KMS, CloudHSM | Key Vault, Managed HSM | Cloud KMS, Cloud HSM, EKM |
| Security posture | Security Hub, GuardDuty, Inspector | Defender for Cloud, Sentinel | Security Command Center |
| Data warehouse | Redshift | Fabric / Synapse | BigQuery |
| IaC (native) | CloudFormation, CDK | ARM templates, Bicep | Infrastructure Manager (Terraform-based) |
Notable differences in philosophy:
- Azure is organised around subscriptions and resource groups (lifecycle containers), with deep Microsoft ecosystem integration (Entra ID, Windows, .NET, SQL Server, Microsoft 365, GitHub). Azure Policy is a powerful governance engine.
- Google Cloud leans on its global network (global VPCs and load balancers), data and AI strengths (BigQuery, Spanner, Vertex AI, TPUs), and Kubernetes heritage (GKE); projects are lightweight and IAM inheritance through the resource hierarchy is central.
- AWS has the broadest catalogue and the most configuration knobs per service; accounts are the isolation unit.
The same application on three clouds
// AWS CDK (TypeScript): Fargate service behind an ALB with autoscaling and a DynamoDB table
const vpc = new ec2.Vpc(this, "Vpc", { maxAzs: 3, natGateways: 3 });
const table = new dynamodb.TableV2(this, "Orders", {
partitionKey: { name: "pk", type: dynamodb.AttributeType.STRING },
sortKey: { name: "sk", type: dynamodb.AttributeType.STRING },
billing: dynamodb.Billing.onDemand(),
pointInTimeRecoverySpecification: { pointInTimeRecoveryEnabled: true },
});
const svc = new ecsPatterns.ApplicationLoadBalancedFargateService(this, "Api", {
vpc,
cpu: 512, memoryLimitMiB: 1024, desiredCount: 3,
taskImageOptions: {
image: ecs.ContainerImage.fromRegistry("ghcr.io/acme/orders@sha256:3b1c..."),
containerPort: 8080,
environment: { TABLE: table.tableName },
},
circuitBreaker: { rollback: true },
runtimePlatform: { cpuArchitecture: ecs.CpuArchitecture.ARM64 },
});
table.grantReadWriteData(svc.taskDefinition.taskRole); // least-privilege task role
svc.targetGroup.configureHealthCheck({ path: "/actuator/health/readiness" });
svc.service.autoScaleTaskCount({ minCapacity: 3, maxCapacity: 30 })
.scaleOnCpuUtilization("Cpu", { targetUtilizationPercent: 60 });
// Azure Bicep: Container App with a managed identity and Cosmos DB access
resource env 'Microsoft.App/managedEnvironments@2024-03-01' = {
name: 'shop-env'
location: location
properties: { zoneRedundant: true }
}
resource api 'Microsoft.App/containerApps@2024-03-01' = {
name: 'orders-api'
location: location
identity: { type: 'SystemAssigned' }
properties: {
managedEnvironmentId: env.id
configuration: { ingress: { external: true, targetPort: 8080 } }
template: {
containers: [{
name: 'orders'
image: 'ghcr.io/acme/orders@sha256:3b1c...'
resources: { cpu: json('0.5'), memory: '1Gi' }
env: [{ name: 'COSMOS_ENDPOINT', value: cosmos.properties.documentEndpoint }]
}]
scale: { minReplicas: 3, maxReplicas: 30, rules: [{ name: 'http', http: { metadata: { concurrentRequests: '50' } } }] }
}
}
}
// Role assignment: grant the app's managed identity the Cosmos DB data contributor role (no keys)
# Google Cloud: deploy to Cloud Run with a dedicated service account and Firestore access
gcloud iam service-accounts create orders-api
gcloud projects add-iam-policy-binding acme-prod \
--member="serviceAccount:orders-api@acme-prod.iam.gserviceaccount.com" --role="roles/datastore.user"
gcloud run deploy orders-api \
--image=asia-south1-docker.pkg.dev/acme-prod/apps/orders@sha256:3b1c... \
--region=asia-south1 \
--service-account=orders-api@acme-prod.iam.gserviceaccount.com \
--min-instances=3 --max-instances=30 --concurrency=80 \
--cpu=1 --memory=1Gi --no-allow-unauthenticated
Multi-cloud and portability
Using more than one cloud is common, but for different reasons with different costs:
| Pattern | Example | Trade-off |
|---|---|---|
| Best-of-breed per workload | Apps on AWS, analytics on BigQuery, identity in Entra ID | Reasonable; needs cross-cloud identity federation and data-transfer budgets |
| Inherited (acquisitions, teams' choices) | Two business units on different clouds | Common; standardise tooling (Terraform, Kubernetes, OpenTelemetry, IdP) |
| Active-active across clouds for availability | Same service running on AWS and GCP | Very expensive and complex: lowest-common-denominator services, data replication across providers, double expertise. Rarely worth it versus multi-region in one cloud |
| Portability as an exit option | Containers + Kubernetes + Postgres + Terraform | Keeps migration feasible at moderate cost; avoid assuming "portable" means "free to move" (data gravity, IAM and networking differ) |
Practical stance: use managed services deeply in your primary cloud (they're where the cloud's value is), keep data formats and interfaces open (Postgres, Kafka protocol, OCI images, OpenTelemetry, Iceberg/Parquet), keep infrastructure as code, and accept that some lock-in buys real productivity. Assess regulatory needs (exit plans for critical services under rules like the EU's DORA) explicitly.
Lab: reading what your infrastructure code generates
The CDK app from the on-ramp (aws-cdk-lib 2.275, Python), synthesised locally with different settings; the generated CloudFormation templates are inspected with Python. Nothing is deployed. NAT costs use AWS us-east-1 list prices from chapter 87.
Experiment 1: least privilege from grant_* calls
Two lines of CDK, db.secret.grant_read(task_role) and queue.grant_send_messages(task_role), generated this policy:
Allow ['secretsmanager:GetSecretValue', 'secretsmanager:DescribeSecret'] on ['DbSecretAttachment7AED447C']
Allow ['sqs:SendMessage', 'sqs:GetQueueAttributes', 'sqs:GetQueueUrl'] on [['OrdersA9B65338', 'Arn']]
Each statement names exact actions on one specific resource (by reference, resolved to its ARN at deploy time), not secretsmanager:* on *. Granting through resources rather than writing policy JSON by hand is one of the biggest practical advantages of higher-level IaC: least privilege becomes the easy path.
Experiment 2: network rules from connections
db.connections.allow_default_port_from(service) generated:
database security group ingress: tcp {'Fn::GetAtt': ['Db5D02A0A9', 'Endpoint.Port']} from security group ApiServiceSecurityGroupB2E30D06 only
The database accepts its own port only from members of the service's security group, a rule that stays correct as tasks come and go, rather than from an IP range.
Experiment 3: the cost hidden in one parameter
nat_gateways=2: 52 resources, 2 NAT gateways, 4 subnets → NAT hourly cost ~$66/month before data
nat_gateways=1: 50 resources, 1 NAT gateways, 4 subnets → NAT hourly cost ~$33/month before data
nat_gateways=0: synthesis fails: «ThereSubnetGroups» There are no 'Private' subnet groups in this VPC. Available types: Isolated,Deprecated_Isolated,Public
The VPC construct's default is one NAT gateway per zone (resilient, and the most expensive). One NAT gateway halves the hourly cost but makes every zone's egress depend on one zone. Zero turns private subnets into isolated ones with no internet path, and the synthesiser refused, because the database was asked for PRIVATE_WITH_EGRESS subnets. Isolated subnets are a good design (no egress means no exfiltration path), but then tasks must pull images and call AWS APIs through VPC endpoints, which you'd add explicitly. Every high-level default is a design decision someone made for you.
Experiment 4: defaults worth checking
database properties as synthesised: {'MultiAZ': True, 'StorageEncrypted': None, 'DeletionProtection': None, 'BackupRetentionPeriod': None, 'PubliclyAccessible': False, 'AllocatedStorage': '100'}
load balancer listener: {'Protocol': 'HTTP', 'Port': 80}
bucket: {'VersioningConfiguration': {'Status': 'Enabled'}, 'PublicAccessBlockConfiguration': {'BlockPublicAcls': True, 'BlockPublicPolicy': True, 'IgnorePublicAcls': True, 'RestrictPublicBuckets': True}}
The bucket was locked down because the code asked for it. The database was Multi-AZ and private, but unencrypted at rest (CloudFormation's validator flagged it during synthesis), with no deletion protection and the default backup retention; the load balancer listened on plain HTTP. None of these is a CDK bug: they're defaults you must override (storage_encrypted=True, deletion_protection=True, backup_retention=Duration.days(14), an HTTPS listener with a certificate and a redirect from 80). Policy-as-code tools (cdk-nag, Checkov, cfn-guard, OPA) catch them automatically in CI.
Try it yourself
- Fix the four defaults in experiment 4 and add cdk-nag's
AwsSolutionsChecksto the app. How many findings remain? - Add VPC endpoints (S3 gateway; ECR, Logs and Secrets Manager interface endpoints) and synthesise with
nat_gateways=0. - Write the same architecture in Terraform/OpenTofu with community modules and compare the resource count and defaults.
- Sketch the same design on Azure (Container Apps, Azure Database for PostgreSQL flexible server, Service Bus, Front Door) and list which choices change.
Revision sheet: cloud architecture
Key ideas
- One cloud deeply: core compute, networking, storage, database, messaging, identity, observability and IaC services, with their limits, quotas and defaults.
- AWS in depth: accounts and Organizations, VPC, EC2/ASG, ECS/EKS/Fargate, Lambda, ALB/NLB, CloudFront, S3, EBS/EFS, RDS/Aurora, DynamoDB, SQS/SNS/EventBridge/Kinesis, IAM/KMS/Secrets Manager, CloudWatch/X-Ray/CloudTrail, CloudFormation/CDK.
- Azure and GCP equivalents and genuine differences: resource groups and subscriptions, Entra ID; projects and folders, global VPCs, Cloud Run.
- Reference architectures: three-tier web, event-driven, data pipelines, multi-region active-passive and active-active.
- Multi-cloud and portability: reasons (regulation, acquisitions, leverage, best-of-breed), costs (egress, duplicated skills and tooling, lowest-common-denominator designs), portable layers (Kubernetes, Terraform, OpenTelemetry, Postgres).
- IaC practice: high-level constructs/modules, grants, reviewing synthesised output, policy-as-code, drift detection.
Numbers to remember
- Lab: ~30 lines of CDK → 52 resources; grants produced resource-scoped policies; NAT per zone ≈ $33/month each before data; synthesised database defaults: not encrypted, no deletion protection, HTTP listener.
Pitfalls
- Trusting construct and module defaults without reading the output.
- Learning many clouds superficially.
- Multi-cloud for its own sake, paying egress and complexity.
- Hand-written
*policies instead of grants. - Unencrypted storage and HTTP listeners in production.
Glossary
- CDK construct: a reusable component that generates cloud resources.
- Synthesis: turning IaC code into deployable templates.
- Landing zone: a pre-configured multi-account environment with guard rails.
- Isolated subnet: a subnet without any route to the internet.
- Policy-as-code: automated rules checking infrastructure definitions.
- Egress: data leaving a cloud or region, usually charged.