Cloud Architecture and Operations Fundamentals
Hard · System Design · Software Engineer · Technical Screen
Prompt
Architect, ship, and run an internet-facing cloud platform engineered to scale horizontally and withstand infrastructure failures while serving millions of daily users. Ground your design in concrete workload assumptions and walk through each of these foundational layers:
- Cloud Service Abstractions & Compute: Compare IaaS, PaaS, and serverless offerings—when each model shines and where it falls short—then select and justify your compute substrates across virtual machines, containers, and event-driven functions.
- Traffic Distribution & Stateless Elasticity: Detail edge and regional load balancing, horizontal autoscaling rules, and how application instances stay completely stateless.
- Polyglot Storage & Data Protection: Match relational databases, NoSQL stores, object storage, and in-memory caches to distinct access patterns, explaining each store's consistency semantics, write durability, and backup/recovery workflow.
- Network Topology & Zero-Trust Boundaries: Lay out VPC addressing, subnet segmentation, security groups, firewalls, outbound NAT routing, CDN edge delivery, and internal zero-trust enforcement.
- Identity, Secrets & Cryptography: Specify least-privilege IAM bindings, runtime secret delivery, encryption in transit and at rest, and non-disruptive key/credential rotation.
- Resilience & Disaster Recovery: Show how multi-zone redundancy and cross-region failover satisfy explicit Recovery Time Objective (RTO) and Recovery Point Objective (RPO) targets.
- Telemetry, SLOs & Cost Governance: Cover metrics, structured logs, distributed traces, error-budget alerting, and cloud spend attribution/optimization.
- Automated Delivery & Safe Rollouts: Describe Infrastructure as Code (IaC), CI/CD promotion pipelines, blue/green versus canary release mechanics, and fast code/schema rollback strategies.
Scope & Expectations
- Workload-Driven Choices: Anchor your compute, caching, and database selections in realistic traffic ratios, concurrency estimates, and latency budgets rather than abstract definitions.
- End-to-End Cloud Topology: Connect edge caching, segmented VPC subnets, compute tiers, and managed data stores without single points of failure.
- Defense in Depth & Recovery Rigor: Separate hardware failover from corruption-proof backups, enforce cryptographic workload identity, and make RTO/RPO trade-offs explicit.
- Production Operations: Tie together progressive deployments, user-centric SLO alerts, and pragmatic FinOps controls.
Step-by-step walkthrough
Clarify requirements and anchor on a concrete retail application
Answering nine cloud-computing topics in the abstract quickly turns into a dry dictionary of acronyms. Anchoring every decision on one concrete multi-million-user system lets us justify compute, networking, databases, security, disaster recovery, and cost choices with real numbers. Here we design an omnichannel home-improvement retail web application (browsing 1,000,000+ catalog items, checking real-time aisle inventory across ~2,000 physical stores, managing a cart, paying at checkout, and viewing orders). We use AWS service names for concreteness; Google Cloud and Azure provide direct equivalents for every layer.
Functional requirements
- Browse & search: product detail pages, faceted search, and local per-store inventory checks.
- Cart & checkout: persistent carts for guests and signed-in shoppers, tokenized card checkout, store pickup reservation, and order history.
- Back-office & async workflows: catalog/price updates, merchant image uploads, order confirmation emails, image thumbnail generation, and analytics pipelines.
Non-functional targets and key definitions
- Scale: 5,000,000 daily active users (DAU), with a seasonal retail peak (Spring sale / Black Friday) at 3x the normal daily peak.
- Service-level objectives (SLOs)—measurable reliability targets over a 30-day (
43,200-minute) month:- Browsing API: 99.9% availability (
43.2 minutesmonthly error budget) and p95 latency < 300 ms (95% of requests finish under 300 ms). - Checkout API: 99.95% availability (
21.6 minutesmonthly error budget) and p99 latency < 1 s (excluding external card-network processing time).
- Browsing API: 99.9% availability (
- Fault tolerance & disaster recovery:
- Survive losing an entire availability zone (AZ)—one or more physical data centers inside a region with independent power, cooling, and networking—with zero visible outage and zero data loss.
- Survive losing an entire cloud region (geographic cluster of AZs) within explicit targets for RTO (recovery time objective: maximum time to restore service) and RPO (recovery point objective: maximum age of recent writes that could be lost): RTO <= 30 minutes and RPO < 1 minute for checkout/orders, and RTO <= 15 minutes for browsing.
- Security & FinOps: zero raw credit-card numbers touching our infrastructure, least-privilege identity everywhere, encryption in transit and at rest, and per-team cost attribution.
Back-of-the-envelope traffic, compute, and storage math
1. Traffic profile Daily active users 5,000,000 DAU Page views (15/user/day) 75,000,000 views/day Dynamic API calls (4/view) 300,000,000 calls/day Average API rate 300M / 86,400 s = ~3,500 req/s Normal daily peak (3x avg) = ~10,400 req/s Seasonal peak (3x normal = 9x avg) = ~31,000 req/s Static assets (40 files/view) 3,000,000,000 req/day (~150 TB/day served by CDN; at 95% CDN hit rate, 7.5 TB/day from origin) 2. Write volume Completed orders (1% of DAU) 50,000 orders/day (~0.6/s avg, ~5-10/s seasonal peak) Cart mutations (20% of DAU * 3) 3,000,000 writes/day (~35/s avg, ~300/s seasonal peak) 3. API container capacity (1-vCPU pod serves ~200 req/s at 60% target CPU; verify via load test) Pods needed at normal peak 10,400 / 200 = 52 pods Survive losing 1 of 3 AZs 2 AZs must hold >= 52 = 26 pods/AZ * 3 AZs = 78 pods (1.5x) Seasonal Black Friday peak ceil(31,000 / 200) in 2 AZs -> 78 pods/AZ * 3 AZs = 234 pods 4. Storage footprint Product catalog 1,000,000 SKUs * 5 KB = ~5 GB (fits easily in SQL + RAM cache) Product images (8 sizes/SKU) 1M * 8 * 300 KB = ~2.4 TB in object storage Structured JSON logs 300M req/day * 2 KB = ~600 GB/day (~8.4 TB for 14 hot days)Four architectural takeaways from the numbers:
- Reads outnumber order writes by > 5,000 to 1: one relational primary handles 5–10 orders/s without breaking a sweat; our real scaling job is shielding it from 10k–31k reads/s via edge caching and Redis.
- Static assets are 10x our API request count: serving 3B image/JS requests/day directly from a CDN (content delivery network of global edge caches) keeps 95% of bandwidth off our cloud region.
- Peak is 9x average: paying for Black Friday hardware all year wastes ~80% of compute spend, so stateless horizontal autoscaling is mandatory.
- Instant AZ-failure survival costs 1.5x baseline pods (78 instead of 52)—an explicit cost-for-uptime choice.
Public API contracts: edge caching, idempotency, and direct uploads
GET /v1/products/{sku} CDN-cacheable (Cache-Control: public, max-age=60, stale-if-error=3600) GET /v1/search?q=drill&store=104 CDN-cacheable 30 s for anonymous shoppers GET /v1/stores/{store_id}/stock?sku=... Short 10 s TTL (physical store stock changes often) GET /v1/cart Private, never edge-cached; strongly consistent read PUT /v1/cart/items/{sku} {"qty": 2} Naturally idempotent (sets absolute quantity = 2, not "+1") POST /v1/checkout Requires `Idempotency-Key: <uuid>` header body: {"cart_version": 7, "payment_token": "tok_...", "pickup_store": 104} -> 201 {"order_id": "..."} | 409 Cart Changed | 402 Payment Declined POST /v1/uploads/images Returns a short-lived pre-signed S3 upload URL Asynchronous domain events (published via transactional outbox -> message queue): order.placed -> confirmation email function, analytics stream, store pickup fulfillment image.uploaded -> serverless thumbnail/WebP resizer function product.updated -> search re-indexer, Redis/CDN cache invalidation- Why
Idempotency-KeyonPOST /v1/checkout? Mobile networks drop packets constantly. An idempotency key (a client-generated UUID saved in a unique database column alongside the first checkout response) ensures that if a shopper's phone retries after a timeout, our server returns the existingorder_idinstead of charging their credit card twice. - Why
payment_tokeninstead of card numbers? The browser submits raw card digits directly to the payment processor's hosted iframe and hands us an opaque token, keeping our cloud servers out of heavy PCI DSS (payment-card security) scope. - Why pre-signed object-storage URLs? Merchants upload multi-megabyte product photos straight from the browser to object storage, keeping API pods fast, tiny, and stateless.
- Why
Data stores: matching workload, consistency, durability, and backups
No single database excels at atomic money transfers, millions of ephemeral guest carts, full-text search, and petabytes of images. We pick the right managed store per workload:
Workload Managed Store (AWS Example) Consistency Model Durability, Backup, and Restore Orders, payments, store stock, catalog source of truth Relational SQL: Amazon RDS PostgreSQL (Multi-AZ + 2 read replicas) Strong ACID on primary; async read replicas lag by ms–s Synchronous standby in AZ-b; PITR (point-in-time recovery via snapshots + transaction logs) for 35 days; daily snapshot copied to an isolated, vault-locked backup account in Region B Shopping carts Key-Value NoSQL: DynamoDB ( PK = cart_id, 30-day TTL)Strongly consistent reads per cart_idAutomatically replicated across 3 AZs; continuous PITR enabled; Global Table async replication to Region B Hot catalog cache & rate limits In-memory store: ElastiCache (Redis) (primary + replica across AZs) Cache-aside (eventual up to TTL; deleted on write) Ephemeral/rebuildable from PostgreSQL; multi-AZ replica avoids cold-cache latency spikes Faceted product search Search index: OpenSearch across 3 AZs Eventual (~1–2 s behind SQL via outbox stream) Derived data; rebuilt from PostgreSQL if ever corrupted Images, invoices, log archives, DB backups Object storage: Amazon S3 Strong read-after-write consistency Engineered for 99.999999999%(11 nines) durability across >= 3 AZs; Versioning + immutable Object Lock on backup bucketsWhy SQL transactions matter for inventory: checking out executes
UPDATE stock SET reserved = reserved + :qty WHERE store_id = :store_id AND sku = :sku AND on_hand - reserved >= :qtyinside the same ACID transaction (atomic, consistent, isolated, durable unit of work that commits completely or rolls back completely) as insertingorders,payments, and anoutboxevent row—making it mathematically impossible to oversell the last power drill at Store #104. Meanwhile, Redis absorbs 95% of the ~5,200/s catalog reads so PostgreSQL sees a relaxed ~260 reads/s.Crucial distinction—replication is NOT backup: Multi-AZ synchronous replication protects against hardware and power failures, but it faithfully copies an accidental
DROP TABLEor buggy migration to the standby in 1 millisecond! Only immutable cross-account PITR backups—verified by an automated monthly restore drill into a sandbox account—protect against human error, software bugs, or ransomware.Cloud network design: VPC, subnets, NAT, and CDN
A VPC (virtual private cloud) is our isolated private network inside the cloud provider (
10.0.0.0/16= 65,536 private IPs), carved into subnets (IP ranges pinned to one AZ whose routing tables control internet reachability):[ Shoppers (Web / Mobile) ] | Authoritative DNS (health-checked failover, 60 s TTL) v [ CDN + WAF + DDoS Shield ] -----------------> [ S3 Bucket: images & JS (private; CDN-only access) ] | HTTPS (dynamic /v1/* calls only) v REGION A (Primary) — VPC 10.0.0.0/16 spanning 3 Availability Zones (AZ-a, AZ-b, AZ-c) +--------------------------------------------------------------------------------------------------+ | Public Subnets (/24 per AZ = 251 usable IPs): Layer-7 Load Balancer nodes + 1 NAT Gateway/AZ | |--------------------------------------------------------------------------------------------------| | Private App Subnets (/19 per AZ = 8,187 usable IPs): | | Managed Kubernetes (EKS) worker VMs -> API pods (catalog, search, cart, checkout, orders) | | Service mesh sidecars (mTLS) + Async queue workers + Serverless functions (resize, email) | |--------------------------------------------------------------------------------------------------| | Isolated Data Subnets (/22 per AZ = 1,019 usable IPs — ZERO route to internet or NAT): | | RDS PostgreSQL Primary (AZ-a) ===sync===> Standby (AZ-b) + Read Replicas | | Redis Primary (AZ-a) + Replica (AZ-b) | OpenSearch 3-AZ cluster | |--------------------------------------------------------------------------------------------------| | Private VPC Endpoints: S3, DynamoDB, KMS, Secrets Manager, Container Registry (stays off NAT!) | | Outbound Internet Path: App Subnet -> NAT Gateway -> Egress Firewall Allowlist -> Payment/Email | +--------------------------------------------------------------------------------------------------+ | Asynchronous cross-region replication (RDS replica, DynamoDB Global Table, S3 CRR) v REGION B (Warm Standby DR): identical Terraform VPC, scaled-down EKS cluster, live DB read replica Isolated Cloud Accounts: [ prod ] [ staging ] [ dev ] [ security-audit ] [ immutable-backups ]- Why three subnet tiers? Only load balancers and NAT gateways (network address translation gateways that let private pods initiate outbound calls to external payment APIs while blocking all unsolicited inbound internet connections) touch public subnets. Data subnets have no route to the internet at all.
- Why
/19(8,192 IPs) for private app subnets? Container networking assigns a real VPC IP to every pod plus warm spare IPs on every worker VM; during a Black Friday rolling deploy (234 * 2 = 468pods + nodes + future services), tiny/24subnets (251usable IPs) would run out of IP addresses and block scaling! - Why one NAT gateway per AZ + VPC endpoints? Sharing a single NAT gateway in AZ-a would break outbound payment calls in AZ-b and AZ-c if AZ-a went dark; VPC endpoints route S3 and DynamoDB traffic privately over the cloud backbone without paying per-gigabyte NAT processing fees.
Deep dive 1: IaaS vs. PaaS vs. serverless and choosing compute
Cloud compute models trade low-level OS control against operational overhead and scaling granularity:
Model What You Manage Scaling & Cold Start Billing & Best Fit IaaS (Virtual Machines, OS kernel, security patches, Minutes to boot a VM; Per VM-hour (busy or idle); e.g., EC2) runtime, scaling, app code coarse VM-level scaling custom kernels, GPUs, legacy COTS PaaS / Managed Containers Container image & app config Seconds to start a pod; Per vCPU/GB-hour (commit discounts); (e.g., EKS, ECS Fargate) (cloud patches host OS/CP) long-lived DB pools steady, high-throughput APIs Serverless Functions Function code only Milliseconds per event; Per invocation + GB-second ($0 idle); (FaaS, e.g., Lambda) (15 min max run, quotas) cold starts hurt p99 spiky, event-driven background tasksJustifying our hybrid compute split with Little's law (
concurrency = rate * latency):- Core customer APIs -> Containers on Managed Kubernetes (EKS): At our 24/7 average of
3,500 req/sand50 mslatency,3,500 * 0.050 = 175requests are continuously in flight (520at daily peak). Because concurrency never drops to zero, serverless functions' main superpower (scale-to-zero cost savings) saves $0, while per-invocation fees, occasional cold starts in the p99, and 520 separate unpooled database connections work against FaaS. Long-lived containers keep warm connection pools, avoid cold starts, and qualify for 1–3 year Savings Plans on the 78-pod baseline. (Note: for smaller engineering orgs that do not need Kubernetes' multi-team ecosystem, serverless containers like AWS ECS Fargate or Cloud Run give the exact same container benefits with far less cluster-upgrade maintenance.) - Bursty background jobs -> Serverless Functions (Lambda): Resizing 10,000 product images uploaded by a merchant at 2 PM and doing zero work at 3 AM, sending order confirmation emails, and processing payment webhooks are short, asynchronous, and spiky—ideal for pay-per-invocation functions with per-function reserved concurrency caps (e.g., max 50 concurrent email functions) so a burst never starves regional quotas.
- Stateful stores -> Managed PaaS (RDS, DynamoDB, ElastiCache, S3): Hand-rolling PostgreSQL failover and WAL archiving on raw IaaS VMs adds outage risk without differentiating a retailer.
- Core customer APIs -> Containers on Managed Kubernetes (EKS): At our 24/7 average of
Deep dive 2: load balancing, autoscaling policies, and stateless services
1. Multi-layer load balancing and safe health checks
- Edge (DNS + CDN): DNS routes users to the healthy region; the CDN terminates TLS near the shopper, caches public catalog/search JSON, and serves cached pages via
stale-if-errorif the origin stumbles. - Regional Layer-7 Application Load Balancer (ALB): spans all 3 AZs, routes paths (
/v1/checkoutvs./v1/search), balances via least outstanding requests (avoiding piling requests onto a pod momentarily slowed by a cache miss), and drains connections for 30 s during deploys. - Health-check rule: liveness (
/livez) restarts deadlocked pods; readiness (/readyz) checks only local pod warmup—never PostgreSQL or Redis—so a brief database blip never tricks the ALB into marking all 78 pods unhealthy at once.
2. Fast-out, slow-in autoscaling + flash-sale headroom
Pod autoscaler (HPA) Trigger on 60% CPU or 200 req/s per pod. Scale OUT aggressively (+100% pods per 30 s) to catch spikes; Scale IN conservatively (-10% per 5 min) to prevent flapping. Enforce >= 26 pods/AZ (78 min total) via AZ topology spread constraints. Node autoscaler Karpenter / Cluster Autoscaler boots new worker VMs in ~60-120 s. Run low-priority "pause" placeholder pods holding ~20% spare VM headroom: real pods evict placeholders and start in 2 seconds while new VMs boot! Scheduled pre-scaling Pre-scale to 234+ pods the night before Black Friday or major promos.3. Stateless pod rules & downstream bottleneck protection
- Zero local state: auth uses 15-minute signed JWT access tokens + database-backed refresh tokens; carts live in DynamoDB; uploads go straight to S3; checkout idempotency keys live in PostgreSQL.
- Zero-502 graceful shutdown: when Kubernetes sends
SIGTERMto retire a pod, apreStophook fails/readyzwhile keeping the HTTP listener open for 10 s so the ALB finishes deregistering the pod's IP before the process stops accepting packets, then drains in-flight calls cleanly. - Downstream shields: place RDS Proxy / PgBouncer in front of PostgreSQL so 234 pods * 10 threads (
2,340connections) share ~60 database backends, and add random jitter + singleflight locking to Redis TTLs to prevent cache stampedes when a viral product key expires.
- Edge (DNS + CDN): DNS routes users to the healthy region; the CDN terminates TLS near the shopper, caches public catalog/search JSON, and serves cached pages via
Deep dive 3: zero-trust security, IAM, secrets, and key rotation
1. Network defense in depth + Zero Trust
Traditional perimeter security assumed "anything inside the private VPC is safe." Zero trust assumes an attacker may eventually compromise one pod and requires cryptographic identity and explicit authorization on every internal call:
Security Group Allowed Inbound Allowed Outbound sg-alb TCP 443 from CDN IP prefix list only TCP 8080 to sg-app sg-app TCP 8080 from sg-alb; mTLS from sg-app TCP 5432 -> sg-db, TCP 6379 -> sg-redis, TCP 443 -> VPC endpoints & Egress Firewall sg-db TCP 5432 from sg-app ONLY None sg-redis TCP 6379 from sg-app ONLY None- Stateful Security Groups reference logical group IDs (
sg-app), backed up by coarse subnet Network ACLs, a CDN WAF (blocking SQL injection, XSS, and credential-stuffing bots), and an egress firewall that blocks pods from calling arbitrary internet domains (only the payment gateway and email provider domains are allowlisted). - Service-to-service mutual TLS (mTLS): a service mesh issues each service a short-lived cryptographic certificate so both sides prove identity and encrypt pod-to-pod traffic; mesh policy allows
checkoutto callpayments, while blockingsearchfrom ever callingpayments. - Human access: engineers authenticate via SSO + hardware MFA with just-in-time temporary elevation (no SSH keys or public bastion VMs; audited session-manager shells only).
2. Least-privilege IAM, secrets, envelope encryption, and zero-downtime rotation
- IAM (Identity and Access Management): every microservice binds its Kubernetes service account to a dedicated IAM role issuing automatic short-lived tokens—zero static long-lived cloud access keys exist anywhere. Organization-level guardrails (Service Control Policies) forbid public S3 buckets or disabling audit logs (
CloudTrailstreams to the lockedsecurity-auditaccount). - Secrets management: third-party API keys live in Secrets Manager (never in Git or Dockerfiles; CI runs secret scanners on every PR), and PostgreSQL connections use 15-minute IAM auth tokens instead of static passwords where supported.
- Encryption in transit & at rest: TLS 1.3 externally + mTLS internally; every disk, DB, cache, S3 bucket, and backup uses customer-managed keys in KMS (Key Management Service) via envelope encryption (encrypting gigabytes of data locally with a fast symmetric data key, and encrypting only that 32-byte data key with the hardware-protected KMS master key).
- Zero-downtime credential rotation via overlap windows:
- KMS master keys: automatic annual rotation; KMS retains prior key versions transparently to decrypt historical blocks.
- DB passwords (if any): Secrets Manager alternates between two DB users every 30 days so active pods finish queries on User A while new connections pick up User B.
- JWT signing keys: publish new public
kidto the verification JWKS endpoint first, wait for caches to refresh, switch signing to the new private key, and retire the old public key only after the 15-minute token TTL expires.
- Stateful Security Groups reference logical group IDs (
High availability, multi-region disaster recovery, and failure modes
Inside Region A, spreading all tiers across 3 AZs with
1.5xpod headroom and synchronous RDS Multi-AZ replication makes single-node and single-AZ failures automatic (RPO = 0, RTO ≈ 0 s for stateless APIs and ~60–120 s for RDS standby promotion).Across regions, we choose the disaster-recovery tier directly from our 30-minute RTO and < 1-minute RPO:
DR Strategy Typical RTO Typical RPO Cost & Engineering Complexity Backup & Restore Hours Hours (last backup) Lowest (cold S3 snapshots only) Pilot Light 15-45 minutes Seconds (async DB) Low (DB replicating; app compute off) Warm Standby 10-30 minutes Seconds (async DB) Medium (DB replicating + scaled-down app live) <- CHOSEN Active-Active ~0-1 minute ~0-seconds Highest (2x infra + multi-region write conflicts!)- Why Warm Standby in Region B wins here: Region B runs an asynchronous cross-region PostgreSQL read replica (typical lag < 1–5 s, continuously monitored), DynamoDB Global Tables for carts, cross-region S3 replication, and a small live EKS cluster running every microservice. If Region A suffers a regional catastrophe, an on-call commander triggers a tested runbook (never hair-trigger automated regional failover, which risks split-brain dual primaries on a transient network blip!): promote Region B's PostgreSQL replica, scale EKS to production pod counts, and flip DNS health checks—comfortably inside our 30-minute RTO and 1-minute RPO.
- Explicit SLO honesty: note that a 30-minute regional failover consumes more than checkout's 21.6-minute monthly 99.95% budget, meaning full-region loss is governed as a rare disaster-recovery event outside normal monthly SLOs; if the business ever demanded near-zero regional RTO, we would shard inventory writes by geographic store region or adopt a globally distributed SQL database.
CI/CD, Infrastructure as Code, canary vs. blue/green, and rollbacks
1. Build-once GitOps pipeline & Infrastructure as Code (IaC)
All cloud resources (VPCs, EKS, RDS, IAM, WAF) live in version-controlled Terraform modules (IaC: declarative code replacing manual console clicks, keeping Region A and Region B identical) validated by policy-as-code checks (
no 0.0.0.0/0 admin ports,all storage encrypted) on every pull request. Merging application code builds one immutable container image tagged with its Git SHA digest, scans dependencies/secrets, signs the image, deploys that exact digest tostagingvia GitOps (Argo CD syncing cluster state to Git), runs end-to-end tests, and promotes the exact same binary digest toprod.2. Canary vs. Blue/Green deployments
- Canary releases (default for stateless microservices): shift
5% -> 25% -> 50% -> 100%of live traffic over 30–40 minutes, auto-aborting in seconds if 5xx error rate or p99 latency regresses. Sample-size nuance: at 5% traffic,catalogsees ~500 req/s (statistically conclusive in 2 minutes), whereascheckoutsees ~0.25 req/s at normal hours (~15 checkouts in a minute)—so checkout canaries run longer steps supplemented by continuous synthetic test-card checkouts! - Blue/Green releases (for Kubernetes cluster upgrades or major infra shifts): provision a complete parallel
greencluster alongsideblue, smoke-testgreen, shift load-balancer weights across, and keepbluewarm for 1 hour for instant flip-back, trading temporary 2x compute cost for clean isolation.
3. Rollbacks and backward-compatible database migrations
Code rolls back in seconds via GitOps image-digest revert or feature flags (decoupling code deployment from feature activation). Database schemas never roll back destructively—instead, enforce expand-and-contract (
add nullable column -> dual-write -> backfill -> switch reads -> drop old column next sprint) andCREATE INDEX CONCURRENTLYsov1andv2pods always coexist safely during canaries and rollbacks.- Canary releases (default for stateless microservices): shift
Observability, SLO burn-rate alerts, cost governance, and trade-offs
1. Three observability pillars + user-centric SLO alerting
- Metrics: RED (
Rate,Errors,Duration) per endpoint, USE (Utilization,Saturation,Errors) per pool/node, plus business KPIs (orders_per_minute,payment_auth_rate—if orders drop to zero at 2 PM Tuesday, page immediately even if HTTP 5xx is 0%!). - Logs & Traces: structured PII-scrubbed JSON logs correlated by
trace_id(14 days hot in OpenSearch, 1 year cold in S3 Glacier) + OpenTelemetry tail-based tracing (keeping 100% of errors and requests > 1 s, plus 5% baseline sample). - Multi-window error-budget burn-rate alerts: over a 720-hour month, burning
100%of budget in 720 hours is a1.0xburn rate (burn_rate = budget_fraction / (window_hours / 720)):- Page on-call immediately:
2%of monthly budget burned in1 hour(0.02 * 720 = 14.4xburn rate, confirmed over a 5-min window so a 30-second blip resets cleanly). - Open daytime ticket:
10%burned in72 hours(0.10 * 10 = 1.0xsteady burn).
- Page on-call immediately:
2. Cloud cost governance (FinOps)
- Attribute every dollar: IaC blocks any resource missing
team,service,env, andcost_centertags; track unit economics (cloud cost per 1,000 ordersandper 1M API calls) alongside anomaly alerts. - Buy the baseline, rent the spikes: cover the 24/7 78-pod baseline and RDS instances with 1–3 year Savings Plans / Reserved Instances (~30–50% discount), run interruptible async queue/batch workers on Spot VMs (~60–70% discount, handling 2-minute reclaim notices gracefully), and pay On-Demand only for daily/seasonal peaks.
- Eliminate idle & transfer waste: auto-hibernate
dev/stagingclusters nights and weekends (running 60 of 168 hours/week cuts ~64% of non-prod compute), enforce S3 lifecycle tiering (Standard -> Infrequent Access at 30d -> Glacier at 365d), offload 95% of egress to the CDN, and route S3/DynamoDB over free VPC Gateway Endpoints instead of NAT Gateways.
Summary of core trade-offs
- Containers (steady APIs) + Serverless (bursty events) + Managed PaaS (databases): optimizes latency and cost per workload at the price of operating two compute deployment paths.
- 1.5x Multi-AZ pod headroom + Regional Warm Standby: makes AZ failures invisible (
RTO ≈ 0) and regional disasters recoverable in<= 30 minwithout paying 2x infrastructure and split-brain write complexity for multi-region active-active. - Polyglot persistence (ACID SQL for stock/orders, NoSQL/Cache/Search elsewhere): guarantees zero oversold inventory while scaling 31,000 reads/s effortlessly, trading strict freshness on catalog/search views (1–60 s lag).
- Zero-trust mTLS, workload IAM, and canary + expand/contract pipelines: adds upfront platform engineering in exchange for shrinking blast radius on both credential leaks and bad code pushes.
- Metrics: RED (
Intuition & how it works
Think of building a cloud-native retail platform for millions of shoppers like running a flagship retail chain across three fireproof buildings (availability zones, or independent data centers in a region): neighborhood flyer kiosks (CDN edge servers) answer 95% of casual catalog browsing before shoppers ever walk inside; interchangeable cashiers (stateless container pods) open or close checkout lanes in seconds because customer carts sit in a shared locker wall (NoSQL key-value store) rather than in any single cashier's apron; a central vault ledger (ACID relational database paired with a synchronous twin next door) ensures the last power drill on the shelf is never sold to two buyers at once; badge scanners on every internal hallway door (zero-trust IAM and mutual TLS) verify every employee on every room entry; and a smaller sister warehouse in a second city (warm standby region) receives continuous inventory updates so the business can reopen within 30 minutes if a hurricane knocks out the primary city.
Why do simpler "one-size-fits-all" cloud approaches fail? Lifting a monolith onto one giant virtual machine in a public subnet creates a single point of failure, exposes database ports to internet scanners, and forces you to rent Black Friday-sized hardware 365 days a year. Conversely, forcing everything onto serverless functions or a single database engine backfires too: a steady 3,500 requests/s API keeps ~175 execution environments running 24/7 (where serverless scale-to-zero saves nothing while adding cold-start tail latency, per-request fees, and hundreds of unpooled database connections), whereas using eventual consistency for stock counts oversells scarce items and routing 31,000 product views/s straight to a relational primary melts it down.
Trace how a catalog browse and a card checkout flow through the architecture step by step:
Flow A — Anonymous shopper views SKU #9041 (95%+ of traffic):
1. Browser -> DNS -> nearest CDN edge server:
- Cache HIT (95%): returns JSON/images in ~15 ms; zero load on our cloud region!
- Cache MISS (5%): HTTPS -> WAF -> Multi-AZ ALB -> `catalog` pod in `/19` private subnet
-> Redis cache hit (1 ms) -> returns response with `Cache-Control: max-age=60`.
Flow B — Signed-in shopper clicks "Place Order" with `Idempotency-Key: 7c9e...`:
1. Browser sends card digits directly to payment provider -> receives `tok_visa_88`.
2. Browser -> CDN (bypass cache) -> WAF -> ALB -> `checkout` pod (authenticated via JWT).
3. `checkout` pod connects via mTLS + PgBouncer to RDS PostgreSQL Primary (isolated `/22` subnet):
BEGIN;
INSERT INTO idempotency_keys ... (halts duplicates if mobile Wi-Fi retried!);
UPDATE stock SET reserved = reserved + 1 WHERE store_id = 104 AND sku = '9041' AND on_hand - reserved >= 1;
INSERT INTO orders ...;
INSERT INTO outbox (event_type, payload) VALUES ('order.placed', ...);
COMMIT; -- Synchronously written to AZ-b standby (~1 ms) before returning `201 Created`!
4. Outbox relay publishes `order.placed` -> Queue -> Serverless function emails receipt asynchronously.
Key trade-offs
- Managed containers (PaaS/EKS) vs. serverless functions (FaaS) vs. raw VMs (IaaS). IaaS (Infrastructure as a Service: raw virtual machines where you patch the OS yourself) gives full kernel control but scales in minutes; Serverless functions bill per millisecond and scale to zero automatically, making them unbeatable for bursty background jobs (image resizing, receipt emails), yet expensive and cold-start-prone for a steady 3,500 req/s API that keeps ~175 concurrent requests in flight 24/7. Running core APIs on managed containers alongside serverless event workers optimizes both latency and cost, at the trade-off of maintaining two deployment runtimes.
- Polyglot persistence (strong SQL vs. eventual NoSQL/cache/search). Enforcing ACID transactions (atomic, all-or-nothing database commits) on RDS PostgreSQL for orders and store inventory guarantees zero overselling and exact payment records, while serving catalog details from Redis/CDN and search facets from OpenSearch absorbs > 95% of read volume. The trade-off is managing eventual-consistency windows (1–60 seconds of catalog/search staleness) and publishing updates reliably via a transactional outbox.
- Pre-provisioned 1.5x Multi-AZ pod headroom vs. purely reactive autoscaling. Running 78 baseline pods across 3 AZs when 52 pods handle normal peak costs ~50% extra baseline compute, in exchange for surviving a sudden AZ outage or 30-second flash-sale spike instantly while new worker VMs take 1–3 minutes to boot.
- Multi-region Warm Standby vs. Active-Active. A warm standby region (asynchronous cross-region database replica + scaled-down Kubernetes cluster) meets a 30-minute RTO (recovery time objective: max downtime) and < 1-minute RPO (recovery point objective: max data-loss window) while keeping a simple single-region writer. Active-active cuts regional RTO near zero, but roughly doubles cloud spend and forces complex conflict resolution or cross-region distributed locks whenever shoppers in two regions buy the same physical store's last item.
- Canary vs. Blue/Green deployments. Canary rollouts (
5% -> 25% -> 100%) catch regressions on real traffic without provisioning 2x hardware, but require neighboring application versions and database schemas (expand-and-contract migrations) to stay backward-compatible; Blue/Green spins up a full parallel environment for clean infrastructure/cluster swaps at the cost of temporary double capacity. - Zero-trust security depth vs. developer friction. Private isolated subnets, mutual TLS (mTLS) pod-to-pod encryption, short-lived workload IAM roles, envelope encryption via KMS, and just-in-time production access require upfront platform tooling, in exchange for shrinking the blast radius of a compromised container or leaked token to one microservice for a few minutes.
Common mistakes
- Reciting textbook definitions of IaaS/PaaS/Serverless without tying choices to traffic math. Without Little's law (
3,500 req/s * 0.05 s = 175always-busy workers) or read-vs-write ratios, candidates pick serverless for high-volume steady APIs or raw VMs for commodity databases without seeing the cost and operational traps. - Placing databases in public subnets, sizing pod subnets too small (
/24), or using a single NAT gateway. Databases never belong on public routes;/24subnets (251usable IPs) exhaust IP addresses during container rolling deploys; and a single NAT gateway in AZ-a creates a hidden cross-AZ single point of failure. - Storing user sessions or uploaded files inside API containers. Local state breaks horizontal autoscaling, drops active carts when Spot or rolling-deploy pods terminate, and blocks seamless AZ failover.
- Treating Multi-AZ database replication as a backup. Synchronous standbys replicate an accidental
DELETEor bad schema migration in milliseconds; real recovery requires point-in-time recovery (PITR) logs plus immutable cross-account snapshots verified by monthly restore drills. - Swapping rotated secrets/keys abruptly without an overlap window, or embedding static cloud keys in CI/code. Rotating DB credentials, TLS certs, or JWT signing keys without a dual-valid overlap window causes self-inflicted authentication outages across live pods.
- Checking shared dependencies inside
/readyzreadiness probes, or skipping connection pooling. Failing/readyzon a transient DB hiccup causes the load balancer to drop all pods simultaneously, and letting 234+ pods open direct PostgreSQL connections without PgBouncer/RDS Proxy exhausts database memory. - Paging engineers on CPU thresholds and ignoring cloud unit economics. Alerting on raw CPU creates noisy alert fatigue while missing broken checkouts; leaving untagged dev environments running 24/7 and routing terabytes of S3 traffic through paid NAT gateways instead of free VPC Gateway Endpoints silently bloats the cloud bill.
Follow-up questions
- How would you prepare and stress-test the platform two weeks before a major seasonal sale expected to triple normal peak traffic? Using our retail sizing (
~10,400 req/snormal peak jumping 3x to~31,000 req/s), start by load-testing a production-like staging environment at 1.5x the forecast (~47,000 req/s) to uncover hidden ceilings like database connection pools, hot-SKU row locks, NAT port limits, and third-party payment gateway quotas. Request cloud quota increases (regional Lambda concurrency, EKS vCPU limits, ALB pre-warming) weeks ahead, pre-warm CDN and Redis caches, freeze non-essential code releases, and pre-scale the API fleet to ~234+ pods with 20% warm VM headroom the night before. Finally, wire graceful degradation feature flags (to shed expensive personalized recommendations if latency climbs) and a virtual waiting room at the CDN edge for limited-inventory "doorbuster" drops so sudden surges queue cleanly instead of overwhelming checkout locks. - What architectural changes are needed if leadership later mandates sub-minute regional failover via an active-active multi-region deployment? Serving stateless catalog and search reads active-active across two regions via latency-based DNS is straightforward, because both regions can read local replicas and caches. The hard problem is multi-region inventory and order writes: if Region East and Region West both decrement stock for Store #104 asynchronously, concurrent checkouts will oversell scarce items. You solve that either by home-region sharding (pinning each physical store's inventory master to its geographically nearest cloud region so writes for Store #104 always route to one authoritative writer unless that region fails over) or by adopting a globally strongly consistent SQL database (such as Spanner or CockroachDB, accepting ~30–70 ms of cross-region Raft/Paxos commit latency on checkout writes).
- How would you migrate a live on-premises monolithic application onto this cloud stack without taking customer-facing downtime? Use the strangler-fig pattern rather than a risky "big-bang" rewrite: first place the cloud CDN, WAF, and Layer-7 load balancer in front of the existing monolith so you control URL routing cleanly. Next, extract high-read, low-risk capabilities (
/v1/products,/v1/search) into stateless cloud containers backed by read caches, shifting traffic incrementally (1% -> 10% -> 100%) at the load balancer with instant fallback to the monolith. For stateful order and inventory tables, stream continuous updates from the legacy database into cloud RDS PostgreSQL via change data capture (CDC), run shadow reads to verify row counts and checksums match 100%, and cut over checkout writes during a quiet maintenance minute while keeping reverse-CDC active briefly in case rollback is needed.
Follow-up questions
- How would you prepare and stress-test the platform two weeks before a major seasonal sale expected to triple normal peak traffic?
- What architectural changes are needed if leadership later mandates sub-minute regional failover via an active-active multi-region deployment?
- How would you migrate a live on-premises monolithic application onto this cloud stack without taking customer-facing downtime?
Similar questions
- Python Runtime Internals and Production Engineering Practices
- Longest Repeat-Free Substring
- Global Live Video Streaming Platform
- Multi-User Collaborative Document Editor
- Burst-Resilient Multi-Channel Notification Platform
- Prior Authorization Status Engine, Clinical Worklists, and Digests