Summary#
Cloud computing means renting compute, storage, networking and higher-level services from a provider (AWS, Google Cloud, Microsoft Azure and others) through APIs, paying for what you use instead of buying hardware.
- Regions and availability zones. The physical world is organised into regions, which are geographic areas such as Frankfurt or Northern Virginia. Each region contains several availability zones (AZs): separate data centres, or groups of them, with independent power, cooling and networking, a few milliseconds apart. Spread across AZs to survive a data-centre failure. Spread across regions to survive a regional failure, and to be close to users.
- Your private network. A Virtual Private Cloud (VPC) is your private network in a region: an IP range, carved into public and private subnets per AZ, with route tables, internet and NAT gateways, and firewall rules (security groups).
- The service map. All three big providers offer equivalent building blocks, under different names: VMs, managed Kubernetes, functions, object storage, managed SQL and NoSQL databases, queues, streams and CDNs.
- Managed vs self-hosted. You can run software yourself on VMs, or use a managed service where the provider handles patching, backups, failover and scaling. Managed costs more per unit, but usually far less in engineering time.
- Cloud-native design. Cloud-native architecture assumes failure, scales elastically, automates everything, and treats servers as disposable.
- Cost. Cloud bills hide surprises: data egress, cross-AZ traffic, NAT gateways, idle resources and over-provisioning. Frugal architecture makes cost a design requirement from day one, alongside latency and availability.
Why It Exists#
Before the cloud, launching a service meant forecasting demand months ahead, buying servers, waiting weeks for delivery, racking them in a data centre you leased, and paying for that capacity whether you used it or not. Underestimate, and the launch melts down. Overestimate, and money sits idle in a rack. Every company also rebuilt the same undifferentiated plumbing: databases with backups, load balancers, monitoring and storage arrays.
Amazon Web Services launched S3 and EC2 in 2006. Microsoft Azure and Google Cloud followed. The cloud changed three things:
- Elasticity. Capacity arrives in minutes through an API call, and goes away when you stop paying. You can scale for a Black Friday peak, and scale back on Monday.
- Pay as you go. Capital expense (buying servers) becomes operating expense (renting them). Experiments are cheap: try something for a week, and delete it.
- Higher-level building blocks. Instead of installing and operating PostgreSQL, Kafka or a CDN yourself, you call a managed service, and get replication, backups and patching included.
The trade-off is that you give up control and some cost efficiency at steady scale, and you must design for a new set of constraints: shared infrastructure, per-request pricing, API limits, and the shared responsibility model. The provider secures the cloud itself: facilities, hardware, hypervisors and managed-service internals. You secure what you put in the cloud: your data, identities, network rules, configurations and code.
Service models. The cloud offers a spectrum of abstraction. The higher you go, the less you manage, and the less you control.
| Model | You manage | Provider manages | Examples |
|---|---|---|---|
| IaaS (Infrastructure as a Service) | OS, runtime, app, data, scaling | Hardware, virtualisation, network fabric | EC2, Compute Engine, Azure VMs |
| CaaS (Containers as a Service) | Containers, app, data | Cluster control plane, sometimes nodes | EKS, GKE, AKS, Fargate, Cloud Run |
| PaaS (Platform as a Service) | App code and data | Runtime, OS, scaling, patching | App Engine, Azure App Service, Elastic Beanstalk, Heroku |
| FaaS (Functions as a Service) | Function code | Everything else, scale to zero | Lambda, Cloud Run functions, Azure Functions |
| SaaS (Software as a Service) | Configuration and data | The whole application | Gmail, Salesforce, Datadog |
Read the diagram top to bottom as increasing control and responsibility: each step down hands you more knobs and more work. Most real systems mix levels, for example containers on managed Kubernetes, data in a managed database, and a few functions for event glue.
How It Works#
Regions and availability zones#
A region is a geographic area containing several isolated data-centre groups. AWS, Google Cloud and Azure each operate dozens of regions worldwide. Regions are deliberately independent: separate control planes for most services, separate power grids, and often hundreds of kilometres apart. A failure in one region shouldn't spread to another.
An availability zone (AZ) is one or more discrete data centres inside a region, with independent power, cooling and networking, located far enough apart that a fire, flood or power failure is unlikely to hit two at once, but close enough for low latency. AZs in a region are connected by redundant, high-bandwidth private fibre. AWS typically has three or more AZs per region. Google Cloud calls them zones (for example, europe-west1-b). Azure has availability zones in most regions, plus older availability sets (fault and update domains within one data centre).
Latency numbers to remember.
| Path | Typical round trip |
|---|---|
| Within one AZ | Well under 1 ms |
| Across AZs in one region | About 1–2 ms |
| Across regions on the same continent | About 10–40 ms |
| Across continents (for example, New York to London) | About 70–90 ms; 150 ms or more to Asia-Pacific |
Physics sets the floor. Light in optical fibre travels at about two-thirds of its speed in a vacuum, about 200,000 km/s. New York to London is about 5,600 km, so a round trip is about 11,200 km, which takes at least 56 ms before any routing, queuing or processing. No amount of engineering beats that. The only fix is to move the data and computation closer to the user (Numbers Every Engineer Should Know).
Data locality and regional partitioning. For a regional application, keep the data a request needs close together, and close to the user. If web servers are in New York, and the database they query is in Los Angeles, every query pays tens of milliseconds, and a page with 10 sequential queries pays them ten times. Two strategies help:
- CDNs cache content at edge locations in hundreds of cities, so cacheable responses (images, video segments, even some API results) are served from nearby (CDN).
- Regional partitioning splits data by geography when users mostly interact with nearby data. A ride-hailing app is the classic example. A rider in Miami never needs a driver in New York. So group cities into regions ("US Northeast", "US Southwest"), and give each region its own services and databases, co-located in that geography. Queries are answered regionally: fast network, smaller datasets, and a failure in one region doesn't affect another. The architecture mirrors the problem's natural locality (Multi-Region and Global Data).
Edge and specialised locations. Beyond regions and AZs, providers offer:
- edge locations / points of presence (PoPs) for CDN, DNS and edge compute, in hundreds of cities;
- local zones, which are small extensions of a region in a metro area, for single-digit-millisecond latency to users there;
- telecom-edge zones inside 5G networks;
- on-premises extensions (AWS Outposts, Azure Stack, Google Distributed Cloud) that run cloud services in your own data centre.
Choosing a region. Criteria, roughly in order:
- Data residency and compliance. GDPR, national laws, and customer contracts may require data to stay in a country or the EU.
- Latency to users. Pick regions near your largest user populations.
- Service availability. New services and instance types launch in some regions first.
- Price. The same instance can cost 10–30% more in some regions, such as São Paulo or Tokyo, than in us-east-1 or us-west-2.
- Carbon intensity, if sustainability is a goal. Providers publish regional carbon data.
- Blast-radius history: whether the region hosts global control-plane dependencies for that provider.
Regions and availability zones, in depth: failure domains, static stability and capacity maths#
Failure domains, from small to large.
- A process.
- A host: an instance retirement, or a hardware fault.
- A rack, or a power distribution unit.
- An AZ: power, cooling or network failure, or a bad deploy of a zonal service.
- A region: a regional control-plane failure, or a regional network event.
- A provider's global services: IAM, DNS, global load balancers, or a global configuration push.
Design so each level's failure is absorbed by the level above:
- run multiple instances per AZ;
- run multiple AZs per region, as the standard for production;
- run multiple regions for the highest availability, or for locality;
- minimise dependence on global control planes in the data path.
AZ failures happen, and so do regional ones. Providers have had AZ-level events (power loss, cooling failures in heat waves) and occasional region-wide disruptions. On 7 December 2021, an AWS us-east-1 event in the internal network that hosts many AWS control-plane services impaired a wide range of services for hours. Many customers' running resources kept working, while their ability to change things (launch instances, update configurations) failed. That's the distinction behind static stability.
Static stability is a term the AWS Builders' Library uses. A statically stable system keeps working during a dependency failure without needing to make changes. For example:
- Provision enough capacity in each AZ in advance, so that losing an AZ doesn't require launching instances, which may be impossible during the event, when everyone else is trying to launch too.
- Keep data-plane operations (serving requests) independent of control-plane operations (creating resources, changing config).
- Cache credentials, configs and DNS answers, with sensible expiry.
- Don't make a regional service depend on a single AZ's resources, or on another region.
Capacity maths for AZ failure. Suppose peak traffic needs N units of capacity. With k AZs, to survive the loss of one AZ, the remaining k − 1 must carry N. So each AZ needs N / (k − 1), and the total provisioned is N · k / (k − 1).
| AZs | Per-AZ capacity | Total provisioned | Overhead |
|---|---|---|---|
| 2 | N | 2N | 100% |
| 3 | N/2 | 1.5N | 50% |
| 4 | N/3 | 1.33N | 33% |
| 6 | N/5 | 1.2N | 20% |
That's why three AZs is the common sweet spot: a 50% overhead for zone-loss tolerance, versus 100% with two. Autoscaling can reduce the steady-state cost, but only if the scale-up succeeds during an AZ event. Static-stability thinking says pre-provision the critical tier, and autoscale the rest.
AZ names vs AZ IDs. On AWS, the AZ name us-east-1a maps to different physical zones in different accounts, which spreads customers evenly. To co-locate resources across accounts (for example, a shared service and its consumers in the same physical zone, to avoid cross-AZ charges and latency), use the AZ ID (use1-az1), which is consistent across accounts.
Zonal isolation patterns. Keep requests within one AZ where possible: the load balancer to app to cache to database replica, all in the same zone. This reduces latency and cross-AZ data charges (about $0.01 per GB in each direction on AWS), and contains failures. If AZ b degrades, shift traffic away from it (a "zonal shift", which AWS offers for its load balancers), rather than letting it fail slowly. The trade-off is less even load distribution, so this needs capacity balance per zone.
Capacity can run out. Clouds are not infinite. Popular instance types, especially GPUs, can hit "insufficient capacity" in a specific AZ. Mitigations:
- allow several instance types and sizes (flexible autoscaling groups, Karpenter);
- spread across AZs;
- use capacity reservations or reserved capacity for critical workloads;
- for GPUs, plan quotas and reservations months ahead.
VPC networking basics#
A Virtual Private Cloud (VPC) is a logically isolated network you define inside a provider's infrastructure. Think of it as your own data-centre network, built from software. On AWS and Azure (where it's called a VNet), a VPC lives in one region, and spans its AZs. On Google Cloud, a VPC is global, with regional subnets, so VMs in different regions can talk over internal IPs without peering.
Building blocks.
- CIDR block: the VPC's private IP range, such as
10.20.0.0/16(65,536 addresses). Use private ranges (RFC 1918:10.0.0.0/8,172.16.0.0/12,192.168.0.0/16), and plan them so they don't overlap with other VPCs, offices, or partners you may connect to later. - Subnets: slices of the range, each in one AZ. Public subnets have a route to an internet gateway, and hold things that must be reachable from the internet, such as load balancers and bastions (if any). Private subnets have no direct inbound route from the internet, and hold app servers, databases and caches. AWS reserves 5 addresses in every subnet.
- Route tables: rules saying where traffic for each destination range goes: local within the VPC, an internet gateway, a NAT gateway, a peering connection, a transit gateway, or a VPN.
- Internet gateway: lets resources with public IPs send and receive internet traffic.
- NAT gateway: lets private-subnet resources make outbound connections (downloading packages, calling third-party APIs) without being reachable inbound. Use one per AZ for availability, and to avoid cross-AZ charges.
- Security groups: stateful firewalls attached to network interfaces, with allow rules only. If inbound traffic is allowed, the response is automatically allowed. Rules can reference other security groups ("allow port 5432 from the app tier's group"), which is much better than IP lists.
- Network ACLs: stateless subnet-level allow and deny rules, evaluated in order. Return traffic must be allowed explicitly. They're useful as a coarse second layer.
- VPC endpoints / Private Link: private connectivity to provider services (S3, DynamoDB, KMS, ECR) or to other VPCs' services, without traversing the internet or NAT. Gateway endpoints for S3 and DynamoDB are free on AWS. Interface endpoints cost an hourly fee plus a per-GB fee.
- Connecting VPCs: peering links two VPCs (non-transitive: A-B and B-C doesn't give A-C). A transit gateway (AWS), Virtual WAN (Azure) or Network Connectivity Center (GCP) acts as a hub router for many VPCs and on-premises links.
- Hybrid connectivity: a site-to-site VPN over the internet (encrypted, quick to set up, variable performance), or a dedicated link (AWS Direct Connect, Google Cloud Interconnect, Azure ExpressRoute) with predictable bandwidth and latency, and lower egress rates.
- Private DNS: internal zones (Route 53 private hosted zones, Cloud DNS private zones, Azure Private DNS), so services resolve
orders.internalto private IPs (DNS).
The same layout is repeated in AZ b and AZ c, with one NAT gateway per AZ.
A typical request path.
- The user's DNS lookup returns the load balancer's public IPs, or anycast IPs through a CDN.
- The request enters through the internet gateway to the load balancer in public subnets.
- The load balancer forwards it to app instances in private subnets, allowed by the security group.
- The app queries the database in a data subnet, allowed by the database's security group, which references the app's group.
- The app reads objects from storage through a VPC endpoint.
- It calls a payment provider through the NAT gateway.
Every hop is defined by routes and security rules, and each can be audited.
VPC networking, in depth: IP planning, NAT costs, egress control and multi-account networks#
IP address planning. Plan for years, because re-addressing a VPC is painful.
- A
/16gives 65,536 addresses. Split it into/19private subnets (8,192 each) per AZ for workloads, smaller/22public subnets (1,024) for load balancers, and dedicated subnets for databases. - Kubernetes with native VPC networking gives each pod a VPC IP, so a 300-node cluster with 30 pods per node needs 9,000 or more IPs. Size pod subnets accordingly, or use secondary CIDRs and prefix delegation (Containers and Kubernetes).
- Use a central IP address management (IPAM) plan across all VPCs and on-premises ranges, so future peering and transit routing never collide.
- IPv6 removes the address-scarcity problem (AWS gives a
/56per VPC), and avoids NAT for egress (through egress-only internet gateways), but needs dual-stack support in every component.
The NAT gateway trap. A managed NAT gateway on AWS costs an hourly fee (about $0.045 per hour in us-east-1) plus a per-GB processing fee (about $0.045 per GB), on top of normal data transfer. A workload that pulls 50 TB a month of container images, packages, or S3 data through NAT pays about $2,250 a month in processing fees alone. Fixes:
- gateway endpoints for S3 and DynamoDB (free);
- interface endpoints for ECR and other services, when volume justifies them;
- registry pull-through caches;
- keeping chatty dependencies inside the VPC.
A single NAT gateway shared across AZs also adds cross-AZ charges, and an AZ-level single point of failure.
Egress control for security. Outbound internet access is how compromised workloads exfiltrate data, or download malware. Mature setups:
- route egress through filtering proxies or firewalls (AWS Network Firewall, Azure Firewall, Cloud NGFW, or a proxy fleet) with domain allow-lists;
- block the instance metadata service from containers;
- log flows (VPC Flow Logs) for investigations.
Security groups vs NACLs in practice. Security groups do most of the work, because they are stateful, attached per resource, and support group-to-group references. NACLs are coarse, stateless guardrails. They're useful to block a known-bad CIDR across a subnet, or to enforce "data subnets never talk to the internet", but are tedious for fine-grained rules, because ephemeral return ports (1024–65535) must be opened explicitly.
Multi-account and hub-and-spoke networks. Large organisations use many accounts or projects: per team, per environment, and for shared services. Networking follows a hub-and-spoke model:
- a central networking account owns the transit gateway (or the equivalent), the egress VPC with firewalls and NAT, the ingress VPC with WAF and load balancers, and the hybrid links to offices and data centres;
- workload VPCs attach as spokes;
- on AWS, shared VPCs (subnets shared to other accounts through Resource Access Manager) let a central team own the network while app teams own their resources;
- on GCP, the Shared VPC construct has the same purpose.
This centralises inspection and egress cost, at the price of a critical shared component that must be highly available.
Load balancer types (Load Balancing):
- L7 application load balancers (AWS ALB, Azure Application Gateway, GCP's HTTP(S) load balancers) for HTTP routing, TLS and WAF integration;
- L4 network load balancers (AWS NLB, Azure Load Balancer, GCP network load balancers) for TCP and UDP, at very high throughput, with static IPs;
- global anycast front doors (Google's global external load balancer, Azure Front Door, AWS Global Accelerator, or CloudFront) for multi-region entry with one IP or hostname.
Core service map across AWS, GCP and Azure#
All three major clouds offer the same categories of building blocks. Knowing the names lets you design in vendor-neutral terms ("a managed queue", "object storage"), then map to a provider. The services are not identical: semantics, limits and pricing differ, as the deep dive below explains.
| Category | AWS | Google Cloud | Azure |
|---|---|---|---|
| Virtual machines | EC2 | Compute Engine | Virtual Machines |
| VM autoscaling groups | Auto Scaling groups | Managed instance groups | Virtual Machine Scale Sets |
| Managed Kubernetes | EKS | GKE (Standard, Autopilot) | AKS |
| Serverless containers | ECS on Fargate, App Runner | Cloud Run | Container Apps |
| Functions (FaaS) | Lambda | Cloud Run functions (formerly Cloud Functions) | Azure Functions |
| PaaS web apps | Elastic Beanstalk | App Engine | App Service |
| Object storage | S3 | Cloud Storage | Blob Storage |
| Block storage | EBS | Persistent Disk, Hyperdisk | Managed Disks |
| File storage | EFS, FSx | Filestore | Azure Files, NetApp Files |
| Archive storage | S3 Glacier classes | Archive storage class | Blob Archive tier |
| Managed relational | RDS, Aurora | Cloud SQL, AlloyDB | Azure SQL Database, Azure Database for PostgreSQL and MySQL |
| Globally distributed SQL | Aurora DSQL | Spanner | Azure Cosmos DB for PostgreSQL (distributed Postgres), Azure SQL Hyperscale (scale-up) |
| Key-value and wide-column NoSQL | DynamoDB, Keyspaces (Cassandra API) | Bigtable, Firestore | Cosmos DB (several APIs), Table Storage |
| Document database | DocumentDB (MongoDB-compatible) | Firestore | Cosmos DB for MongoDB |
| In-memory cache | ElastiCache, MemoryDB | Memorystore | Azure Cache for Redis / Azure Managed Redis |
| Data warehouse | Redshift | BigQuery | Synapse Analytics, Microsoft Fabric |
| Message queue | SQS | Cloud Tasks, Pub/Sub | Service Bus, Queue Storage |
| Pub/sub and event routing | SNS, EventBridge | Pub/Sub, Eventarc | Event Grid, Service Bus topics |
| Event streaming (Kafka-like) | Kinesis Data Streams, MSK (managed Kafka) | Pub/Sub, Managed Service for Apache Kafka | Event Hubs (Kafka-compatible endpoint) |
| Stream processing | Managed Service for Apache Flink | Dataflow (Apache Beam) | Stream Analytics |
| Workflow orchestration | Step Functions | Workflows | Logic Apps, Durable Functions |
| CDN | CloudFront | Cloud CDN | Azure Front Door |
| DNS | Route 53 | Cloud DNS | Azure DNS |
| Load balancing | Elastic Load Balancing (ALB, NLB, GWLB) | Cloud Load Balancing | Load Balancer, Application Gateway, Front Door |
| API gateway | API Gateway | API Gateway, Apigee | API Management |
| Identity and access | IAM, IAM Identity Center | Cloud IAM | Microsoft Entra ID, Azure RBAC |
| Keys and secrets | KMS, Secrets Manager | Cloud KMS, Secret Manager | Key Vault |
| Monitoring and logs | CloudWatch, X-Ray | Cloud Monitoring, Logging, Trace | Azure Monitor, Application Insights |
| Infrastructure as code | CloudFormation, CDK | Infrastructure Manager (Terraform-based) | ARM templates, Bicep |
| Search | OpenSearch Service | Vertex AI Search | Azure AI Search |
| ML and GenAI platform | SageMaker, Bedrock | Vertex AI | Azure Machine Learning, Azure AI Foundry (Azure OpenAI) |
The service map, in depth: equivalent is not identical#
The mapping table is a starting point. Equivalent services differ in ways that change designs.
Semantics differ.
- SQS standard queues give at-least-once delivery with best-effort ordering. SQS FIFO adds ordering per message group, and deduplication, with lower throughput limits (high-throughput mode raises them substantially).
- Google Pub/Sub is a global service, with optional ordering keys and exactly-once delivery for pull subscriptions.
- Azure Service Bus offers sessions (ordered groups), transactions, and dead-letter queues, in an enterprise messaging style, while Event Hubs is a partitioned log, much closer to Kafka.
Choosing "the queue" for a design means checking ordering, delivery semantics, retention, and replay (Message Queues).
Consistency differs.
- Amazon S3 has provided strong read-after-write consistency for all objects since December 2020. Before that, overwrites and deletes were eventually consistent.
- DynamoDB reads are eventually consistent by default, and strongly consistent on request, within a region. Global tables replicate across regions asynchronously, with last-writer-wins conflict resolution (AWS has also added a multi-region strong consistency option).
- Cosmos DB exposes five consistency levels: strong, bounded staleness, session, consistent prefix and eventual.
- Spanner offers external consistency (linearisable transactions) globally, using TrueTime (Consistency Models).
Limits shape architecture.
- An S3 bucket supports at least 3,500 writes and 5,500 reads per second per prefix, and scales by spreading load across prefixes.
- A DynamoDB partition handles up to about 3,000 read capacity units and 1,000 write capacity units, so a hot partition key throttles regardless of table capacity (DynamoDB).
- AWS Lambda functions run for at most 15 minutes, with up to 10 GB of memory, and accounts have default concurrency quotas. That's fine for event glue, but wrong for long jobs (Serverless).
- API gateways have per-account request quotas, and payload and timeout limits (AWS API Gateway REST APIs have a 29-second integration timeout by default).
Every design that depends on a managed service should name the relevant quota, and the plan for when you hit it.
Modern machines are huge. A frequent over-engineering mistake is to assume single machines are small. Today a general-purpose instance such as an AWS m6i.32xlarge has 128 vCPUs and 512 GiB of RAM. Memory-optimised instances reach 4 TB (x1e.32xlarge), or even 24 TB of RAM on high-memory bare-metal instances. Storage-optimised instances carry about 60 TB of local NVMe SSD (i3en.24xlarge), and dense-storage instances offer hundreds of terabytes of HDD. Networking of 25 Gbps is ordinary, and 100 Gbps or more is available on larger instances. So a single well-tuned PostgreSQL primary on a large instance can serve workloads that textbooks from a decade ago would have sharded. Before distributing a system, check whether one big machine (plus a standby in another AZ) already fits the load. It's cheaper, simpler and faster. See Vertical vs Horizontal Scaling.
Multi-cloud reality. Using two clouds for different workloads (analytics in BigQuery, apps on AWS) is common, and sensible. Running the same workload active-active across clouds, for resilience or leverage, is rare, and expensive. You're limited to the lowest common denominator of services, you pay egress between clouds, and you must operate two of everything: IAM, networking, observability. Most organisations get better availability from a well-designed multi-region deployment on one provider. Portability is better bought selectively: containers, Kubernetes, Terraform, open-source data stores (PostgreSQL, Kafka, Redis protocols), and OpenTelemetry keep the exit cost manageable without forgoing managed services.
Managed vs self-hosted#
For every component, you choose where on the spectrum to sit:
- Self-hosted on VMs. You install, configure, patch, back up, monitor, scale and fail over the software, say Kafka on EC2.
- Self-hosted on Kubernetes with an operator (Strimzi for Kafka, CloudNativePG for Postgres). The operator automates parts of day-2 operations, but you still own the cluster, the upgrades and the incidents.
- Managed service (Amazon MSK, RDS, Memorystore). The provider runs the software, with automated backups, patching, failover and scaling. You choose sizes, configure parameters, and own your schemas, data, access and capacity planning.
- Serverless or fully managed (DynamoDB on-demand, Aurora Serverless, Confluent Cloud, BigQuery). No servers, sizes or clusters: pay per request or per unit of usage, with scaling handled for you.
The shared responsibility line moves with each step. With RDS, AWS patches the database engine and the OS, while you still configure security groups, encryption, parameter groups, IAM and backups retention, and you design the schema and queries.
API gateways are a good example. Managed gateways from cloud providers (AWS API Gateway, Azure API Management, Google Cloud's API Gateway and Apigee) integrate tightly with their ecosystems: IAM and OAuth, throttling and usage plans with API keys, direct function integrations, built-in monitoring, and developer portals. Some have strong gRPC and OpenAPI support. They are by far the easiest option, and often the most expensive per request at high volume. Open-source gateways (Kong, built on NGINX with a large plugin ecosystem; Tyk, with native GraphQL support and analytics; Express Gateway, which is lightweight and Node.js-based; and Envoy-based gateways) give more control, work on-premises and across clouds, and cost compute instead of per-request fees, but you operate them (API Gateway).
Decision factors.
| Factor | Favours managed | Favours self-hosted |
|---|---|---|
| Team size and expertise | Small team, no deep specialist | Dedicated experts for that system |
| Scale | Small to large | Very large, steady, where per-unit premiums dominate |
| Differentiation | Commodity component | Core competency; tuning is a competitive edge |
| Features | Standard features suffice | Need specific versions, plugins, kernel tuning, or unsupported configs |
| Compliance | Provider certifications cover needs | Data must stay on-premises, or requires custom controls |
| Portability | Acceptable lock-in | Must run across clouds or on-premises |
| Time to market | Need it next week | Can invest months |
A worked example: total cost of ownership. A team needs a 3-broker Kafka cluster handling 50 MB/s.
- Self-hosted: 3 brokers on reasonably sized VMs, with disks, cost perhaps $2,000–3,000 a month in infrastructure. But someone must handle upgrades, broker failures, partition rebalancing, monitoring, security patches and on-call. If that's 25% of one engineer, costing $200,000 a year fully loaded, that's about $4,200 a month.
- Managed (MSK): perhaps $3,500–5,000 a month, with most of that operational toil gone. It's still not zero: you tune topics, partitions and clients.
At this scale, managed usually wins on total cost. At 50× the scale, with a dedicated streaming team, the per-unit premium may outweigh the labour, and self-hosting (or a different architecture) can win. Rule of thumb: default to managed services, and revisit when the managed bill for one service rivals the cost of a team that would run it, or when you're blocked by missing features.
Managed vs self-hosted, in depth: lock-in, failure modes of managed services, and leaving the cloud#
Lock-in exists on a spectrum.
- Low lock-in: managed PostgreSQL, MySQL or Redis-protocol services, managed Kafka, Kubernetes, object storage via S3-compatible APIs. You can migrate with effort.
- Medium lock-in: proprietary APIs with clear equivalents (SQS to Pub/Sub, Lambda to Cloud Run functions). Code changes are needed, but the architecture survives.
- High lock-in: deeply proprietary data models or semantics (DynamoDB's single-table designs, Spanner's TrueTime-backed semantics, BigQuery-specific SQL and pricing, Cosmos multi-model). Migrating means redesign.
Lock-in isn't automatically bad. It's a trade for capability and speed. Make it a conscious decision: record it in an architecture decision record, keep data exportable (open formats such as Parquet in object storage), and isolate provider-specific code behind interfaces where it's cheap.
Managed services fail too. Managed services have:
- maintenance windows (patching can cause brief failovers, so set windows and handle reconnects);
- version end-of-life, forcing upgrades on the provider's schedule;
- opaque internals, so debugging a latency spike in a managed database is harder;
- noisy-neighbour effects on shared multi-tenant infrastructure;
- regional dependencies (some services rely on a control plane in one region);
- quotas that bite at the worst time.
Design for these the same as for any dependency: timeouts, retries with backoff, circuit breakers, and multi-AZ configurations (Resilience Patterns). Read the service's SLA. A 99.99% SLA usually means service credits, not compensation for your losses.
Leaving the cloud, or parts of it. Some companies with large, steady workloads have moved off public cloud for specific systems.
- Dropbox built its own storage system ("Magic Pocket"), and migrated the bulk of user file data off Amazon S3 into its own data centres by around 2016, citing cost and control at exabyte scale.
- 37signals (Basecamp, HEY) publicly moved its applications from AWS to its own hardware in 2022–2023, reporting large savings for its predictable workloads.
These cases share a profile: steady, predictable load, huge scale in one dimension (storage or bandwidth), and in-house operational expertise. For spiky, fast-growing or small workloads, and for teams that would need to hire data-centre skills, the cloud remains the better deal. Many organisations land on hybrid: a steady baseline on owned or colocated hardware, and burst capacity, new products and managed data services in the cloud.
Cloud-native principles#
Cloud-native describes systems designed to exploit the cloud's properties (elasticity, automation, managed services, global reach) rather than simply relocating a data-centre design onto rented VMs ("lift and shift"). The Cloud Native Computing Foundation's definition highlights containers, service meshes, microservices, immutable infrastructure and declarative APIs, enabling loosely coupled systems that are resilient, manageable and observable, combined with robust automation. In practice, the principles are:
- Design for failure. Instances, AZs and dependencies fail. Assume it, and build redundancy, health checks, timeouts, retries and graceful degradation (High Availability Design).
- Elasticity: scale horizontally and automatically. Stateless services behind load balancers, with autoscaling on load signals. Scale in as well as out, because unused capacity is pure cost.
- Treat servers as cattle, not pets. No hand-tended servers. Instances are disposable, and replaced rather than repaired (immutable infrastructure, built from images).
- Automate everything. Infrastructure as code, CI/CD, policy as code, and auto-remediation. If a human must click it, it will eventually be done wrong (CI/CD and Deployment).
- Prefer managed services for undifferentiated components, and spend engineering time on the product.
- Loose coupling through APIs and events, so components evolve and scale independently (Event-Driven Architecture).
- Observability by default: metrics, logs and traces, with SLOs (Observability).
- Security in depth, with least privilege: an identity per workload, encryption everywhere, private networking, and no long-lived credentials.
- Cost awareness: pay-per-use means architecture choices are cost choices.
The Well-Architected frameworks. AWS's Well-Architected Framework organises guidance into six pillars: operational excellence, security, reliability, performance efficiency, cost optimisation, and sustainability. Google Cloud and Azure publish similar frameworks (the Google Cloud Architecture Framework and the Azure Well-Architected Framework, with closely matching pillars). They're useful checklists for design reviews: for each pillar, the framework asks concrete questions ("How do you detect and respond to an AZ failure?", "How do you govern usage?").
Cloud-native anti-patterns.
| Anti-pattern | Why it hurts | Better |
|---|---|---|
| Lift and shift with no changes | Pays cloud prices for data-centre design; no elasticity | Re-platform incrementally: managed DB, autoscaling, containers |
| Fixed-size fleets sized for peak | Pay for peak 24/7 | Autoscaling, scheduled scaling, serverless for spiky work |
| Hard-coded IPs and hostnames | Break on replacement and failover | Service discovery, DNS, config |
| Local disk state on app servers | Lost on instance replacement; blocks scaling | Externalise state: databases, caches, object storage |
| Single AZ "for now" | One data-centre event takes you down | Multi-AZ from the first production deploy |
| Long-lived access keys | Leak, never rotate | Workload identity, short-lived roles, OIDC federation |
| No tagging or ownership | Unknown costs, orphaned resources | Mandatory tags: owner, team, environment, cost centre |
| Distributed monolith of microservices | Network calls everywhere, coupled deploys | Clear service boundaries, or a well-structured monolith |
| Ignoring data transfer in design | Surprise egress and cross-AZ bills | Model data flows and their cost during design |
Cloud-native principles, in depth: control planes, data planes, cells and shuffle sharding#
Control plane vs data plane. Every cloud service has a control plane, the APIs that create, configure and delete resources, and a data plane, which serves the actual traffic: packets, reads and writes. Data planes are designed to be simpler and more available than control planes. Lessons for your own designs:
- During an incident, don't depend on control-plane actions (launching instances, changing DNS records, creating resources) for recovery, if you can avoid it. Pre-provision standby capacity, and use data-plane mechanisms (health-check-based failover, routing controls that are already in place).
- Build your own systems the same way. Keep the request path free of calls to configuration or management services. Cache their answers, and keep working when they're down (Configuration management has the same lesson).
Cell-based architecture. Partition the system into independent cells, each a full copy of the stack serving a subset of customers, with a thin routing layer mapping customers to cells. A bug, poison request or overload affects one cell's customers, not everyone. Deploys go cell by cell. Cells have a fixed maximum size, so you scale by adding cells, and every cell stays within tested limits. AWS has written that many of its services are cellular internally. See High Availability Design.
Shuffle sharding. With 8 workers and plain sharding into 4 shards of 2, a customer sending poison requests takes down its shard, and everyone else on it. With shuffle sharding, each customer is assigned a random combination of 2 workers out of 8. There are C(8,2) = 28 possible pairs, so the chance that another given customer shares both workers with the bad customer is 1/28, about 3.6%. With 100 workers and shards of 5, there are about 75 million combinations, and complete overlap is vanishingly rare. Clients retry on their other workers, so most customers are unaffected even while one is misbehaving. The AWS Builders' Library describes how Route 53 uses this to isolate customers from attacks on other domains.
Elasticity has limits and lag. Autoscaling reacts in minutes (new VMs boot in 1–3 minutes, containers in seconds if nodes have room, functions in milliseconds to seconds, including cold starts). Traffic can spike faster than that. Keep headroom, scale on leading indicators (queue depth, request rate), use scheduled scaling for known peaks (a sale, a broadcast), and pre-warm where providers require it (some load balancers and services need notice for sudden 10× surges).
Cost optimisation and hidden costs#
Cloud cost is an architectural property. The bill is the sum of thousands of small design decisions: instance sizes, replication factors, log levels, cross-AZ calls, and storage classes. The main levers:
1. Pricing models.
- On-demand: pay by the second or hour, with no commitment. The most flexible and the most expensive.
- Commitments: Savings Plans and Reserved Instances on AWS, committed use discounts on GCP, reservations and savings plans on Azure. Commit to a spend level, or a capacity, for 1 or 3 years, for discounts often in the range of 30–70% versus on-demand, depending on term and flexibility. Use them for the steady baseline.
- Spot or preemptible capacity: spare capacity at discounts up to about 90%, which can be reclaimed with short notice (2 minutes on AWS, about 30 seconds on GCP). Use it for stateless, fault-tolerant, interruptible work: batch jobs, CI runners, stateless web tiers with diversified instance types.
- Sustained use discounts (GCP applies some automatically), and ARM-based instances (AWS Graviton, Google Axion, Azure Cobalt), which providers market as offering better price-performance for many workloads.
2. Right-sizing. Most fleets are over-provisioned: instances at 10–15% average CPU "just in case". Measure p95 utilisation over weeks, and downsize. Pick instance families that match the workload's shape (compute-, memory- or storage-optimised). In Kubernetes, right-size requests, because over-requested pods waste whole nodes (Containers and Kubernetes).
3. Elasticity and scheduling. Autoscale, so capacity follows demand. Turn off non-production environments at night and at weekends. That's 168 hours a week reduced to 60 working hours, about a 64% saving on those resources. Use serverless and scale-to-zero for spiky or low-traffic workloads.
4. Storage tiering and lifecycle. Object storage classes differ by more than 20× in price per GB-month. In AWS us-east-1, S3 Standard is about $0.023 per GB-month, while Glacier Deep Archive is about $0.001, but with retrieval fees and hours of retrieval time. Lifecycle rules move objects to cheaper tiers as they age, and delete them at the end of retention. Also: delete orphaned disk snapshots, unattached volumes and old container images, and compress logs (Object Storage).
5. Data transfer: the hidden cost.
- Internet egress: data leaving the cloud to users costs roughly $0.05–0.09 per GB on the big three at moderate volumes, with tiered discounts at large volumes. Inbound is generally free. Serving 1 PB a month directly from object storage can cost tens of thousands of dollars a month in egress. A CDN reduces origin egress, and CDN egress itself is often cheaper, especially with committed pricing.
- Cross-AZ: about $0.01 per GB in each direction on AWS, often overlooked. A chatty microservice architecture moving 500 TB a month across AZs pays about $10,000 a month just for crossing zones. Replication across AZs (databases, Kafka) is a necessary, but significant, part of this.
- Cross-region: about $0.02 per GB or more between regions, which matters for replication and DR.
- NAT gateway processing, and load balancer capacity units, which scale with traffic.
- Inter-cloud and on-premises egress: data gravity makes moving large datasets out expensive, which is a lock-in mechanism in itself.
6. Idle and forgotten resources. Idle load balancers, stopped instances with attached volumes, unattached elastic IPs (AWS charges for all public IPv4 addresses, since February 2024), development databases running 24/7, old snapshots, forgotten test clusters, and over-retained logs. Tag everything with an owner, and run automated cleanup reports.
7. Observability and managed-service premiums. Log ingestion and high-cardinality metrics can rival compute costs (Observability). Managed services charge for convenience: know which ones dominate the bill.
Cost optimisation, in depth: unit economics, FinOps and a worked bill#
Unit economics. Total spend alone is a poor metric, because spend should grow with business. Track cost per unit of value: cost per 1,000 requests, per active user per month, per order, per GB stored, or per video minute streamed. If monthly active users double, and cost per user falls 20%, the architecture is improving even though the bill went up. Unit cost dashboards make trade-offs concrete: "this cache saves $0.002 per request at our volume".
FinOps. The FinOps Foundation describes a practice where engineering, finance and product share accountability for cloud spend, in iterative phases: Inform (visibility and allocation: tags, accounts per team, showback and chargeback), Optimise (rightsizing, commitments, architecture changes), and Operate (budgets, anomaly alerts, governance, continuous improvement). Key practices:
- mandatory cost-allocation tags, enforced by policy as code;
- a budget per team, with alerts;
- anomaly detection for sudden spend spikes (often a runaway loop or a misconfigured log level);
- a monthly review of the top 10 cost drivers;
- commitment management by a central team, with a target coverage of about 70–80% of the steady baseline.
Worked example: a video-heavy API. A service handles 2,000 RPS on average, serves 400 TB a month of media to users, and stores 1 PB. A naive design:
- Compute: 40 on-demand general-purpose instances at about $0.20 an hour each costs about $5,800 a month. Running at 15% CPU.
- Egress: 400 TB directly from object storage, at about $0.05–0.09 per GB, costs roughly $20,000–35,000 a month.
- Storage: 1 PB in a standard class, at about $0.021–0.023 per GB-month, costs about $21,000–23,000 a month.
- Cross-AZ: chatty services moving 300 TB a month across AZs costs about $6,000 a month.
Optimised:
- Compute: right-size to 16 instances, with a 3-year commitment for the baseline and spot for burst. About $1,500–2,000 a month.
- Egress: a CDN with 95% cache hit rate cuts origin egress to 20 TB. The CDN delivery cost depends on contract, but is usually substantially below list egress at this volume.
- Storage: lifecycle rules move 70% of objects, those not accessed in 90 days, to an infrequent-access or archive tier. Storage cost roughly halves, or better.
- Cross-AZ: zone-aware routing keeps most calls in-zone. Down to about $1,000 a month.
The design changes (CDN, lifecycle, zone affinity, right-sizing) matter more than any discount negotiation. Each is also an architecture decision that affects latency, availability or complexity, which is exactly the trade-off thinking that frugal architecture asks for.
Serverless vs always-on maths. A function costing about $0.20 per million invocations, plus duration charges, is far cheaper than an always-on instance at low or spiky traffic, and more expensive at sustained high traffic. Example: at 100 RPS sustained (about 260 million requests a month), with 100 ms at 512 MB each, the duration charge is about 260M × 0.1 s × 0.5 GB × about $0.0000167 per GB-second, which is about $217, plus about $52 in request charges. So about $270 a month, which is still competitive with 2–3 small always-on instances. At 2,000 RPS sustained, it's about $5,400 a month, where a few containers would cost far less. The crossover depends on duration, memory and utilisation, so calculate it for your workload (Serverless).
Frugal architecture#
Frugal architecture treats cost as a first-class non-functional requirement, designed in from the start like security, availability and performance, not cleaned up after the bill arrives. Amazon CTO Werner Vogels presented "The Frugal Architect" at AWS re:Invent 2023, with seven "laws", paraphrased here:
- Make cost a non-functional requirement. Set cost targets (cost per transaction, per user) alongside latency and availability targets, and review designs against them.
- Systems that last align cost to business. The revenue model and the cost model should move together. If revenue grows per order, costs should grow per order too, not per server provisioned for peak.
- Architecting is a series of trade-offs. Every "nine" of availability, every replica, and every millisecond of latency has a price. Spend where the business needs it, not uniformly.
- Unobserved systems lead to unknown costs. You can't optimise what you don't measure, so instrument cost like any other metric, per service and per feature.
- Cost-aware architectures implement cost controls: tiers of service, the ability to turn off non-essential features, throttles and quotas, and degradation modes that cut cost under pressure.
- Cost optimisation is incremental. Revisit regularly as usage, prices and services change. There's no one-time fix.
- Unchallenged success leads to assumptions. Question the "we've always done it this way" designs, languages and services. What was right at launch may be wasteful at scale.
Frugality in practice.
- Start simple, and on modern hardware. One large database instance with a standby, a monolith or a few services, and a managed queue will carry most products a long way. Distribute when the numbers demand it. Premature sharding and microservices multiply cost: more instances, more cross-AZ traffic, more observability, more people.
- Pick the cheapest architecture that meets the requirement. Does this need 99.99% availability, or is 99.9% fine? Does it need real-time updates, or is 1-minute batch acceptable? Does every request need the large model, or can a small one answer 80% of them?
- Make expensive work optional and controllable: feature flags to disable costly features, tiered quality of service (free-tier users get batch processing; paid users get real time), and sampling for analytics and tracing.
- Design data lifecycles: what to keep hot, what to compact and archive, what to delete.
- Measure and feed back: cost per feature on dashboards, cost reviews in design docs, and cost anomaly alerts routed to owning teams.
A public example. In 2023, the Amazon Prime Video team wrote about re-architecting an audio and video quality monitoring tool, from a distributed design built on serverless functions and step-function orchestration, into a single process running on containers, reporting a cost reduction of over 90% for that service. The lesson is not "serverless is bad". It's frugal law 7: re-examine the architecture when the workload's shape becomes clear.
When to Use It#
Cloud architecture applies to almost every new system. The questions are how much cloud, which services, and how much managed. Strong signals for public cloud, and for managed or cloud-native designs:
- Uncertain or fast-growing demand. A start-up whose traffic may grow 10× in a year can't size a data centre. Elastic capacity, with no capital spend, is decisive.
- Spiky load. Sales, launches, sports events, end-of-month batches. If peak-to-average is 5× or more, paying per use beats owning peak capacity.
- Global users. Dozens of regions and hundreds of edge locations put compute and data near users, which would take years to build yourself (CDN, Multi-Region Data).
- Small or medium teams. Managed databases, queues and Kubernetes let 5–20 engineers run systems that would otherwise need a dedicated infrastructure team.
- Need for many specialised services quickly: ML accelerators, data warehouses, streaming, search, managed identity. Building each yourself is a project. Renting it is an API call.
- Disaster recovery and multi-AZ resilience at a cost a single company could not match with physical sites (Disaster Recovery).
- Experimentation. Spin up a cluster for a day's test, then delete it.
When NOT to Use It#
- Large, steady, predictable workloads where you already have, or can hire, infrastructure expertise. Owned or colocated hardware can be dramatically cheaper at scale (Dropbox storage, 37signals). Revisit when the cloud bill is large and flat for years.
- Egress-dominated workloads: video delivery, large downloads, or data products shipping petabytes out. Egress pricing can dominate. Use CDNs with negotiated rates, or providers with cheaper or free egress, or serve from owned edge capacity.
- Strict data sovereignty or air-gapped requirements that no available region or sovereign-cloud offering satisfies (some defence, government or regulated-industry systems).
- Specialised hardware or latency needs: ultra-low-latency trading co-located with an exchange's matching engine, or custom hardware that providers don't offer (Stock Exchange).
- Multi-cloud "for resilience" without a concrete requirement. It doubles operational complexity and lowers you to the lowest common denominator. Prefer multi-AZ, then multi-region on one provider.
- Fully serverless or managed for everything at sustained high volume, when the per-request premium has clearly overtaken the cost of running containers. Re-architect selectively, as in the Prime Video example.
How to Implement It#
A practical path for a new product or organisation: a landing zone first, then workloads.
- Set up the organisation and accounts (or projects and subscriptions). Use separate accounts for production, staging, development, security tooling, logging and shared networking. Accounts are hard isolation boundaries for blast radius, quotas, billing and permissions.
- Add guardrails. Use organisation-level policies (AWS Service Control Policies, GCP Organisation Policies, Azure Policy): deny disabling audit logs, deny public object storage, restrict to approved regions, and require encryption.
- Centralise identity. Use SSO through an identity provider for humans, with role-based access per account. Use workload identities (IAM roles for service accounts, GCP Workload Identity, Azure managed identities) for software. No long-lived access keys. Federate CI via OIDC (Authentication and Authorization).
- Plan the network. Allocate non-overlapping CIDRs per VPC and region. Use a hub (transit gateway, or shared VPC) for shared egress, inspection and on-premises connectivity, plus private endpoints for provider services. Use 3 AZs in each production VPC.
- Set up logging and security monitoring. Organisation-wide audit trails (CloudTrail, Cloud Audit Logs, Azure Activity Log) into a locked logging account, threat detection services, configuration-compliance rules, and flow logs where needed (Security Fundamentals).
- Enforce tagging and cost controls. Mandatory tags (owner, team, environment, cost-centre) enforced by policy, budgets with alerts per account, cost-anomaly detection, and lifecycle policies on storage.
- Make infrastructure as code the only path. Terraform or OpenTofu, Pulumi, or provider-native tools, applied by CI/CD pipelines and reviewed in pull requests (CI/CD and Deployment).
- Deploy workloads multi-AZ from the first production release. Use managed databases with standby replicas in another AZ, autoscaling groups or Kubernetes node pools across 3 AZs, and load balancers with cross-zone health checks.
- Define and practise DR. Set RPO and RTO per system, cross-region backups and copies, and run restore tests and game days (Disaster Recovery).
- Review regularly against the Well-Architected pillars, and against unit-cost targets.
A storage lifecycle policy is one of the cheapest cost wins. This one is an S3 lifecycle configuration, as JSON, for a log bucket:
{
"Rules": [
{
"ID": "logs-tiering-and-expiry",
"Filter": { "Prefix": "logs/" },
"Status": "Enabled",
"Transitions": [
{ "Days": 30, "StorageClass": "STANDARD_IA" },
{ "Days": 90, "StorageClass": "GLACIER_IR" },
{ "Days": 365, "StorageClass": "DEEP_ARCHIVE" }
],
"Expiration": { "Days": 2555 },
"NoncurrentVersionExpiration": { "NoncurrentDays": 30 },
"AbortIncompleteMultipartUpload": { "DaysAfterInitiation": 7 }
}
]
}It moves logs to infrequent access after 30 days, to instant-retrieval archive after 90, and to deep archive after a year. It deletes them after about 7 years (a common retention requirement), expires old object versions, and cleans up abandoned multipart uploads, which otherwise accumulate silently and are billed as storage.
| Technology | Fits when |
|---|---|
| AWS | Broadest service catalogue and region footprint; most third-party tooling and hiring pool; default for many start-ups and enterprises |
| Google Cloud | Data and analytics-heavy (BigQuery), ML and TPU workloads, global network and global load balancing, Kubernetes (GKE) |
| Microsoft Azure | Microsoft-centric enterprises (Entra ID, Windows, .NET, Office 365), hybrid with Azure Arc, OpenAI model access via Azure |
| Oracle Cloud, IBM Cloud, Alibaba Cloud | Specific database or mainframe ecosystems, or regional presence (Alibaba in China) |
| Cloudflare, Fastly, Akamai | Edge delivery, edge compute (Workers), DDoS protection, zero-egress object storage (Cloudflare R2) |
| DigitalOcean, Hetzner, Linode (Akamai) | Simpler, cheaper VMs and managed basics for small teams and steady workloads |
| Terraform or OpenTofu, Pulumi | Multi-cloud or provider-agnostic infrastructure as code |
| CloudFormation or CDK, Deployment Manager, Bicep or ARM | Provider-native IaC with deep integration |
| AWS Control Tower, GCP landing zone blueprints, Azure Landing Zones | Bootstrapping multi-account organisations with guardrails |
| Kubecost or OpenCost, cloud cost explorers, FinOps tools | Cost allocation per team, service and Kubernetes namespace |
Trade-offs#
| Option | Pros | Cons | Pick when |
|---|---|---|---|
| Single AZ | Cheapest, no cross-AZ fees, simplest | One data-centre failure means downtime | Development, test, batch jobs that can rerun |
| Multi-AZ, one region | Survives AZ failure, low latency for synchronous replication | Cross-AZ data costs; region-wide events still hurt | Default for production |
| Multi-region active-passive | Survives region loss; moderate complexity | Idle standby cost; failover RTO in minutes; asynchronous replication with RPO above zero | Strict DR requirements; regulated systems |
| Multi-region active-active | Low latency globally; survives region loss quickly | Conflict handling, data residency, complex operations, double cost | Global user base with high availability needs |
| Self-hosted on VMs | Full control, cheapest per unit at scale | Highest operational load | Expert team, steady large scale, special needs |
| Managed service | Fast, reliable, patched, backed up | Premium cost, less control, quotas, some lock-in | Default for commodity components |
| Serverless | Scale to zero, no servers, pay per use | Cold starts, limits, cost at sustained high volume | Spiky, event-driven, low or medium traffic |
| Single cloud | Deep integration, simplest | Provider dependency | Most organisations |
| Multi-cloud | Leverage, best-of-breed, regulatory hedging | Double complexity, egress, lowest common denominator | Distinct workloads per cloud, or explicit regulatory need |
| On-demand capacity | Flexible | Highest unit price | Unpredictable or short-lived usage |
| Commitments or reservations | 30–70% cheaper | Commitment risk if usage drops | Steady baseline |
| Spot or preemptible | Up to about 90% cheaper | Interruptions | Fault-tolerant batch, CI, stateless tiers |
Common Pitfalls#
- Single-AZ production "to start with", which then never gets fixed until the AZ outage.
- Assuming the cloud is automatically highly available. It gives you building blocks. You must spread across AZs, replicate data, and test failover.
- Ignoring data-transfer costs: chatty cross-AZ microservices, NAT gateways in front of heavy object storage traffic (use gateway endpoints), and serving large media without a CDN.
- Over-provisioning, and never scaling in. Instances at 10% CPU, oversized Kubernetes requests, and non-production environments running all weekend.
- No tagging or ownership. Nobody knows who owns the expensive cluster, so nobody deletes it.
- Long-lived access keys in code, CI or laptops, which are then leaked. Use workload identity and OIDC.
- Public object storage by accident, a recurring source of large data leaks. Block public access at the organisation level.
- Hitting quotas in an incident. Instance limits, IPs, and API rate limits. Request increases ahead of peaks, and monitor quota usage.
- Recovery that depends on control-plane actions that may fail during the same regional event.
- Overlapping CIDR ranges that block future peering and transit connectivity.
- Lift-and-shift with no re-platforming, paying cloud prices for a data-centre design.
- Multi-cloud for its own sake, gaining complexity without a measurable benefit.
- Trusting the SLA as protection. Credits don't cover your losses. Design for the failure anyway.
Real-World Examples#
- Netflix moved its streaming infrastructure to AWS over about seven years after a 2008 database corruption incident, and announced the migration complete in early 2016. It's known for multi-region active-active designs on AWS, and for chaos engineering (Chaos Monkey). Video bytes are delivered by its own CDN, Open Connect, placed in ISPs (High Availability Design).
- Spotify announced in 2016 that it was moving its infrastructure from its own data centres to Google Cloud, citing data and analytics services among the reasons.
- Dropbox moved the bulk of its user file storage from Amazon S3 to its own Magic Pocket storage system by around 2016. That's an example of self-hosting a core, massive and steady workload, while continuing to use cloud for other needs.
- 37signals publicly documented leaving AWS for owned hardware in 2022–2023 for its main applications, reporting large expected savings for predictable workloads.
- The AWS us-east-1 event on 7 December 2021 showed how internal network and control-plane dependencies in one region affect many customers, and why static stability matters.
- Amazon Prime Video reported, in 2023, a cost reduction of over 90% by consolidating one monitoring service from a distributed serverless design into a single containerised process. That's an example of revisiting architecture as costs become clear.
- Werner Vogels' "The Frugal Architect" (re:Invent 2023) framed cost as a design-time, non-functional requirement.
Case studies that use this pattern#
- Video Streaming: object storage tiers, CDN egress economics, multi-region origins.
- File Sync and Object Storage: storage cost per GB, lifecycle, build vs buy.
- Metrics Monitoring: observability cost, retention tiers, data volume.
- Ride Hailing and Food Delivery: regional partitioning, multi-AZ, peak elasticity.
- Flash Sale and Ticket Booking: pre-scaling, quotas and pre-warming for known peaks.
- ChatGPT: GPU capacity, region selection, cost per request.
In the Interview#
Deep Dive: Static stability and capacity planning across AZs and regionsShow
The core idea. A statically stable system keeps working through a failure without needing to change anything: no new instances launched, no configuration pushed, no DNS changed. The AWS Builders' Library describes this using an analogy to a car with spare-tyre capacity already mounted. The key is pre-provisioned capacity plus data-plane-only failover.
Capacity maths for k AZs. To survive losing one of k AZs at full load, the remaining k−1 must handle all traffic. If the steady-state need is N instances, you must run N·k/(k−1) instances in total:
| AZs (k) | Total capacity as multiple of N | Overprovision |
|---|---|---|
| 2 | 2.0 N | 100% |
| 3 | 1.5 N | 50% |
| 4 | 1.33 N | 33% |
| 6 | 1.2 N | 20% |
This is why 3 AZs is the common production sweet spot: 50% headroom buys AZ-failure tolerance, versus 100% for two AZs. If you also want headroom for regular traffic peaks, say 30%, apply both: N × 1.3 × 1.5, about 1.95N instances on three AZs. Autoscaling can reduce the steady overprovision, but only if you trust that scaling works during an AZ event, when capacity may be scarce and every customer is scaling at once. Many teams keep the static N·k/(k−1) minimum for critical tiers, and let autoscaling handle growth beyond it.
Databases. A multi-AZ managed database keeps a synchronous standby in another AZ. Failover typically takes 30–120 seconds (DNS update and connection re-establishment). Applications must retry connections, and use short DNS TTLs or provider-managed endpoints. Distributed databases with quorum writes across 3 AZs (Aurora's six-copy storage across 3 AZs, Spanner, CockroachDB, Cassandra with LOCAL_QUORUM) tolerate an AZ loss with no failover step at all, because the quorum still forms.
Region failover. For multi-region active-passive:
- the standby region needs its own capacity reservations, or a tested ability to scale up fast;
- data replicates asynchronously, so RPO equals the replication lag at failure, typically seconds;
- traffic shifts through pre-configured health-check failover or routing controls, rather than ad-hoc DNS edits during the incident.
AWS Route 53 Application Recovery Controller is one example of a dedicated, highly available data-plane switch for this. For active-active, each region needs enough capacity to absorb the other's traffic, the same N·k/(k−1) maths at region level: two regions each at 50% of their capacity, or three regions each at 67%.
Dependencies. Static stability fails if a critical dependency is not stable: an auth service in one AZ, a config service whose control plane is regional, or DNS records you must change. Map every dependency on the request path, and ask: "If this AZ disappears, does this still answer?" Tests: AZ evacuation drills, zonal shift exercises, and chaos experiments that black-hole one AZ's network (High Availability Design).
Quotas and capacity scarcity. During a large AZ failure, many customers try to launch instances in the remaining AZs at once. Capacity for specific instance types may run out. Mitigations: hold reserved capacity (on-demand capacity reservations), diversify instance types in autoscaling groups, keep warm pools, and avoid relying on a single rare instance type for critical tiers.
Deep Dive: Modelling data-transfer cost before you buildShow
Data transfer is the cost most often missed in design reviews, because it doesn't appear as a resource in diagrams. Model it explicitly: list every arrow in the architecture diagram, estimate the bytes per month on it, and price each one.
Step 1: classify each flow.
- Inbound from the internet: usually free.
- Outbound to the internet: tiered, roughly $0.05–0.09 per GB at list price.
- Same AZ, private IP: usually free.
- Cross-AZ: about $0.01 per GB each way on AWS (GCP and Azure have similar inter-zone charges).
- Cross-region: about $0.02 per GB or more.
- Through a NAT gateway: an extra processing fee per GB.
- Through gateway endpoints (S3 and DynamoDB on AWS): no data charge.
- To a CDN from origin: discounted or free on some providers' own CDNs.
Step 2: worked example. A microservice architecture handles 5,000 RPS. Each request triggers 6 internal calls, each about 20 KB of request plus response. Services are spread across 3 AZs, with random routing, so about two-thirds of calls cross AZs.
- Internal bytes: 5,000 × 6 × 20 KB is 600 MB/s, or about 1.55 PB a month.
- Cross-AZ share: two-thirds of that is about 1.04 PB.
- Each byte crossing an AZ boundary is billed at about $0.01 per GB in each direction, about $0.02 per GB in total. So 1.04 PB is about 1,040,000 GB × $0.02, roughly $20,000 a month.
With zone-aware routing (topology-aware routing in Kubernetes, locality-aware load balancing in Envoy or a service mesh), most calls stay in-zone. If 90% stay local, cross-AZ traffic drops to about 10% of the 1.55 PB, roughly $3,100 a month. That saves about $17,000 a month with no new hardware. The trade-off: in-zone routing can skew load if zones are unbalanced, so meshes fall back to cross-zone routing when local capacity is low.
Step 3: replication. A Kafka cluster with replication factor 3 across 3 AZs, ingesting 100 MB/s, replicates each byte to two other AZs: 200 MB/s cross-AZ, about 518 TB a month, which at about $0.02 per GB round-trip billing is on the order of $10,000 a month. Consumers in other AZs add more. Mitigations: rack-aware consumers that fetch from the nearest replica (Kafka KIP-392, "fetch from follower"), compression (zstd or lz4 often reduce payloads 3–5×), and right-sizing the replication factor for non-critical topics (Kafka).
Step 4: egress to users. 400 TB a month of media at about $0.05–0.09 per GB costs about $20,000–36,000 a month from origin. A CDN with a 95% hit ratio sends only 20 TB from origin. CDN delivery pricing is contract-dependent, but at this volume it's usually much lower per GB than raw cloud egress. Some providers charge nothing between their object storage and their CDN. Compression and modern codecs (AV1 over H.264 can cut bitrates substantially at equal quality) reduce bytes directly (Video Streaming).
Step 5: put it in the design doc. A table with the flow, bytes per month, price per GB, monthly cost, and mitigation turns hidden costs into design decisions. Re-check after launch with cost-allocation tags and flow logs. Real traffic patterns often differ from estimates.
Deep Dive: Multi-account security, landing zones and portable architectureShow
Why many accounts. One account for everything means one IAM namespace, shared quotas, one blast radius for credential leaks, and messy cost allocation. A multi-account (or multi-project or multi-subscription) layout gives hard isolation:
- separate production and non-production accounts, so a developer mistake in dev can't touch prod;
- a security account that owns audit logs, which workload accounts cannot delete;
- per-team or per-service accounts, so quotas and costs are naturally separated.
AWS Organizations, GCP's resource hierarchy (organisation, folders, projects) and Azure management groups all support this with inherited policies.
Guardrails as code. Preventive controls (service control policies, organisation policies) deny dangerous actions outright, regardless of IAM permissions within an account. Examples:
- block regions you don't use (reducing attack surface and data-residency risk);
- forbid disabling CloudTrail;
- forbid public S3 buckets;
- require encryption on new volumes.
Detective controls (config rules, security posture tools) flag drift. Keep both in version control, and roll them out like code: test in a sandbox organisational unit first, because an over-broad deny policy can break production at once.
Identity. Humans use SSO with short-lived role sessions, and MFA (prefer phishing-resistant passkeys or security keys). Workloads use attached roles: instance profiles, Kubernetes service account federation (IRSA or EKS Pod Identity on AWS, Workload Identity on GKE), and managed identities on Azure. CI pipelines use OIDC federation, with no stored secrets. Break-glass accounts exist for emergencies, with alerts on use. Permission boundaries and least-privilege policies, generated from access logs, shrink blast radius (Authentication and Authorization).
Networking at scale. A hub-and-spoke design (a transit gateway, or a shared VPC host project) centralises egress inspection, private DNS, on-premises connectivity through Direct Connect, Interconnect or ExpressRoute, and shared services. Spokes are application VPCs, owned by teams. Central IP address management prevents overlaps. Private endpoints keep traffic to managed services off the internet. Egress through a central firewall or proxy, with an allow-list, limits data exfiltration and SSRF damage (Security Fundamentals).
Portability without paralysis. A pragmatic portability strategy:
- Portable compute: containers and Kubernetes, or at least OCI images, so workloads can move.
- Portable infrastructure definitions: Terraform or OpenTofu modules per environment.
- Open protocols and formats for data: PostgreSQL and MySQL wire protocols, Kafka protocol, S3-compatible APIs, Parquet and Iceberg tables in object storage, OpenTelemetry for telemetry.
- Adapters around proprietary services only where the switching cost is high and the probability of switching is real. Wrapping every SDK call "just in case" costs more than it saves.
- Documented exit plans for critical dependencies, as some regulators now expect (for example, the EU's Digital Operational Resilience Act for financial entities requires exit strategies for critical ICT third-party providers).
The goal is a known, bounded exit cost, not zero lock-in. Use the best managed services where they deliver value, and keep the data and the core logic in forms you can take with you.
Key Takeaways#
- Regions and AZs are your failure domains. Run production across 3 AZs, and plan explicitly for region-level events. Static stability means pre-provisioned capacity (N·k/(k−1)) and failover through the data plane.
- A VPC is your private network. Plan non-overlapping CIDRs, use public and private subnets, prefer private endpoints over NAT for provider services, and use security groups as the main firewall.
- The big three clouds map closely, but semantics, consistency and limits differ. Name the quotas your design depends on.
- Default to managed services for commodity components. Self-host when the scale is steady and huge, the component is core to your edge, or features are missing, and you have the expertise.
- Cloud-native means: design for failure, elasticity, cattle not pets, automation, loose coupling, observability and least privilege. Use cells and shuffle sharding to contain blast radius.
- Cost is architecture. The hidden costs are egress, cross-AZ and NAT traffic, idle and over-provisioned resources, logs and metrics, and storage that never tiers or expires. Match pricing models to usage: commitments for the baseline, spot for interruptible work, on-demand for the rest.
- Frugal architecture treats cost as a non-functional requirement. Track unit costs, implement cost controls, and keep challenging assumptions, because modern machines are big enough that premature distribution is often the most expensive mistake.