Chapter
Cloud System Design
Cloud primitives, autoscaling, serverless, observability, and cost control.
Cloud Building Blocks
Major clouds offer the same conceptual building blocks with different names: compute (VMs, containers, functions), managed databases, object storage, VPC networking, load balancers, and managed messaging. Design in concepts first, map to services second.
| Need | AWS | GCP | Azure |
|---|---|---|---|
| Object storage | S3 | GCS | Blob Storage |
| Managed SQL | RDS / Aurora | Cloud SQL / AlloyDB | Azure SQL |
| NoSQL KV/Document | DynamoDB | Firestore / Spanner | Cosmos DB |
| Queue | SQS | Cloud Pub/Sub | Service Bus |
| Stream | Kinesis / MSK | Dataflow / Pub/Sub | Event Hubs |
| Load balancer | ALB / NLB | Cloud Load Balancing | Application Gateway |
| CDN | CloudFront | Cloud CDN | Azure CDN / Front Door |
- VPC: private subnets for DB/workers; public subnets for LB only
- IAM: least-privilege roles per service — no long-lived keys in code
- Managed services reduce ops but create vendor coupling — acknowledge tradeoff
- Multi-AZ by default for production managed databases
Stay vendor-neutral first
Draw 'object store', 'managed queue', 'NoSQL table' before naming S3/SQS/DynamoDB. Map to AWS if interviewer asks or works there.
Compute: VM vs Container vs Serverless
Compute choice balances control, portability, scaling granularity, and operational overhead. VMs give full OS control. Containers (Docker + Kubernetes/ECS) package apps with dependencies. Serverless (Lambda, Cloud Functions) runs code on demand without managing servers.
| Model | Unit of scale | Cold start | Best for |
|---|---|---|---|
| VM (EC2, GCE) | Instance | Minutes (AMI boot) | Legacy apps, GPU, full OS needs |
| Container (EKS, GKE) | Pod / task | Seconds | Microservices, portable workloads |
| Serverless (Lambda) | Function invocation | 100ms–2s | Event-driven, spiky, short tasks |
| PaaS (App Engine, Elastic Beanstalk) | App deployment | Varies | Simple web apps, rapid deploy |
- Kubernetes: declarative scaling, service mesh, but operational complexity
- Fargate / Cloud Run: container without managing nodes
- Serverless limits: max duration (15 min Lambda), memory, no persistent local disk
- Hybrid: API on containers, async workers on serverless
Interview default
Start with managed containers or PaaS for the main API. Add serverless for event triggers (S3 upload → thumbnail). Mention VMs only for special requirements (custom kernel, license software).
Storage: Object/Block/Managed DB
Cloud storage tiers serve different access patterns. Object storage holds unstructured blobs at massive scale. Block storage provides disk volumes for VMs. Managed databases offload backups, patching, replication, and failover.
| Type | Access | Durability | Use case |
|---|---|---|---|
| Object (S3, GCS) | HTTP API, key-based | 11 nines (S3) | Images, backups, data lake |
| Block (EBS, PD) | Mount as disk on VM | Replicated within AZ | DB files, boot volumes |
| File (EFS, Filestore) | NFS mount, shared | Regional | Shared config, CMS uploads |
| Managed SQL (RDS) | SQL protocol | Automated backups, Multi-AZ | Transactional core |
| Managed NoSQL (DynamoDB) | API / SDK | Multi-AZ replication | Key-value at scale |
- S3 storage classes: Standard, IA, Glacier — lifecycle policies auto-tier
- EBS vs instance store: EBS persists after stop; instance store is ephemeral but fast
- Read replicas and Multi-AZ are different — replicas for read scale, Multi-AZ for failover
- Egress cost: moving data out of cloud is expensive — design data locality
Don't put files in DB
Store metadata in DB, blobs in object storage. Serve via signed URLs or CDN. Mention this in any media upload design.
Autoscaling & Load
Autoscaling dynamically adjusts capacity based on metrics — CPU, request count, queue depth, or custom business metrics. Effective scaling matches the bottleneck resource and accounts for warmup time and scale-in safety.
| Signal | When to scale on | Caveat |
|---|---|---|
| CPU utilization | Compute-bound workloads | Misleading if I/O blocked |
| Request count / RPS | Stateless web tier | Need capacity model per instance |
| Queue depth | Worker pools | Scale before backlog grows unbounded |
| Custom metric | Business KPI (orders/min) | Requires CloudWatch/Prometheus pipeline |
| Schedule | Predictable traffic (9am peak) | Pre-warm before spike |
- Target tracking: maintain 70% CPU → add/remove instances automatically
- Cooldown period prevents flapping during oscillating load
- Scale-out fast, scale-in slow — protect against removing needed capacity
- Predictive scaling (ML-based) for known patterns (Prime Day, Black Friday)
Capacity planning + autoscaling
Estimate peak QPS from back-of-envelope, divide by per-instance capacity, add 30% headroom. Autoscaling handles unexpected spikes; baseline capacity handles predictable load cost-effectively.
Multi-AZ & Multi-Region
Multi-AZ deploys across availability zones within a region for zone-level fault tolerance — typically synchronous replication for databases. Multi-region adds geographic redundancy, lower global latency, and disaster recovery at the cost of complexity and consistency challenges.
| Pattern | Scope | Failover | Consistency |
|---|---|---|---|
| Multi-AZ (active-passive DB) | Same region, different zones | Automatic (minutes) | Sync replication; strong |
| Multi-region active-passive | Primary + DR region | Manual or DNS failover | Async replication; RPO > 0 |
| Multi-region active-active | Both regions serve traffic | Global LB routes around failure | Conflict resolution needed |
| Stretch cluster | Low-latency zones only | Fast failover | Network partition risk |
Global Load Balancer (GeoDNS / Anycast)
/ \
Region US-EAST Region EU-WEST
AZ-a AZ-b AZ-c AZ-a AZ-b AZ-c
App tier App tier
Regional DB ◄──async repl──► Regional DB
(conflict resolution / CRDTs for writes)- RPO: max data loss on failover; RTO: max downtime to restore
- Route 53 health checks + DNS failover for regional DR
- Data residency regulations may require EU data stays in EU
- Global tables (DynamoDB) or Spanner for multi-region strong consistency
Serverless & Event-Driven
Event-driven architecture reacts to state changes (file uploaded, order placed, timer fired) rather than polling. Serverless functions are natural event handlers — pay per invocation, zero idle cost, but constrained by runtime limits and cold starts.
| Trigger | Flow | Example |
|---|---|---|
| S3 ObjectCreated | Upload → Lambda → thumbnail | Image processing pipeline |
| SQS message | Queue → Lambda batch consume | Email notification sender |
| EventBridge schedule | Cron → Lambda | Nightly report generation |
| DynamoDB Streams | Table change → Lambda | Real-time index sync |
| API Gateway HTTP | Request → Lambda | Lightweight REST API |
- Step Functions / Cloud Workflows for multi-step orchestration with retries
- EventBridge as central event bus with schema registry and routing rules
- Cold start mitigation: provisioned concurrency, smaller runtimes, ARM Graviton
- Avoid long chains of sync Lambda calls — use async events or Step Functions
When serverless fits
Image thumbnails, webhooks, ETL glue, scheduled jobs. Poor fit: long-running compute, WebSockets at scale, tight p99 latency with cold starts, stateful sessions.
Observability & SLOs
Observability is the ability to understand system behavior from external outputs: metrics, logs, and traces. SLOs (Service Level Objectives) define target reliability (e.g. 99.9% availability, p99 < 200ms) and drive engineering priorities via error budgets.
| Pillar | Data | Tools / patterns |
|---|---|---|
| Metrics | Time-series numbers | Prometheus, CloudWatch, Datadog |
| Logs | Structured event records | ELK, CloudWatch Logs, Loki |
| Traces | Request path across services | Jaeger, X-Ray, OpenTelemetry |
| Profiles | CPU/memory flame graphs | pyroscope, continuous profiler |
- Define SLIs: latency p99, availability, error rate, throughput
- Set SLOs (target) and SLAs (contractual consequence)
- Error budget = 1 - SLO; when exhausted, freeze features, fix reliability
- Alert on symptoms (user-facing SLO burn rate), not every internal blip
- RED method: Rate, Errors, Duration for services
Wrap-up mention
Always close with: 'I'd monitor p99 latency, error rate, queue lag, and cache hit ratio. Page on SLO burn rate > 2x. Distributed tracing across API → cache → DB.'
Cost Optimization
Cloud costs scale with usage — compute hours, storage GB, egress bandwidth, and API calls. Cost optimization is a continuous practice: right-size resources, use reserved capacity, tier storage, and architect for efficient data transfer.
| Strategy | Savings | Tradeoff |
|---|---|---|
| Reserved / Savings Plans | 30–70% vs on-demand | Commitment term (1–3 yr) |
| Spot / Preemptible instances | 60–90% discount | Can be terminated; stateless only |
| Right-sizing | Eliminate over-provision | Requires utilization monitoring |
| S3 lifecycle policies | Auto-tier to Glacier | Retrieval latency for cold data |
| Cache aggressively | Reduce DB compute + egress | Staleness management |
| NAT gateway optimization | VPC endpoints for S3/DynamoDB | Architecture change |
- Egress is often the surprise bill — CDN and regional data locality help
- Serverless can be cheaper at low volume; containers cheaper at steady high volume
- Tag resources by team/service for chargeback and anomaly detection
- Review top 10 cost drivers monthly; set billing alerts
Interview mention
After designing for scale, note: 'At steady state I'd reserved-instance the baseline, spot for batch workers, lifecycle cold data to IA/Glacier, and front static assets with CDN to cut egress.'