Skip to main content
HS
HiSETSuccess
LeetCode Prep

System Design

Comprehensive interview guide: scalability, databases, distributed systems, cloud architecture, and full case-study walkthroughs — plus adaptive quizzes.

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.

NeedAWSGCPAzure
Object storageS3GCSBlob Storage
Managed SQLRDS / AuroraCloud SQL / AlloyDBAzure SQL
NoSQL KV/DocumentDynamoDBFirestore / SpannerCosmos DB
QueueSQSCloud Pub/SubService Bus
StreamKinesis / MSKDataflow / Pub/SubEvent Hubs
Load balancerALB / NLBCloud Load BalancingApplication Gateway
CDNCloudFrontCloud CDNAzure 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.

ModelUnit of scaleCold startBest for
VM (EC2, GCE)InstanceMinutes (AMI boot)Legacy apps, GPU, full OS needs
Container (EKS, GKE)Pod / taskSecondsMicroservices, portable workloads
Serverless (Lambda)Function invocation100ms–2sEvent-driven, spiky, short tasks
PaaS (App Engine, Elastic Beanstalk)App deploymentVariesSimple 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.

TypeAccessDurabilityUse case
Object (S3, GCS)HTTP API, key-based11 nines (S3)Images, backups, data lake
Block (EBS, PD)Mount as disk on VMReplicated within AZDB files, boot volumes
File (EFS, Filestore)NFS mount, sharedRegionalShared config, CMS uploads
Managed SQL (RDS)SQL protocolAutomated backups, Multi-AZTransactional core
Managed NoSQL (DynamoDB)API / SDKMulti-AZ replicationKey-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.

SignalWhen to scale onCaveat
CPU utilizationCompute-bound workloadsMisleading if I/O blocked
Request count / RPSStateless web tierNeed capacity model per instance
Queue depthWorker poolsScale before backlog grows unbounded
Custom metricBusiness KPI (orders/min)Requires CloudWatch/Prometheus pipeline
SchedulePredictable 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.

PatternScopeFailoverConsistency
Multi-AZ (active-passive DB)Same region, different zonesAutomatic (minutes)Sync replication; strong
Multi-region active-passivePrimary + DR regionManual or DNS failoverAsync replication; RPO > 0
Multi-region active-activeBoth regions serve trafficGlobal LB routes around failureConflict resolution needed
Stretch clusterLow-latency zones onlyFast failoverNetwork partition risk
Active-active multi-region
        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.

TriggerFlowExample
S3 ObjectCreatedUpload → Lambda → thumbnailImage processing pipeline
SQS messageQueue → Lambda batch consumeEmail notification sender
EventBridge scheduleCron → LambdaNightly report generation
DynamoDB StreamsTable change → LambdaReal-time index sync
API Gateway HTTPRequest → LambdaLightweight 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.

PillarDataTools / patterns
MetricsTime-series numbersPrometheus, CloudWatch, Datadog
LogsStructured event recordsELK, CloudWatch Logs, Loki
TracesRequest path across servicesJaeger, X-Ray, OpenTelemetry
ProfilesCPU/memory flame graphspyroscope, continuous profiler
  1. Define SLIs: latency p99, availability, error rate, throughput
  2. Set SLOs (target) and SLAs (contractual consequence)
  3. Error budget = 1 - SLO; when exhausted, freeze features, fix reliability
  4. Alert on symptoms (user-facing SLO burn rate), not every internal blip
  5. 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.

StrategySavingsTradeoff
Reserved / Savings Plans30–70% vs on-demandCommitment term (1–3 yr)
Spot / Preemptible instances60–90% discountCan be terminated; stateless only
Right-sizingEliminate over-provisionRequires utilization monitoring
S3 lifecycle policiesAuto-tier to GlacierRetrieval latency for cold data
Cache aggressivelyReduce DB compute + egressStaleness management
NAT gateway optimizationVPC endpoints for S3/DynamoDBArchitecture 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.'