MODULE 1

Service Models

IaaS / PaaS / SaaS / FaaS — what the cloud manages, what you manage.

Stack Layers

ModelYou manageCloud managesExample
On-premEverythingNothingBare metal in your DC
IaaSOS, runtime, app, dataVirtualization, networking, storage, hardwareEC2, GCE, Azure VM
CaaSContainer image, app configContainer runtime, scheduler, infraECS, GKE, AKS, Fargate
PaaSApp code, dataRuntime, OS, scaling, infraApp Engine, Heroku, Elastic Beanstalk
FaaSFunction codeEverything else; pay per invocationLambda, Cloud Functions
SaaSConfiguration, usersEverythingGmail, Salesforce
MODULE 2

AWS Core Services

The 20 services that cover 80% of architectures.

Compute

  • EC2 — VMs. Instance families: m (general), c (compute), r (memory), i (storage), g/p (GPU). Spot = up to 90% off, can be reclaimed in 2 min.
  • Lambda — FaaS. Max 15 min, 10 GB memory. Cold start mitigations: provisioned concurrency, smaller bundle, SnapStart (Java 11+ / Python 3.12+ / .NET 8+).
  • ECS / Fargate — container orchestration. Fargate = serverless containers (no EC2 to manage).
  • EKS — managed Kubernetes control plane.
  • Batch — long-running compute jobs.

Storage

  • S3 — object store. Classes: Standard, IA, One-Zone-IA, Intelligent-Tiering, Glacier Instant / Flexible / Deep Archive. Strongly consistent for all operations (reads / overwrites / deletes / LIST) since Dec 2020.
  • EBS — block storage for EC2. gp3 (general SSD, 3000–80000 IOPS), io2 (provisioned), st1 (HDD throughput), sc1 (cold HDD).
  • EFS — NFS. Multi-AZ, scales automatically. Slower than EBS.
  • FSx — Lustre / Windows / OpenZFS / NetApp managed file systems.

Databases & Data

  • RDS — managed Postgres / MySQL / MariaDB / Oracle / SQL Server. Multi-AZ for HA, read replicas for scale.
  • Aurora — RDS-compatible, storage-decoupled. 6 copies across 3 AZs. Failover is faster than classic RDS (typically under a minute) because storage is shared and survives the instance: a promoted replica attaches to the existing 6-way-replicated volume instead of restoring from a snapshot.
  • DynamoDB — managed k-v / document. Single-digit ms p99. PK + optional SK. GSI / LSI for secondary access. On-demand vs provisioned RCU/WCU.
  • ElastiCache — managed Valkey / Redis OSS / Memcached.
  • Redshift — columnar warehouse, OLAP.
  • Athena — serverless SQL on S3 (Presto).
  • Kinesis — managed streaming. Data Streams (Kafka-like), Firehose (load to S3/Redshift), Managed Service for Apache Flink (formerly Kinesis Data Analytics).

Networking

  • VPC — private virtual network. Subnets per AZ, public/private split.
  • ALB — L7 LB, HTTP-aware, target groups, path/host routing, WebSockets.
  • NLB — L4 LB, TCP/UDP, static IP, ultra-low latency, preserves source IP.
  • API Gateway — managed API frontend, auth, rate limit, transformation.
  • CloudFront — CDN with edge compute (Lambda@Edge / Functions).
  • Route 53 — DNS with health checks + weighted / latency / geo routing.
  • VPN / Direct Connect / Transit Gateway — hybrid + multi-VPC connectivity.

Messaging & Integration

  • SQS — managed queue. Standard (best-effort order, at-least-once) or FIFO (ordered per message group; exactly-once processing via a 5-min dedup window — not end-to-end exactly-once delivery, so consumers must stay idempotent). FIFO throughput is bounded because order is preserved per message group, so a single group is processed serially; scale by spreading messages across many message-group IDs. DLQ for poison messages.
  • SNS — pub/sub fanout. SNS → SQS / Lambda / HTTP / email / SMS.
  • EventBridge — event bus with rules + scheduler.
  • Step Functions — managed state machines, sagas.
  • MSK — managed Kafka.

IAM & Security

  • IAM — users, roles, policies. Trust + permission policies.
  • STS — short-lived credentials via AssumeRole.
  • KMS — managed keys, envelope encryption. CMK + data keys.
  • Secrets Manager — secret storage with rotation; Parameter Store for non-secret config.
  • Cognito — user pools (identity) + identity pools (federated).
  • WAF / Shield — L7 firewall + DDoS.

Least-privilege policy granting read-only access to one S3 prefix. Note the two ARN granularities: s3:GetObject acts on objects (bucket/prefix/*), while s3:ListBucket acts on the bucket ARN and is scoped to the prefix via an s3:prefix condition — getting that level wrong is the classic least-privilege bug.

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "ReadObjectsInPrefix",
      "Effect": "Allow",
      "Action": "s3:GetObject",
      "Resource": "arn:aws:s3:::my-app-data/reports/*",
      "Condition": {
        "Bool": { "aws:SecureTransport": "true" }
      }
    },
    {
      "Sid": "ListOnlyThatPrefix",
      "Effect": "Allow",
      "Action": "s3:ListBucket",
      "Resource": "arn:aws:s3:::my-app-data",
      "Condition": {
        "StringLike": { "s3:prefix": "reports/*" }
      }
    }
  ]
}

Observability

  • CloudWatch — metrics, logs, alarms. Custom metrics via PutMetric / EMF.
  • X-Ray — distributed tracing.
  • CloudTrail — API audit log.
  • Config — resource state + compliance.
MODULE 3

GCP / Azure Mappings

Same primitives, different names.

Cross-Cloud Equivalents

AWSGCPAzure
EC2Compute EngineVirtual Machines
LambdaCloud Functions / RunFunctions
S3Cloud StorageBlob Storage
EBSPersistent DiskManaged Disks
RDSCloud SQLAzure SQL / Postgres / MySQL
AuroraAlloyDB / Spanner (global)Cosmos DB (multi-model)
DynamoDBFirestore / BigtableCosmos DB
SQSPub/Sub (queue mode)Service Bus / Queue Storage
SNSPub/SubEvent Grid / Service Bus topics
KinesisPub/Sub + DataflowEvent Hubs
ALBCloud Load Balancing (HTTPS)App Gateway / Front Door
CloudFrontCloud CDNFront Door / CDN
Route 53Cloud DNSAzure DNS / Traffic Manager
EKSGKEAKS
RedshiftBigQuerySynapse Analytics
IAMCloud IAMEntra ID + RBAC
KMSCloud KMSKey Vault
CloudWatchCloud Monitoring + LoggingMonitor + Log Analytics
MODULE 4

Containers

Image format, runtime, registry.

Image Anatomy

  • Layered filesystem (overlayfs). Each Dockerfile instruction = layer.
  • Layer cache: identical layer hashes are reused across builds. Order Dockerfile from least → most changing.
  • Multi-stage builds: build in heavy image, copy artifacts to slim runtime.
  • OCI image spec — vendor-neutral standard. Distroless / scratch / alpine for minimal base.
# multi-stage example
FROM golang:1.26 AS build
WORKDIR /src
# deps layer cached unless go.mod/go.sum change
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 go build -o /out/app

FROM gcr.io/distroless/static
COPY --from=build /out/app /app
# nonroot uid (distroless) = least privilege
USER 65532:65532
ENTRYPOINT ["/app"]

Runtime & Linux Primitives

  • Namespaces — pid, net, mnt, uts, ipc, user, cgroup. Isolate process view.
  • cgroups v2 — limit + account CPU, memory, IO, pids.
  • seccomp / AppArmor / SELinux — syscall filtering, MAC.
  • Container runtimes — containerd, CRI-O, runc (OCI runtime).
MODULE 5

Kubernetes

Declarative orchestration. Reconciliation loops drive desired state.

Architecture

  • Control plane: API server (kube-apiserver), etcd (state), scheduler, controller-manager, cloud-controller-manager.
  • Node: kubelet (agent), kube-proxy (network), container runtime (containerd).
  • Everything is a CRUD operation on the API server; controllers watch + reconcile.
The reconciliation loop: kubectl apply to running pod

Core Objects

ObjectPurpose
PodSmallest unit; 1+ containers sharing net + IPC
ReplicaSetMaintains N pod replicas
DeploymentDeclarative rolling update over ReplicaSets
StatefulSetStable identity + ordered rollout (DBs)
DaemonSetOne pod per node (logs, monitoring agents)
Job / CronJobRun-to-completion / scheduled work
Service (ClusterIP / NodePort / LB)Stable virtual IP + endpoints
Gateway API (preferred) / Ingress (feature-frozen)L7 routing into cluster — migrate to Gateway API; ingress-nginx controller retired March 2026 (no further releases or security fixes)
ConfigMap / SecretConfig + sensitive data
PersistentVolume / PVC / StorageClassStorage provisioning
HPA / VPA / Cluster Autoscaler / KarpenterScaling pods + nodes
NetworkPolicyPod-to-pod L3/L4 firewall

Scheduling

  • Filters (node selector, taints/tolerations, affinity, resource fit) → scoring → bind.
  • Requests = scheduler reservation; limits = runtime cap. Set CPU request always; CPU limit cautiously (throttling).
  • QoS classes: Guaranteed (req=lim), Burstable, BestEffort. Eviction order: BestEffort → Burstable → Guaranteed.
  • Pod disruption budgets (PDB) protect availability during voluntary disruption.

A complete Deployment + Service + HPA with requests/limits and the three probes. The CPU-utilization HPA computes load as a percentage of the pod's CPU request, so the Deployment must set resources.requests.cpu or the HPA has no denominator and cannot scale.

apiVersion: apps/v1
kind: Deployment
metadata:
  name: web
spec:
  replicas: 3
  selector:
    matchLabels: { app: web }
  template:
    metadata:
      labels: { app: web }
    spec:
      containers:
        - name: web
          image: registry.example.com/web@sha256:abc123   # pin digest, not tag
          ports:
            - containerPort: 8080
          resources:
            requests: { cpu: "250m", memory: "256Mi" }     # scheduler reservation + HPA denominator
            limits:   { memory: "512Mi" }                   # cap memory; omit CPU limit to avoid throttling
          startupProbe:        # gates the others until the app has booted
            httpGet: { path: /healthz, port: 8080 }
            failureThreshold: 30
            periodSeconds: 5
          readinessProbe:      # fail -> removed from Service endpoints (no restart)
            httpGet: { path: /ready, port: 8080 }
            periodSeconds: 5
          livenessProbe:       # fail -> kubelet restarts the container
            httpGet: { path: /healthz, port: 8080 }
            periodSeconds: 10
---
apiVersion: v1
kind: Service
metadata:
  name: web
spec:
  selector: { app: web }
  ports:
    - port: 80
      targetPort: 8080
---
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
  name: web
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: web
  minReplicas: 3
  maxReplicas: 10
  metrics:
    - type: Resource
      resource:
        name: cpu
        target:
          type: Utilization
          averageUtilization: 70   # % of the 250m request

Networking & Probes

Probes — three jobs, different failure semantics

  • Startup — runs first and gates the other two; while it is failing, liveness and readiness are suspended. Use it for slow-booting apps so a long warm-up isn't mistaken for a crash.
  • Readiness — failure removes the pod from its Service's endpoints, so it stops receiving traffic but is not restarted. This is the lever for graceful drain and "not ready yet."
  • Liveness — failure makes the kubelet restart the container. Reserve it for unrecoverable deadlock; a too-aggressive liveness probe turns a slow dependency into a restart loop.

Pod networking — flat L3

  • The K8s network model requires every pod to get its own routable IP and to reach every other pod without NAT — a flat L3 fabric. This is why pods can talk cross-node as if on one network.
  • The CNI plugin (Calico, Cilium, AWS VPC CNI, …) implements that contract: it wires the pod's veth into the node and programs routes. Swapping CNI changes how IPs are allocated and how NetworkPolicy is enforced, not the flat-network guarantee.

Service data path

  • A Service is a stable virtual IP (ClusterIP). The endpoints controller watches pods matching the selector that are Ready and writes their IPs into EndpointSlices (the scalable replacement for the single Endpoints object).
  • kube-proxy on each node watches EndpointSlices and programs the dataplane — iptables mode installs DNAT rules that randomly pick a backend; IPVS mode uses an in-kernel hash table that scales better with thousands of services. Either way, ClusterIP traffic is rewritten to a real pod IP in-kernel; there is no proxy process in the hot path.
  • Because only Ready pods appear in EndpointSlices, a failing readiness probe is exactly what pulls a pod out of this data path.

Service discovery — CoreDNS

  • CoreDNS runs in-cluster and resolves <service>.<namespace>.svc.cluster.local to the Service's ClusterIP. Pods get it as their resolver via the kubelet, so apps address dependencies by name and let the Service/EndpointSlice layer handle the live pod set.

Operators & CRDs

Custom controllers reconcile custom resources. Patterns: state machine for app lifecycle (e.g., Postgres operator handles backups, failover, scaling). Tools: kubebuilder, Operator SDK.

Rollouts

  • RollingUpdate: maxSurge, maxUnavailable. Default deployment.
  • Recreate: kill all then start. Brief downtime.
  • Blue/Green: two deployments, switch service selector.
  • Canary: weighted routing via Service Mesh (Istio/Linkerd) or Argo Rollouts.
MODULE 6

Infrastructure as Code

Terraform / Pulumi / CloudFormation / CDK.

Terraform Concepts

  • Providers (aws, gcp, k8s) → resources → state file.
  • State: source of truth for what TF created. Remote backend (S3 + DynamoDB lock, Terraform Cloud).
  • Plan / Apply: dry-run shows diff. Apply executes.
  • Modules: reusable groups of resources. Inputs / outputs / variables.
  • Workspaces or directories for env separation (dev / staging / prod).
  • Drift = real infra ≠ state. Detect via plan; reconcile or import.

Remote state on S3 with a DynamoDB lock table. The DynamoDB table provides a distributed lock so two concurrent applys can't interleave writes and corrupt state; its key attribute must be named LockID (String) or Terraform won't find the lock item. Note backend blocks accept only literal values — no variables or interpolation — so the bucket/table names are hardcoded.

terraform {
  backend "s3" {
    bucket         = "my-org-tfstate"
    key            = "prod/network/terraform.tfstate"
    region         = "us-east-1"
    dynamodb_table = "tf-locks"
    encrypt        = true
  }
}

# The lock table (created once, e.g. in a bootstrap config):
resource "aws_dynamodb_table" "tf_locks" {
  name         = "tf-locks"
  billing_mode = "PAY_PER_REQUEST"
  hash_key     = "LockID"
  attribute {
    name = "LockID"
    type = "S"
  }
}

Tooling Comparison

ToolLangProsCons
TerraformHCLMulti-cloud, large ecosystem, matureHCL limited; state mgmt headaches
PulumiPython/TS/GoReal lang, tests, conditionalsSmaller community
CloudFormationYAML/JSONNative AWS, no state to manageAWS-only, slow rollback
AWS CDKTS/Python/Java/GoSynth to CFN; constructsAWS-only; opinionated abstractions
CrossplaneK8s CRDsGitOps-native; multi-cloud as K8sK8s-shaped solutions only
MODULE 7

Cloud Networking

VPC anatomy + connectivity patterns.

VPC Topology

  • VPC = isolated address space (e.g., 10.0.0.0/16).
  • Subnets per AZ (typically 2–3 AZs). Public subnet = route to IGW; private = no IGW route.
  • NAT Gateway in public subnet → outbound internet from private subnet.
  • Route tables associate with subnets. Security groups (stateful, instance-level) + NACLs (stateless, subnet-level).
  • VPC endpoints: Interface (ENI for AWS service) or Gateway (S3 / DynamoDB free).
VPC reachability: public vs private subnet routing

Cross-VPC / Hybrid

  • VPC peering — 1:1, non-transitive, same/different account/region.
  • Transit Gateway — hub-and-spoke, transitive, scales to thousands of VPCs.
  • PrivateLink — expose service via interface endpoint without VPC peering.
  • VPN — IPsec over internet, up to 1.25 Gbps per standard tunnel (5 Gbps on large-bandwidth tunnels).
  • Direct Connect — dedicated fiber, 1/10/100/400 Gbps dedicated ports (50 Mbps–25 Gbps hosted via partners), lower latency + predictable.

Egress Cost

MODULE 8

Storage Tiers & Patterns

Match access pattern to tier; lifecycle policies move automatically.

S3 Classes

ClassCost / GB-moRetrievalUse
Standard$0.023InstantHot data
Intelligent-Tiering$0.023 → $0.0036InstantUnknown access pattern
Standard-IA$0.0125Instant + retrieval $Backup, infrequent access
One-Zone-IA$0.01InstantRe-creatable, single AZ
Glacier Instant Retrieval$0.004InstantArchive accessed rarely
Glacier Flexible$0.0036Minutes–hoursBackup
Glacier Deep Archive$0.0009912 hoursCompliance, long retain

EBS Volume Types

  • gp3 — console-default GP SSD (the CreateVolume API default is still gp2, and root-volume defaults follow the AMI: AL2023 = gp3, AL2 = gp2). 3000 IOPS / 125 MiB/s baseline free; IOPS & throughput provisioned independently of size (vs gp2's 3 IOPS/GiB); scale to 80,000 IOPS / 2,000 MiB/s.
  • io2 Block Express — up to 256k IOPS, <1 ms; expensive.
  • st1 / sc1 — HDD, sequential workloads, cheap.
  • Snapshots = incremental, stored in S3 internally.
MODULE 9

Cost Optimization

FinOps basics. Engineering decisions = cost decisions at scale.

Pricing Levers

  • On-Demand — full price, no commit.
  • Reserved Instances / Savings Plans — 1 or 3 yr commit. Compute SP = flexible across EC2/Fargate/Lambda, up to ~66% off; EC2 Instance SP / Standard RI = locked to a family/type, up to ~72% off.
  • Spot — up to 90% off; can be reclaimed in 2 min. Pair with checkpointing or Karpenter.
  • Right-sizing — match instance to workload. Compute Optimizer surfaces.
  • Auto-scaling — scale to zero off-hours where possible.

Watch For

  • Idle EBS volumes / snapshots / Elastic IPs.
  • NAT Gateway egress for internal traffic — use VPC endpoints.
  • Cross-AZ chatter — colocate replicas / cache.
  • S3 unfinished multipart uploads (lifecycle rule to expire).
  • Log retention default = forever; set retention.
  • RDS over-provisioned IOPS; switch to gp3.
MODULE 10

Docker Internals — How Containers Work

Namespaces, cgroups, and a layered filesystem — how one Linux kernel pretends to be many isolated machines.

A Container Is Just a Process

The single most important mental correction for the interview: a container is not a lightweight VM. There is no hypervisor, no guest kernel, no emulated hardware. A container is an ordinary Linux process running on the host kernel — the same ps, the same scheduler, the same page cache. What makes it feel isolated is three kernel features layered on top of that process:

  • Namespaces — change what the process can see (its own PID tree, network stack, mounts, hostname).
  • cgroups v2 — limit and account what the process can use (CPU, memory, IO, PID count).
  • Union filesystem — give it a root filesystem assembled from stacked read-only image layers plus one thin writable layer.

Strip those away and a "container" is a process like any other. That framing answers most Docker-internals questions before they're fully asked.

Container vs Virtual Machine

Both provide isolation, but at completely different layers. A VM virtualizes hardware and boots a full guest OS; a container virtualizes the OS interface and shares the host kernel. That single difference cascades into boot time, density, and the strength of the isolation boundary.

DimensionContainerVirtual Machine
KernelShared host kernelOwn guest kernel per VM
Isolation boundaryKernel syscall surface (namespaces + cgroups)Hypervisor / hardware virtualization (VT-x)
Start timeTens of millisecondsSeconds to tens of seconds
Density per hostHundreds to thousandsTens
OverheadNear-zero (process-level)Full OS RAM + CPU per guest
Isolation strengthWeaker — one kernel is sharedStronger — separate kernels
Image sizeMBs to low hundreds of MBsGBs (full disk image)

You still reach for a real VM or a microVM (Firecracker, Kata) when you need a hard security boundary: multi-tenant workloads running untrusted code, compliance requirements demanding kernel-level separation, or running a different kernel/OS than the host. Containers give you speed and density; VMs give you a stronger wall.

The Linux Primitives

Docker is largely a friendly UX over kernel features that predate it by years. Know the namespaces cold — each one isolates exactly one kind of global resource:

  • pid — process ID tree. The container's entrypoint sees itself as PID 1; host PIDs are invisible.
  • net — network stack: its own interfaces, routing table, iptables rules, ports.
  • mnt — mount points, so the container sees its own root filesystem.
  • uts — hostname and domain name (UTS = Unix Time-sharing System).
  • ipc — System V IPC, POSIX message queues, shared memory segments.
  • user — UID/GID mapping; root (0) inside can map to an unprivileged UID outside. Foundation of rootless containers.
  • cgroup — hides the host's cgroup hierarchy, showing the container its own root.

cgroups v2 — the accountant

Where namespaces isolate visibility, cgroups v2 enforce consumption through a single unified hierarchy: CPU (cpu.max), memory (memory.max plus OOM kill), block IO (io.max), and process count (pids.max — your fork-bomb defense). They both limit and account, so docker stats reads straight out of cgroup files.

Hardening layers

  • Capabilities — root is split into ~40 discrete caps (NET_BIND_SERVICE, SYS_ADMIN…). Docker drops most by default; drop the rest with --cap-drop ALL.
  • seccomp — a syscall allowlist/filter. Docker's default profile blocks ~44 dangerous syscalls.
  • AppArmor / SELinux — mandatory access control (MAC) restricting file/resource access beyond standard permissions.

You can build a "container" by hand to prove the point — no Docker daemon required:

# Create a new PID + mount + UTS + net namespace and run a shell as PID 1
sudo unshare --pid --mount --uts --net --fork --mount-proc bash

# Inside: you are PID 1, hostname is isolated, ps sees only this tree
hostname container-demo
ps aux            # only the shell and ps — host processes are invisible
echo $$           # prints 1

# That is the whole trick. Docker just automates unshare + cgroups + overlayfs.

Image Anatomy — Content-Addressable Layers

A Docker image is a stack of read-only layers, each identified by the SHA-256 digest of its content (content-addressable). Identical layers are stored and pulled exactly once, shared across every image that references them. Each instruction in a Dockerfile that changes the filesystem (RUN, COPY, ADD) produces one new layer diffed on top of the previous.

At runtime an overlayfs mount unifies them: the image layers become read-only lowerdirs, and a fresh writable upperdir sits on top. A read walks top-down through the stack; a write triggers copy-on-write into the upper layer.

overlayfs componentRole
lowerdirStacked read-only image layers (shared, immutable)
upperdirPer-container writable layer (copy-on-write target)
workdirInternal scratch space overlayfs uses to stage atomic writes
mergedThe unified view the container sees as /

Layer cache and ordering is the single biggest build-speed lever: order instructions least-changing → most-changing. Copy your dependency manifest and install deps before copying source code, so a code edit doesn't bust the dependency layer. Multi-stage builds let a heavy build stage compile the artifact, then a tiny final stage copies only the binary — the toolchain never ships.

# ---- Stage 1: build (heavy toolchain, discarded) ----
FROM golang:1.26 AS build
WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download                 # cached unless deps change
COPY . .
RUN CGO_ENABLED=0 go build -o /app ./cmd/server

# ---- Stage 2: runtime (tiny, distroless) ----
FROM gcr.io/distroless/static:nonroot
COPY --from=build /app /app
USER nonroot:nonroot
EXPOSE 8080
ENTRYPOINT ["/app"]
Base imageSize (approx)ContainsUse when
scratch0 MBNothing — emptyFully static binary, no libc
distroless~2–20 MBRuntime libs, no shell/pkg-mgrProd services; minimal attack surface
alpine~5–8 MBmusl libc + busybox shellNeed a shell; watch musl vs glibc bugs
debian-slim~30–80 MBglibc + aptBroad compatibility, glibc required

Image vs Container

The relationship is the same as a class vs an instance. The image is the immutable, read-only stack of layers — a template. A container is that image plus one thin writable layer on top, created the moment you docker run.

  • Image — N read-only layers, content-addressed, shared across containers. Never mutated.
  • Container — image layers + a per-container writable upper layer (copy-on-write). All runtime file changes land here.
  • Ephemerality — docker rm deletes only the writable layer. The image is untouched; any data not on a volume is gone.

This is why two containers from the same image are cheap: they share every read-only layer on disk and in page cache, and diverge only in their tiny upper layers.

Container Lifecycle

What actually happens between pressing Enter on docker run and your process running:

  1. Resolve & pull — resolve the tag to an image digest; pull any missing layers by digest (existing layers are skipped).
  2. Create writable layer — allocate the thin copy-on-write upperdir on top of the image's read-only layers.
  3. Set up namespaces — create fresh pid, net, mnt, uts, ipc (and optionally user) namespaces for the process.
  4. Attach cgroups — place the process in a cgroup and apply CPU/memory/IO/pids limits.
  5. Mount rootfs — overlay-mount the merged filesystem and pivot_root into it; wire up networking (veth into the bridge).
  6. Exec entrypoint — the entrypoint process starts as PID 1 inside the pid namespace.

PID 1 is special. In a normal init system PID 1 reaps zombie children and forwards signals. Most app processes don't do this, so an app running as PID 1 may leak zombie processes and, worse, ignore SIGTERM — making docker stop hang until the 10-second timeout escalates to SIGKILL. Fix it with a minimal init: docker run --init (injects tini) or bake tini/dumb-init as your entrypoint.

Networking

Each container gets its own net namespace — a private network stack. Docker's default bridge mode connects it to the host with a veth pair: a virtual cable with one end inside the container (eth0) and the other plugged into the host bridge docker0. Outbound traffic is NAT'd through the host's IP via iptables masquerade.

          host network namespace
   ┌───────────────────────────────────────┐
   │   eth0 (host uplink)  ── iptables NAT  │
   │            │                           │
   │        docker0 bridge  (172.17.0.1)    │
   │          │         │                   │
   │       veth-a     veth-b   (host ends)  │
   └──────────│──────────│──────────────────┘
              │          │      veth pairs
   ┌──────────│───┐  ┌───│──────────┐
   │  eth0 172.17 │  │ eth0 172.17  │   container
   │   .0.2       │  │   .0.3       │   net namespaces
   │ [container A]│  │ [container B]│
   └──────────────┘  └──────────────┘
DriverBehaviorUse when
bridgePrivate subnet, veth + NAT (default)Single-host, standard app
hostShares host net namespace; no isolation, no NATMax network perf, no port remap
noneLoopback only; fully isolated networkBatch jobs needing no network
overlayVXLAN tunnel across hostsMulti-host (Swarm / cluster)

Because the container has its own port space, you publish ports to reach it: docker run -p 8080:80 maps host :8080 to container :80 via an iptables DNAT rule.

Storage — Persistence Beyond the Writable Layer

Anything written to the container's copy-on-write upper layer dies with the container. For data that must survive restarts, rebuilds, or rescheduling, mount storage from outside the layer stack.

Mount typeManaged byLifecycleUse for
VolumeDocker (/var/lib/docker/volumes)Independent of containerDatabases, persistent app data
Bind mountYou (any host path)Tied to host pathDev: mount source code live
tmpfsKernel (RAM)Vanishes on stopSecrets, scratch, never-to-disk
# Named volume — survives docker rm, portable, Docker-managed
docker run -d -v pgdata:/var/lib/postgresql/data postgres:17

# Bind mount — live-edit source from the host (dev workflow)
docker run -v $(pwd):/app -w /app node:22 npm run dev

# tmpfs — sensitive data kept in RAM, never touches disk
docker run --tmpfs /run/secrets:size=64m myapp

Rule of thumb: volumes for state, bind mounts for local development, tmpfs for secrets. Never rely on the writable layer for anything you'd be sad to lose.

The Runtime Stack & OCI

"Docker" is a chain of daemons, not one binary. Understanding the split explains why Kubernetes dropped the Docker daemon yet still runs your images unchanged.

docker CLI  ──▶  dockerd  ──▶  containerd  ──▶  runc  ──▶  [container]
 (client)      (daemon,      (container       (OCI      namespaces
               builds,        lifecycle,      runtime:   + cgroups
               API)           image mgmt,     unshare +  + rootfs)
                              CRI to k8s)      clone)

Kubernetes (kubelet) ──CRI──▶ containerd ──▶ runc   (no dockerd needed)
  • docker CLI — the client; talks to dockerd over a socket.
  • dockerd — the daemon: builds images, exposes the REST API, manages networks/volumes.
  • containerd — the core runtime: pulls images, manages container lifecycle, exposes CRI (Container Runtime Interface) so Kubernetes can drive it directly.
  • runc — the low-level OCI runtime that actually does the unshare + cgroup + pivot_root dance and execs your process.

Two OCI specs make this interoperable: the image spec (how layers + manifest are packaged) and the runtime spec (how a bundle is executed). Because Docker builds OCI images and containerd/runc run them, Kubernetes talks to containerd via CRI and never needs the Docker daemon — the same image you built locally runs unchanged in the cluster (cross-reference: the Kubernetes module builds directly on this CRI boundary).

Hardening in production

  • Rootless — run the whole daemon/runtime as an unprivileged user via user namespaces; a container root escape lands on a nobody UID.
  • Drop caps — --cap-drop ALL --cap-add NET_BIND_SERVICE.
  • Read-only rootfs — --read-only plus a tmpfs for scratch; nothing can tamper with the filesystem.
  • Non-root USER — set USER 10001 in the Dockerfile; never run app code as UID 0.
  • Sandboxed runtimes — swap runc for gVisor (userspace kernel), Kata, or Firecracker (microVMs) for multi-tenant / untrusted workloads.
# Hardened run: no new caps, read-only fs, non-root, sandboxed runtime
docker run --rm \
  --read-only --tmpfs /tmp \
  --cap-drop ALL --cap-add NET_BIND_SERVICE \
  --security-opt no-new-privileges \
  --user 10001:10001 \
  --runtime runsc \
  myorg/api:1.4.2
MODULE 11

AWS Deep-Dive — How the Cloud Works

Regions, IAM, and the core compute/storage/network primitives — and how one HTTP request flows through them.

What AWS Actually Is

Strip away the marketing and AWS is a fleet of regional data centers exposed as API-driven primitives. Every action — launch a VM, put an object, open a firewall port — is an authenticated HTTPS call to a service endpoint, gated by IAM and billed per unit of use. You do not need to memorize the 300-service catalog. You need the small set of primitives (compute, storage, network, identity) and a mental model of how a request flows through them. Everything else is a specialized wrapper on top.

  • API-first — the console, CLI, and SDKs all call the same signed REST/JSON APIs. There is no hidden control plane.
  • Auth-gated — no request executes without an IAM decision. Identity is the security perimeter, not the network.
  • Pay-per-use — you rent capacity by the second/GB/request. Idle still costs (EBS volumes, EIPs, provisioned capacity).

Global Infrastructure

AWS capacity is organized in three tiers. Get the failure-domain boundaries right and HA design falls out naturally.

  • Region — a geographic area (e.g. us-east-1, eu-west-1) with its own API endpoint and isolated from other regions. Data does not leave a region unless you explicitly replicate it. ~30+ regions worldwide.
  • Availability Zone (AZ) — one or more physically separate data centers within a region, on independent power/cooling/network but linked by low-latency (single-digit-ms), high-bandwidth fiber. A region has 3–6 AZs. Spreading across ≥2 AZs is the fundamental HA move.
  • Edge / PoP — 400+ points of presence that terminate TLS and serve cached content close to users. CloudFront (CDN) and Route53 (DNS) run here.

Some services are global (a single control plane, not tied to a region): IAM, Route53, CloudFront, WAF. Most are regional: EC2, S3, RDS, Lambda, DynamoDB. This matters for disaster recovery — a regional outage takes out regional services unless you have multi-region replication.

Region: us-east-1
 <-------------- own API endpoint, isolated blast radius -------------->
   +-----------+   +-----------+   +-----------+
   |   AZ-a    |   |   AZ-b    |   |   AZ-c    |   <-- physically separate DCs
   | subnets,  |   | subnets,  |   | subnets,  |       low-latency fiber between
   | EC2, EBS  |   | EC2, EBS  |   | EC2, EBS  |
   +-----------+   +-----------+   +-----------+
Design HA across >=2 AZs. Global services (IAM/Route53/CloudFront) sit outside.

IAM — How Auth Works

Every API call carries a principal (an IAM user, an assumed role, or an AWS service acting on your behalf). AWS evaluates the request against all attached identity policies and any resource policies, then applies a fixed precedence: an explicit Deny always wins, otherwise an explicit Allow grants access, otherwise the implicit Deny default blocks it.

  1. Principal signs the request with credentials (access key or temporary STS token).
  2. AWS authenticates the signature, then gathers all applicable policies.
  3. Evaluate: explicit Deny > Allow > implicit Deny (default deny).

Users vs Roles vs Policies

  • User — a persistent identity with long-lived access keys. Fine for humans (behind MFA); an anti-pattern for workloads because keys leak and rarely rotate.
  • Role — an identity you assume to get short-lived STS credentials (minutes to hours). EC2/Lambda/ECS use instance/task roles so code never holds static keys. This is the correct workload pattern.
  • Policy — a JSON document listing Effect, Action, Resource, and optional Condition. Attach to identities or resources.

Design for least privilege: grant the narrowest actions on the narrowest resources, prefer assume-role over shared keys, and scope with conditions.

{
  "Version": "2012-10-17",
  "Statement": [{
    "Sid": "ReadOnlyOneBucket",
    "Effect": "Allow",
    "Action": ["s3:GetObject", "s3:ListBucket"],
    "Resource": [
      "arn:aws:s3:::my-app-assets",
      "arn:aws:s3:::my-app-assets/*"
    ],
    "Condition": { "IpAddress": { "aws:SourceIp": "203.0.113.0/24" } }
  }]
}
# Assume a role -> get short-lived STS creds (no long-lived keys on the box)
aws sts assume-role \
  --role-arn arn:aws:iam::111122223333:role/app-read \
  --role-session-name web-tier

# What identity am I right now?
aws sts get-caller-identity

Compute Spectrum

Compute is a ladder from raw VMs to pure functions — each rung trades control for less operational burden. Pick the highest rung that still fits your workload.

ServiceUnitYou manageScalingBest for
EC2Virtual machineOS, patching, capacity, autoscalingAuto Scaling Groups (minutes)Full control, legacy/stateful, custom kernels, GPU
LambdaFunctionJust code + configAutomatic per-request (0→N)Event-driven, spiky, glue; 15-min cap, cold starts
ECSContainer/taskTask defs, cluster (on EC2) or none (on Fargate)Service auto scalingContainer orchestration, AWS-native, simpler than K8s
EKSPodK8s workloads (AWS runs the control plane)HPA / Cluster Autoscaler / KarpenterKubernetes portability, existing K8s tooling
FargateContainer/taskJust the container (no nodes)Per-task, serverlessContainers without managing EC2 hosts

Note Fargate is a launch mode, not a separate orchestrator — both ECS and EKS can run tasks/pods on Fargate so there are no EC2 nodes to patch or scale.

Storage

Three questions decide the storage primitive: object or block or file? single-AZ or multi-AZ? shared or attached-to-one-host? Match the access pattern, not the buzzword.

ServiceTypeDurability / scopeAccessBest for
S3Object store11 nines, multi-AZ replicatedHTTPS API, flat namespace + key prefixesStatic assets, backups, data lake, logs; event notifications
EBSBlock volumeSingle-AZ (replicated within the AZ)Attached to one EC2 at a timeBoot disks, databases, low-latency block IO
EFSFile (NFS)Multi-AZ, sharedPOSIX mount from many instancesShared filesystem across a fleet, lift-and-shift
Instance storeEphemeral blockLocal disk, lost on stop/terminateDirectly attached NVMeScratch, caches, shuffle data you can rebuild

S3 has no real folders — the “flat” namespace uses / in keys purely as a prefix convention. Object PUT/DELETE can fire event notifications to Lambda/SQS/SNS, which is the backbone of serverless data pipelines.

# Object put (S3) vs a volume that lives and dies with one EC2 host
aws s3 cp ./build/ s3://my-app-assets/site/ --recursive
aws ec2 create-volume --availability-zone us-east-1a --size 100 --volume-type gp3

Networking (VPC)

A VPC is your private, software-defined network in a region (a CIDR block like 10.0.0.0/16). You carve it into subnets, each pinned to one AZ. A subnet is public if its route table sends 0.0.0.0/0 to an Internet Gateway (IGW); it is private if outbound internet goes through a NAT Gateway (private hosts reach out, but nothing reaches in).

  • Security Group (SG) — stateful, allow-only, attached per-ENI (per instance/task). Return traffic is implicitly permitted. Your primary firewall.
  • NACL — stateless, allow and deny rules, evaluated per-subnet. You must open both directions; used for coarse subnet-level guardrails.
  • ELB — ALB (Layer 7, HTTP/HTTPS, path/host routing, TLS termination) vs NLB (Layer 4, TCP/UDP, ultra-low latency, static IP).
                        Internet
                           |
                        [ IGW ]
                           |
  VPC 10.0.0.0/16   +------+-------------------------------+
                    |                                      |
        PUBLIC subnet (AZ-a)              PRIVATE subnet (AZ-a)
        route 0.0.0.0/0 -> IGW           route 0.0.0.0/0 -> NAT
        +-----------+                     +-----------------+
        |   ALB     |---- SG allows ----> |  Fargate task   |
        |  (L7)     |     :443 -> :8080   |  (app tier)     |
        +-----------+                     +--------+--------+
             |                                     | SG allows :5432
        [ NAT GW ] (for private egress)            v
                                            +---------------+
                                            |  RDS (private)|
                                            +---------------+

Databases

AWS offers managed engines so you stop babysitting replication, backups, and failover. Choose by data model and scaling shape.

ServiceModelHA / scalingBest for
RDSManaged relational (Postgres, MySQL, etc.)Multi-AZ standby failover; read replicas for read scaleStandard OLTP on a familiar engine
AuroraMySQL/Postgres-compatible, cloud-nativeStorage decoupled from compute, 6-way replicated across 3 AZs; fast failoverHigh-throughput relational needing scale + durability
DynamoDBServerless key-value / document NoSQLPartition-key sharded, auto-scales; on-demand or provisionedSingle-digit-ms at any scale, predictable key-based access

Aurora’s trick is a distributed storage layer shared by compute nodes, so replicas and failover are cheap. DynamoDB throughput hinges on partition-key design — a hot key throttles a single partition no matter how much capacity the table has. Choose on-demand for spiky/unknown traffic, provisioned (with auto-scaling) for steady, cost-optimized load.

How a Request Flows

Trace one HTTP request end-to-end. This is the single most-asked AWS interview question — name each hop’s job and the SG rule that permits it.

  1. Route53 (global DNS) resolves app.example.com to the CloudFront/ALB endpoint. Job: name → address, health-checked routing.
  2. CloudFront (edge CDN) terminates TLS near the user, serves cached static assets, forwards dynamic requests to the origin. Job: latency + TLS + caching + WAF.
  3. ALB in a public subnet receives the request, does L7 routing, load-balances across healthy targets. Job: distribute + health-check. Its SG allows :443 from the internet.
  4. ECS/Fargate task in a private subnet runs your app code. Job: business logic. Its SG allows :8080 only from the ALB’s SG — not the internet.
  5. RDS in a private subnet serves the query. Job: persistence. Its SG allows :5432 only from the app task’s SG.
User
 |  DNS
 v
Route53 --> CloudFront (TLS, cache, WAF)  [edge]
                 |
                 v
              ALB  [public subnet]        SG: :443 from 0.0.0.0/0
                 |
                 v
        Fargate task [private subnet]     SG: :8080 from ALB-SG only
                 |
                 v
            RDS  [private subnet]         SG: :5432 from app-SG only

Only the ALB is internet-reachable. App + DB never have inbound from the world;
each tier's SG references the previous tier's SG (chained least privilege).

Well-Architected + Cost

The Well-Architected Framework is AWS’s review lens — six pillars to pressure-test any design. Interviewers love hearing you frame trade-offs against them.

  • Operational Excellence — run and monitor systems; automate change, respond to events, learn from failure.
  • Security — least privilege, encryption, IAM as the perimeter, auditability.
  • Reliability — recover from failure; multi-AZ, health checks, backups, graceful degradation.
  • Performance Efficiency — right-size, use the fitting primitive, scale elastically.
  • Cost Optimization — pay only for what you need; match pricing model to load shape.
  • Sustainability — minimize energy/resource footprint of the workload.

Cost hinges on picking the right pricing model for the load shape:

ModelCommitmentDiscount vs on-demandBest for
On-demandNone, pay per second/hourBaseline (0%)Spiky, short-lived, unpredictable
Reserved / Savings Plans1 or 3 yearsUp to ~72%Steady, predictable baseline capacity
SpotNone; can be reclaimed with ~2-min noticeUp to ~90%Fault-tolerant, interruptible batch/CI/stateless
MODULE 12

AWS Compute Deep-Dive

EC2 families & pricing, Auto Scaling, and the serverless-to-VM spectrum: Lambda, ECS, EKS, Fargate.

EC2 Instance Families

Every EC2 instance name encodes a family letter, a generation number, an optional capability suffix, and a size — e.g. c7g.2xlarge is Compute-optimized, gen 7, Graviton (g), 8 vCPU. Picking the wrong family is the most common right-sizing mistake: you pay for a resource dimension your workload never touches. The letter tells you the vCPU-to-memory ratio and any attached accelerator.

FamilyClassvCPU:Mem ratioReach for it when
T (t3, t4g)Burstable general~1:2–1:4, CPU creditsBursty low-baseline: dev boxes, small web apps, microservices idle most of the time.
M (m7g)General purpose1:4Balanced steady load: app servers, mid-size databases, backends with no skew.
C (c7g)Compute optimized1:2CPU-bound: batch, media transcode, game servers, HPC, ad-serving, high-RPS APIs.
R (r7g)Memory optimized1:8In-memory workloads: Redis/Memcached, real-time analytics, mid-tier RDBMS.
X (x2idn)High memory1:16+ (up to ~1:32)Huge in-memory sets: SAP HANA, big in-memory DBs, memory-resident caches at TB scale.
P (p5)Accelerated (GPU)NVIDIA H100/A100ML training, distributed deep learning, CUDA/HPC simulation.
G (g5, g6)Accelerated (GPU)NVIDIA L4/A10GML inference, graphics/rendering, video encoding — cheaper GPU than P.
I (i4i, i3en)Storage optimizedNVMe instance storeHigh local IOPS: NoSQL (Cassandra, Aerospike), OLTP, data warehousing, search.
  • Suffix decoder — g = Graviton (ARM64, ~20% cheaper/faster), a = AMD EPYC, i = Intel, n = extra network bandwidth, d = local NVMe.
  • T-family gotcha — burstable instances earn CPU credits at idle and spend them under load; sustained 100% CPU exhausts credits and either throttles (standard) or bills overage (unlimited mode).

Pricing Models

The list price is On-Demand; every other model trades flexibility for a discount. The interview skill is matching the commitment model to the workload's predictability and fault tolerance, not memorizing percentages — but know the ballpark numbers.

ModelDiscount vs On-DemandCommitmentBest for
On-Demand0% (baseline)None, per-second billingSpiky/unknown load, dev, short-lived work.
Savings Plans (Compute)up to ~66%$/hour for 1 or 3 yrSteady spend, flexible across EC2 + Fargate + Lambda, any region/family.
Reserved Instances (RI)up to ~72%1 or 3 yr, family/AZ scopedLocked, steady-state fleets; less flexible than Savings Plans.
Spot Instancesup to ~90%None; 2-min interruption noticeFault-tolerant, stateless, restartable: batch, CI, big-data, queue workers.
Dedicated HostsPremium priceOn-Demand or reservedLicensing tied to physical sockets (BYOL Windows/Oracle), compliance isolation.
  • Savings Plans vs RIs — both need a term commitment; Savings Plans commit to a dollars-per-hour spend and float across family/region/service, while RIs pin to a specific config for a slightly deeper max discount.
  • Spot mechanics — no bidding: you pay the Spot price in effect (an optional max price defaults to On-Demand); AWS reclaims capacity with a 2-minute warning via instance metadata / a CloudWatch event. Handle SIGTERM and checkpoint work.

AMIs, Auto Scaling & Load Balancing

An AMI (Amazon Machine Image) is the immutable boot template — root-volume snapshot (OS + baked app), block-device mapping, and launch permissions. The modern pattern is immutable infrastructure: bake a golden AMI in CI (e.g. Packer), then roll the fleet by replacing instances rather than patching live ones. Never bake secrets into an AMI.

EC2 Auto Scaling stitches these together. A launch template (the successor to launch configurations) declares AMI, instance type, security groups, and user-data; the Auto Scaling Group (ASG) keeps a desired count across multiple AZs and registers new instances into an ELB target group so traffic follows capacity.

  • Launch template — versioned config the ASG uses to stamp out identical instances; supports mixed instances policy (blend On-Demand + Spot, multiple types) in one group.
  • Scaling policies — target tracking (hold avg CPU at 60%) is the default; step scaling reacts to alarm thresholds; scheduled scaling pre-warms for known peaks; predictive uses ML on history.
  • Health & draining — the ALB target group health check gates traffic; connection draining (deregistration delay) lets in-flight requests finish before an instance is terminated on scale-in.
  • ALB vs NLB — ALB is L7 (path/host routing, HTTP), NLB is L4 (raw TCP/UDP, static IP, ultra-low latency, millions of connections).
resource "aws_autoscaling_group" "web" {
  desired_capacity    = 3
  min_size            = 2
  max_size            = 10
  vpc_zone_identifier = var.private_subnet_ids   # spread across AZs
  target_group_arns   = [aws_lb_target_group.web.arn]
  health_check_type   = "ELB"

  launch_template {
    id      = aws_launch_template.web.id
    version = "$Latest"
  }
}

resource "aws_autoscaling_policy" "cpu" {
  name                   = "target-cpu-60"
  autoscaling_group_name = aws_autoscaling_group.web.name
  policy_type            = "TargetTrackingScaling"
  target_tracking_configuration {
    predefined_metric_specification {
      predefined_metric_type = "ASGAverageCPUUtilization"
    }
    target_value = 60.0
  }
}

Lambda at Scale

Lambda inverts the model: no servers, just a function plus a trigger. AWS creates one execution environment per concurrent request and freezes it warm for reuse (~5–15 min) after the handler returns. Understanding that lifecycle explains cold starts, concurrency math, and every scaling limit.

Trigger classSourcesRetry / error model
SynchronousAPI Gateway, ALB, CognitoCaller waits; no auto-retry; client handles failure.
AsynchronousS3, SNS, EventBridge, SESLambda retries twice, then DLQ / on-failure destination.
Poll-based (stream/queue)SQS, Kinesis, DynamoDB Streams, MSKBatch polling; use ReportBatchItemFailures for partial retry.

Concurrency = invocation rate × average duration. At 1,000 req/s and 200 ms each you need 1,000 × 0.2 = 200 concurrent environments. The account starts with a soft limit of 1,000 concurrent executions, and each function can then scale by up to 1,000 new execution environments every 10 seconds (the older region-based 500–3,000 burst + 500/min model is retired).

  • Cold start — first request in a new environment pays for code download + runtime init + your out-of-handler init. Go/Rust ~50–100 ms; Python/Node ~200–500 ms; Java 3–10 s (or ~200–500 ms with SnapStart, no extra charge for Java; Python/.NET pay snapshot cache + restore fees).
  • Reserved concurrency — free; both caps a function's max and guarantees it that slice (protects a downstream DB, isolates a noisy function).
  • Provisioned concurrency — pre-warms N environments to kill cold starts on latency-critical paths; costs even while idle (~$0.0000045/GB-s).
  • Init outside the handler — put SDK clients and DB connections at module scope so they persist across warm invocations instead of rebuilding every call.
import boto3
# Runs once per cold start, reused on every warm invocation:
table = boto3.resource("dynamodb").Table("orders")

def handler(event, context):
    failures = []
    for record in event["Records"]:          # SQS batch
        try:
            process(record)
        except Exception:
            failures.append({"itemIdentifier": record["messageId"]})
    return {"batchItemFailures": failures}    # only failed msgs retry

ECS vs EKS

Both orchestrate containers; the split is AWS-native simplicity versus Kubernetes portability. ECS is AWS's homegrown scheduler with a free, fully managed control plane. EKS runs upstream Kubernetes with an AWS-managed control plane billed at $0.10/hour (~$73/month) per cluster. Same containers, very different operational surface.

DimensionECSEKS
Control planeFree, AWS-managed~$73/mo per cluster, AWS-managed (multi-AZ)
API / modelTask Definition, Task, Service, ClusterPod, Deployment, Service, Namespace (full k8s API)
Learning curveWeeks — AWS-native conceptsMonths — full Kubernetes
PortabilityAWS-only (lock-in)Any k8s → multi-cloud / hybrid
EcosystemAWS services, Service Connect (App Mesh was discontinued 30 Sep 2026)Helm, Operators, Istio, ArgoCD, Kubeflow
IAM to workloadTask RoleIRSA / Pod Identity (role per ServiceAccount)
Best forSmall team, pure AWS, fast time-to-prodK8s expertise, portability, complex/stateful, 100+ services
  • Concept map — ECS Task ≈ k8s Pod; ECS Service ≈ Deployment + HPA; Task Definition ≈ Pod spec + ConfigMap/Secret; Capacity Provider ≈ Node Group + autoscaler.
  • Both run on either Fargate (serverless) or EC2/managed-node data planes, and both use the awsvpc ENI-per-task/pod networking model.

Fargate vs EC2 Launch Type

Fargate is the serverless data plane for ECS and EKS — you hand AWS a task/pod with a vCPU+memory request and it provisions, patches, and isolates the host. There are no nodes to manage, no cluster capacity to plan, and each task gets a dedicated micro-VM kernel (stronger isolation than containers sharing an EC2 host OS). The EC2 launch type is the opposite: you own the instances, the AMI, patching, and bin-packing — in exchange for full control and GPU access.

AspectFargateEC2 launch type
You manageTasks/pods onlyInstances + OS + patching + capacity
BillingPer-task vCPU+memory, per-secondPer-instance (running or idle)
IsolationMicro-VM per task (kernel-level)Containers share host kernel
Startup~30–90 s cold provisionFast if instance already running
GPU / custom AMINoYes
SpotFargate Spot (~70% off)EC2 Spot (~90% off)
Wins on cost whenVariable / bursty / smallSteady, high sustained utilization
  • Right-size hard — Fargate memory is a hard ceiling; hit it and the OOM killer terminates the task instantly (no swap). Set CPU/memory from real Container Insights data, not guesses.
  • Cut startup — small images, ECR in-region, VPC endpoints, and Seekable OCI (SOCI) lazy-loading can drop task start from ~90 s to ~10 s.
  • Cost reality — for a flat 24/7 workload Fargate can run several times the price of a right-sized EC2 instance; the premium buys away all node management.
resource "aws_ecs_service" "web" {
  name          = "web"
  cluster       = aws_ecs_cluster.main.id
  desired_count = 3

  capacity_provider_strategy {   # base on-demand, surge on Spot
    capacity_provider = "FARGATE"
    base = 1
    weight = 20
  }
  capacity_provider_strategy {
    capacity_provider = "FARGATE_SPOT"
    weight = 80
  }
}

The Compute Decision

The whole module collapses into one axis: how much of the stack do you want to manage versus how much control do you need? Lambda is maximum abstraction (function), EC2 is maximum control (VM), and ECS/EKS/Fargate sit between on the container spectrum.

ServiceUnit of deployYou manageScalingBest for
LambdaFunctionCode onlyAutomatic, per-request (0 → thousands)Event-driven, bursty, short (<15 min) work.
FargateTask / PodContainer + task specApp Auto Scaling on task countServerless long-running containers, no node ops.
ECS (EC2)Task on your EC2Containers + EC2 fleetService scaling + ASG/capacity providerSteady containers, GPU, high utilization, AWS-native.
EKSPodk8s workloads (+ nodes if not Fargate)HPA / Cluster Autoscaler / KarpenterKubernetes shops, portability, complex platforms.
EC2Virtual machineOS, runtime, everything on itEC2 Auto Scaling GroupsFull control, legacy/stateful, custom kernels, GPU.
MANAGE MORE  <----------------------------------------------->  CONTROL MORE
   Lambda  -->  Fargate  -->  ECS/EKS on Fargate  -->  ECS/EKS on EC2  -->  EC2
 function      task         serverless pods           you own nodes        raw VM
 event-driven  no nodes     k8s w/o node ops          GPU / bin-pack       everything
  • Lambda vs Fargate — Lambda for <15 min, bursty, event-driven; Fargate for long-lived services, WebSockets, big memory (up to 244 GB at 32 vCPU), or full Docker needs.
  • Fargate vs EC2 launch type — Fargate for variable load and zero ops; EC2 for GPU, custom AMIs, or steady high utilization where reserved capacity is cheaper.
MODULE 13

AWS Storage Deep-Dive

Object, block, file, and archive — S3 classes and durability, EBS volume types, EFS, Glacier.

The Object Model: S3 Is Not a Filesystem

S3 exposes a flat, per-bucket key namespace. There are no real directories. A key like logs/2026/07/app.log is a single opaque string; the "folders" you see in the console are a UI fiction rendered by splitting on /. This matters: you cannot mv a "folder" atomically, and listing is a prefix scan, not a directory read.

  • Bucket — globally unique namespace, region-pinned. Bucket names collide across all AWS accounts on Earth.
  • Object — data blob (0 bytes to 50 TB, raised from 5 TB in Dec 2025) + metadata + a version ID. The unit of durability and access control.
  • Key — the full path-like string that uniquely identifies an object within a bucket. Prefix = any leading substring of the key.
  • ETag — content hash (MD5 for single PUT; composite for multipart). Used for integrity and conditional requests.

Eleven Nines of Durability & Strong Consistency

S3 Standard is designed for 99.999999999% (11 nines) annual durability. The mechanism: every PUT is synchronously replicated across a minimum of three Availability Zones before the request returns 200 OK. Continuous integrity checks (checksums, cross-AZ repair) heal bit-rot and device loss. Practically, 11 nines means if you store 10 million objects you can expect to lose one object roughly every 10,000 years.

Since December 2020, S3 provides strong read-after-write consistency for all objects in all regions, at no cost and with no performance penalty:

  • A successful PUT of a new object is immediately readable by a subsequent GET — no eventual-consistency window.
  • Overwrite PUTs and DELETEs are also strongly consistent for read-after-write and list-after-write.
  • Durability ≠ availability. Standard targets 99.99% availability; One Zone classes drop to 99.5% because a single-AZ loss takes the data offline.

S3 Storage Classes: Cost vs Retrieval

Every class stores the same object identically; you trade first-byte latency and per-GB price against retrieval fees and minimum storage durations. Prices below are us-east-1, per GB-month, as a stable reference point for relative comparison.

Class$/GB-moRetrieval latencyMin durationAZsBest for
S3 Standard0.0230msnone≥3Hot data, active workloads
Intelligent-Tieringtier price + monitoringmsnone≥3Unknown/shifting access patterns
Standard-IA0.0125ms30 days≥3Infrequent but latency-sensitive
One Zone-IA0.0100ms30 days1Recreatable, non-critical copies
Glacier Instant Retrieval0.0040ms90 days≥3Archive needing instant access
Glacier Flexible Retrieval0.00361 min – 12 hr90 days≥3Archive, minutes-to-hours OK
Glacier Deep Archive0.0009912 – 48 hr180 days≥3Compliance, tape replacement

Intelligent-Tiering auto-moves objects across frequent/infrequent/archive tiers based on observed access, charging a small per-object monitoring fee instead of a retrieval fee — the right default when you genuinely cannot predict access.

Lifecycle, Versioning & Events

Versioning keeps every mutation as a distinct version ID; a DELETE just writes a delete marker, so nothing is truly lost. Combined with MFA Delete and Object Lock (WORM), it is the primary defense against ransomware and fat-finger overwrites. Lifecycle policies then transition or expire objects by age and prefix, automating the cost ladder from the table above.

{
  "Rules": [{
    "ID": "ArchiveLogs",
    "Status": "Enabled",
    "Filter": { "Prefix": "logs/" },
    "Transitions": [
      { "Days": 30,  "StorageClass": "STANDARD_IA" },
      { "Days": 90,  "StorageClass": "GLACIER" },
      { "Days": 365, "StorageClass": "DEEP_ARCHIVE" }
    ],
    "Expiration": { "Days": 2555 },
    "NoncurrentVersionExpiration": { "NoncurrentDays": 90 }
  }]
}

Event notifications fire on object create/delete/restore to SQS, SNS, Lambda, or EventBridge — the backbone of serverless pipelines (e.g. thumbnail generation on upload).

upload  -->  s3:ObjectCreated:*  -->  Lambda  -->  transform + write derived object
  |
  +--> 30d --> STANDARD_IA --> 90d --> GLACIER --> 365d --> DEEP_ARCHIVE --> expire

Security: Block Public Access, Policies & Encryption

Access is granted only when there is an explicit Allow, no explicit Deny, and Block Public Access settings permit it. The layers, outermost first:

  1. Block Public Access (BPA) — account- and bucket-level master switch (four flags). Overrides any policy or ACL that would expose data publicly. Enable all four unless you are deliberately hosting a public site.
  2. Bucket policy — resource-based JSON; grants cross-account access and enforces conditions (encryption, TLS, source VPC).
  3. IAM policy — identity-based; what a given principal may do.
  4. ACLs — legacy per-object/bucket grants. Disabled by default on new buckets ("Bucket owner enforced"); avoid.
  5. Pre-signed URLs — time-boxed access to one object (seconds to 7 days) without granting standing permissions.

Encryption at rest is on by default (SSE-S3). Options: SSE-S3 (AES-256, AWS-managed keys), SSE-KMS (KMS key, per-request audit trail + key-policy control; use S3 Bucket Keys to cut KMS cost), and SSE-C (customer-supplied key, you manage rotation; disabled by default on new buckets since Apr 2026, so enable it per bucket via PutBucketEncryption if you truly need it).

{
  "Sid": "DenyUnencryptedAndInsecure",
  "Effect": "Deny",
  "Principal": "*",
  "Action": "s3:PutObject",
  "Resource": "arn:aws:s3:::my-bucket/*",
  "Condition": {
    "StringNotEquals": { "s3:x-amz-server-side-encryption": "aws:kms" }
  }
}

Prefixes, Throughput & Large Objects

S3 scales request rate per prefix, not per bucket. Each prefix sustains 3,500 PUT/COPY/POST/DELETE and 5,500 GET/HEAD requests per second, and S3 auto-partitions as load grows. To go higher, spread keys across many prefixes — a workload hitting one prefix hard can be sharded into N prefixes for roughly N× the throughput.

  • Multipart upload — recommended above 100 MB, mandatory above 5 GB. Up to 10,000 parts, 5 MB–5 GB each, uploaded in parallel with per-part retry.
  • Byte-range GETs — fetch parts of a large object in parallel; resume interrupted downloads.
  • Transfer Acceleration — routes uploads through CloudFront edge locations for long-haul speedups.
  • S3 Select — push down SQL to return only matching rows/columns from CSV/JSON/Parquet, cutting bytes scanned and egress. Closed to new customers (existing users continue): use Athena or client-side filtering instead.

Modern guidance: random high-entropy key prefixes are no longer required for hot buckets since S3 auto-scales partitions — but deliberate prefix design still helps you exceed the per-prefix ceiling predictably.

EBS: Block Storage Volume Types

EBS is network-attached block storage for a single EC2 instance, presented as a raw device. A volume lives in exactly one AZ and is replicated within that AZ only. Snapshots are incremental point-in-time backups stored in S3 (not reachable via the S3 API); they are how you clone a volume into another AZ or region.

TypeMediaMax IOPSMax throughputUse case
gp3SSD80,0002,000 MiB/sRecommended general purpose; IOPS/throughput decoupled from size
gp2SSD16,000250 MiB/sLegacy general purpose; IOPS scales with size
io2 Block ExpressSSD256,0004,000 MiB/sMission-critical DBs, sub-ms latency, 99.999% durable
io1SSD64,0001,000 MiB/sHigh-IOPS DBs (predecessor to io2)
st1HDD500500 MiB/sThroughput-heavy sequential: logs, big data, streaming
sc1HDD250250 MiB/sCold, infrequently accessed, lowest-cost HDD

gp3 baseline is 3,000 IOPS / 125 MiB/s free of size, then you pay to provision more — usually ~20% cheaper than gp2 at equal performance. Elastic Volumes let you grow size, change type, or tune IOPS live without detaching. Multi-Attach (io1/io2 only) attaches one volume to multiple instances in the same AZ for clustered apps.

EFS vs FSx vs Instance Store

When multiple instances need a shared filesystem, block storage (single-attach EBS) does not fit. EFS is a fully managed elastic NFSv4 filesystem, mounted concurrently by thousands of Linux instances / containers across multiple AZs. It grows and shrinks automatically — no capacity to provision — and offers Standard, One Zone, IA, and Archive (Regional, Elastic throughput only) tiers with lifecycle management, plus General Purpose vs Max I/O performance modes and Bursting/Provisioned/Elastic throughput modes.

FSx is the family for when you need a specific protocol or engine that EFS does not speak:

ServiceProtocol / engineReachUse case
EFSNFS v4 (Linux)Multi-AZ, elasticShared Linux/container storage, home dirs, CMS
FSx for Windows File ServerSMB / NTFSSingle/Multi-AZWindows apps, Active Directory integration
FSx for LustreLustre (HPC)Scratch/persistentHPC, ML training, S3-linked high-throughput
FSx for NetApp ONTAPNFS+SMB+iSCSIMulti-AZMultiprotocol, snapshots, on-prem ONTAP lift
FSx for OpenZFSNFS (ZFS)Single/Multi-AZZFS snapshots/clones, low-latency NFS

Instance Store is physically-attached NVMe/SSD on the host — the fastest storage available (millions of IOPS) but ephemeral: data is lost on stop, hibernate, or termination, and it cannot be snapshotted. Use it only for scratch, caches, buffers, and replicated/reconstructable data.

PropertyEBSInstance Store
PersistenceSurvives stop/terminateLost on stop/terminate
SnapshotsYes (to S3)No
Detach / re-attachYesNo (bound to host)
PerformanceGood (gp3 up to 80k IOPS)Extreme (local NVMe)

Glacier: Archives, Vaults & Retrieval Tiers

Glacier is the archival tier, now surfaced mainly as S3 storage classes. The original standalone Glacier vault service has been closed to new customers since 15 Dec 2025 (existing customers continue), so new designs use S3 Glacier classes with Object Lock. The legacy vault/archive model: an archive (up to 40 TB, immutable/WORM once written) is the storage unit; a vault groups archives. Vault Lock enforces compliance controls that even the account owner cannot revoke — e.g. "no deletion for 7 years" for SEC 17a-4 or HIPAA retention.

Retrieval from Glacier Flexible/Deep Archive is asynchronous — you request a restore, then read once it lands. Tiers trade speed for cost:

TierFlexible RetrievalDeep ArchiveCost
Expedited1–5 minn/aHighest
Standard3–5 hr~12 hrDefault
Bulk5–12 hr~48 hrLowest

Glacier Instant Retrieval is the exception: it is an S3 class with millisecond synchronous access (no restore step) for archives you occasionally need fast, priced between Standard-IA and Flexible. Early-delete fees apply below the class minimum (90 days for Glacier tiers, 180 for Deep Archive).

MODULE 14

AWS Database Deep-Dive

Pick the right store: RDS/Aurora, DynamoDB, ElastiCache/Redis, Redshift — and why.

RDS vs Aurora: Managed Relational, Two Storage Models

Both speak SQL and run MySQL/PostgreSQL, but they replicate differently. RDS bolts HA on at the instance layer — a synchronous standby you never read. Aurora decouples compute from a shared, distributed storage fleet, which is why its failover and read-scaling numbers are structurally better.

  • RDS engines — PostgreSQL, MySQL, MariaDB, Oracle, SQL Server (+ Aurora). Oracle/SQL Server are RDS-only; Aurora is MySQL/PostgreSQL-compatible only.
  • Multi-AZ (HA, not scale) — synchronous standby in a second AZ. Not readable; it just waits. Automatic failover on infra failure via DNS CNAME swap.
  • Read replicas (scale, not HA) — asynchronous copies that serve reads; eventually consistent; promotable to standalone. RDS: up to 15 for MySQL/MariaDB/PostgreSQL (5 for Oracle/SQL Server). Aurora: up to 15, all sharing one storage volume.
  • Aurora storage — log-structured, auto-grows to 128 TiB (256 TiB on newer engine versions, e.g. PostgreSQL 17.5+/16.9+/15.13+, MySQL 3.10+), 6 copies across 3 AZs. Writes ack on 4/6 quorum; reads need 3/6. Replicas attach to the same volume, so no replication lag from copying data blocks.
DimensionRDS (Multi-AZ)Aurora
ReplicationInstance-level, 1 sync standbyStorage-level, 6-way across 3 AZs
Failover time~60–120 s (DNS + standby promote)< 30 s (replica already attached)
Read replicasUp to 15 (5 for Oracle/SQL Server), each its own copyUp to 15, shared volume
StoragePre-provisioned EBS (gp3), auto-scale onAuto-scaling to 128 TiB (256 TiB on newer versions), pay per use
ServerlessNoServerless v2, 0–256 ACU (~2 GB RAM/ACU); min 0 = auto-pause
ExtrasBroad engine choice (Oracle/SQL Server)Backtrack, Global DB, parallel query
Cost~$210/mo db.r6g.large (2x for Multi-AZ)~20% premium + I/O charges
resource "aws_db_instance" "postgres" {
  engine                = "postgres"
  instance_class        = "db.r6g.large"
  allocated_storage     = 100
  max_allocated_storage = 1000   # storage autoscaling
  multi_az              = true    # sync standby, ~60-120s failover
  storage_encrypted     = true
  backup_retention_period = 7     # PITR window, up to 35 days
}

DynamoDB: Serverless NoSQL, Single-Digit ms at Any Scale

DynamoDB trades JOINs and ad-hoc queries for predictable single-digit-millisecond latency that does not degrade as the table grows to terabytes. The price of that: you design the schema around your access patterns, not around normalized entities.

  • Partition key (PK) — hashed to place the item on a physical partition. Determines distribution.
  • Sort key (SK) — items sharing a PK are stored together, sorted by SK. Enables range queries (begins_with, between) within a partition.
  • GetItem = PK(+SK), one item, fastest. Query = PK + SK condition, a range. Scan = full table read — expensive, avoid.
  • GSI — different PK/SK, own capacity, eventually consistent, up to 20/table, addable anytime. LSI — same PK, alternate SK, shares table capacity, strongly-consistent option, up to 5, must be defined at create time.
  • DAX — in-memory, API-compatible cache; drops reads to microseconds (~10x) with no app changes. Streams — ordered change log feeding Lambda (CDC, invalidation, fan-out).
Capacity modeHow you payUse when
On-demand~$0.125 / M reads, ~$0.625 / M writes (us-east-1, halved Nov 2024); scales instantlySpiky / unknown traffic, new apps, scale-to-zero
ProvisionedRCU $0.00013/hr, WCU $0.00065/hr; + Auto ScalingSteady, predictable load; reserved capacity = up to 77% off

Single-table design collapses related entities into one table so a single Query hydrates a whole aggregate:

PK              SK                GSI1PK           GSI1SK
--------------  ----------------  ---------------  --------------
USER#123        PROFILE           STATUS#pending   ORDER#2024-001
USER#123        ORDER#2024-001    STATUS#pending   ORDER#2024-002
ORDER#2024-001  ITEM#PROD-789
PRODUCT#789     METADATA

Get profile     -> PK=USER#123, SK=PROFILE
Get user orders -> PK=USER#123, SK begins_with "ORDER#"
Orders by status-> GSI1, PK=STATUS#pending
import boto3
tbl = boto3.resource("dynamodb").Table("app")

# All orders for a user in one round trip
resp = tbl.query(
    KeyConditionExpression="PK = :u AND begins_with(SK, :p)",
    ExpressionAttributeValues={":u": "USER#123", ":p": "ORDER#"},
)  # single-digit ms, no Scan

ElastiCache: Redis vs Memcached

ElastiCache is managed in-memory (sub-ms) for caching, sessions, and real-time features. Three engines: Valkey (the open-source Redis fork, Redis OSS-compatible and the recommended default for new clusters), Redis OSS (frozen at 7.1 on ElastiCache), and Memcached. The capabilities differ sharply — the answer is Valkey/Redis-style roughly 95% of the time; the table below says "Redis" for the shared Valkey/Redis OSS feature set.

FeatureValkey / Redis OSSMemcached
Data typesStrings, Lists, Sets, Sorted Sets, Hashes, Streams, HLLStrings only
Replication / HARead replicas, Multi-AZ auto-failoverNone (node loss = data loss)
ShardingCluster mode: 16,384 hash slots, 1–500 shardsClient-side node hashing
PersistenceRDB snapshots + AOF (backups); Valkey 9.0+ adds optional Multi-AZ transaction-log durabilityNone
ThreadingSingle-threaded command execution; Enhanced I/O threads offload network workMulti-threaded
Pub/Sub, Lua, TXYesNo
  • Cluster mode disabled — one shard, primary + up to 5 read replicas. Total data = one node (e.g. ~419 GiB on r6g.16xlarge, ~505 GiB on r8g.16xlarge; the largest listed node, cache.r5.24xlarge, is ~636 GiB). Vertical scaling only.
  • Cluster mode enabled — data partitioned across shards, capacity = sum of shards, online resharding, higher write throughput. Watch CROSSSLOT on multi-key ops.
  • Serverless — auto-scales 0→TBs, Multi-AZ by default, pay per ECPU + storage; use for unknown/variable load.
  • Durability tier — need a Redis-compatible primary store with zero data loss? The classic answer is MemoryDB. Newer: ElastiCache for Valkey 9.0+ (node-based) can also persist to a Multi-AZ transactional log — synchronous writes for zero loss at single-digit-ms write latency, asynchronous for microsecond writes with up to ~10 s at risk.

The high-value patterns lean on Redis data structures, not plain key-value:

# Leaderboard: Sorted Set, O(log n) rank + range
r.zadd("lb:game", {"player1": 1600, "player2": 1200})
r.zrevrange("lb:game", 0, 9, withscores=True)   # top 10
r.zrevrank("lb:game", "player1")                 # exact rank

# Cache-aside with TTL (the default caching pattern)
def get_user(uid):
    key = f"user:{uid}"
    if (hit := r.get(key)):
        return json.loads(hit)
    row = db.query("SELECT * FROM users WHERE id=%s", uid)
    r.setex(key, 3600, json.dumps(row))          # 1h safety TTL
    return row

# Distributed lock: SET NX EX, release via Lua compare-and-del
r.set("lock:job", token, nx=True, ex=10)

Redshift: Columnar MPP Data Warehouse

Redshift is not an OLTP database — it is a petabyte-scale analytics engine. The design choices (columnar storage, MPP, compression) all optimize scanning billions of rows over a few columns, which is exactly what OLTP indexes are bad at.

  • Leader node parses SQL, builds the plan, aggregates results. Compute nodes execute slices of the plan in parallel (MPP).
  • Columnar storage — data laid out by column, so a query touching 3 of 200 columns reads only those blocks; huge I/O reduction vs row stores.
  • Compression (encoding) — per-column, auto-selected; shrinks storage and further cuts I/O.
  • Spectrum queries S3 directly (no load step); Concurrency Scaling adds transient clusters for bursts; Materialized views pre-compute; WLM prioritizes short queries over long ETL.
-- Columnar + MPP: scans only the columns referenced, across all slices
SELECT date_trunc('day', order_ts) AS day,
       region,
       sum(amount) AS revenue
FROM   fact_orders            -- billions of rows
WHERE  order_ts > current_date - 30
GROUP  BY 1, 2
ORDER  BY revenue DESC;       -- seconds, not minutes

Selection Matrix: Workload → Service

The interview move is to start from the access pattern, not the brand name. Map the workload, then justify.

WorkloadServiceWhy
JOINs, ACID, ad-hoc queriesRDS / AuroraRelational model, full transactions
Same, variable/bursty loadAurora Serverless v2Scales ACUs in seconds; no idle compute cost only if min capacity = 0 (auto-pause)
Same, need Oracle / SQL ServerRDSAurora is MySQL/PostgreSQL only
Key-value / key-range at massive scaleDynamoDBFlat < 10 ms latency, serverless, no JOINs
Read-heavy hotspot on any DBElastiCache (Valkey/Redis)Sub-ms cache-aside, offload the primary
Sessions / leaderboards / rate limitElastiCache (Valkey/Redis)Hashes, Sorted Sets, TTL, atomic ops
DynamoDB reads at microsecondsDAXAPI-compatible in-memory front cache
BI / dashboards / big scansRedshiftColumnar MPP over petabytes
Redis as durable primary storeMemoryDBMulti-AZ log, zero data loss on failover

Design Drills

Every store decision reduces to: what are the read/write patterns, the scale, the consistency need, and the latency budget? Rehearse defending a pick out loud.

  1. Global session store, 10M sessions. ElastiCache Redis (or Serverless), Hash per session, 30-min sliding TTL, Multi-AZ so a mass re-login does not stampede auth. Sessions are ephemeral → optimize speed/availability over durability.
  2. E-commerce orders, unpredictable spikes. DynamoDB on-demand, single-table (USER#id PK, ORDER#date SK), GSI on status, Streams → Lambda for fulfillment. Add DAX if a product page is a read hotspot.
  3. Financial ledger with reporting. Aurora PostgreSQL (ACID + JOINs), read replicas for reports, nightly ETL into Redshift for BI dashboards.
MODULE 15

AWS Networking Deep-Dive

VPC design, routing, and edge: subnets, NAT, peering, Transit Gateway, PrivateLink, Route53, CloudFront, API Gateway.

VPC Anatomy & CIDR

A VPC is a logically isolated slice of AWS you carve out with a private CIDR block. Everything else — subnets, route tables, gateways — hangs off that address space. CIDR is chosen once and effectively forever: overlap with a future peer, VPN, or Transit Gateway and you cannot route, so you rebuild.

  • CIDR block — the VPC's IPv4 range, e.g. 10.0.0.0/16 = 65,536 addresses. Prefer RFC1918 space; avoid the default 172.31.0.0/16. Secondary CIDRs can be bolted on later.
  • Subnet — a CIDR slice pinned to exactly one AZ. AWS reserves 5 IPs per subnet (network, VPC router, DNS, future, broadcast), so a /24 gives 251 usable, a /28 (minimum) gives 11.
  • Public subnet — route table sends 0.0.0.0/0 to an Internet Gateway; instances may hold public IPs.
  • Private subnet — 0.0.0.0/0 points at a NAT Gateway (outbound-only) or nowhere (isolated).
  • IGW — horizontally scaled, redundant, free; one per VPC; enables bidirectional internet.
  • NAT Gateway — AWS-managed; the default zonal mode is AZ-scoped and needs an Elastic IP (a regional-mode NAT gateway now spans AZs automatically); lets private instances reach out (patches, APIs) while blocking inbound initiation.
  • Elastic IP — a static public IPv4 you own; attached to the NAT GW or a bastion. Idle EIPs now bill, and all public IPv4 carries an hourly charge.

Public vs private is purely a routing property. The same subnet flips public or private by swapping its route table — nothing about the subnet's CIDR changes.

CIDRTotal IPsUsable (−5)Typical use
/1665,53665,531Whole VPC
/204,0964,091Large tier subnet
/23512507App tier per AZ
/24256251Public / data tier
/281611Min subnet size
VPC 10.0.0.0/16
  AZ-a  public 10.0.0.0/24  private 10.0.10.0/23  data 10.0.20.0/24
  AZ-b  public 10.0.1.0/24  private 10.0.12.0/23  data 10.0.21.0/24
  AZ-c  public 10.0.2.0/24  private 10.0.14.0/23  data 10.0.22.0/24

Route Tables & NAT Economics

Every subnet associates with exactly one route table; routes are evaluated most-specific-prefix-first. The implicit local route (the VPC CIDR) always wins for in-VPC traffic and cannot be removed or overridden.

DestinationTargetMeaning
10.0.0.0/16localStays inside the VPC
172.16.0.0/16pcx-…Peered VPC
192.168.0.0/16vgw-…On-prem via VPN gateway
0.0.0.0/0igw-… / nat-…Default route (public / private)
Internet GatewayNAT Gateway
DirectionBidirectionalOutbound only
CostFree~$0.045/hr + $0.045/GB
AvailabilityRegion-wide, redundantZonal: AZ-scoped (1 per AZ for HA); regional mode auto-expands across AZs
ThroughputUnmetered5 Gbps baseline, auto-scales to 100 Gbps
SubnetPublicLives in public, serves private

Security Groups vs NACLs

Two firewall layers, deliberately different. Security Groups guard the instance ENI and are stateful; NACLs guard the subnet boundary and are stateless. In interviews the discriminator is return traffic.

FeatureSecurity GroupNACL
LevelInstance / ENISubnet
StateStatefulStateless
RulesAllow onlyAllow and Deny
EvaluationAll rules (logical OR)Numbered, first match wins
DefaultDeny in, allow outDefault NACL allows all
Can referenceOther SG IDsCIDR only

SG chaining is the least-privilege pattern: reference SGs, not hardcoded IPs, so scaling instances stay covered. ALB-SG allows 80/443 from the world; App-SG allows 8080 from ALB-SG; DB-SG allows 5432 from App-SG. No IP ever appears past the edge.

Peering vs Transit Gateway vs PrivateLink

Three ways to connect networks, each solving a different scaling problem. Peering is a 1:1 wire; Transit Gateway is a hub-and-spoke router; PrivateLink exposes a single service, not a whole network.

  • VPC Peering — direct point-to-point, private IP routing, cross-region/cross-account. Free (data transfer only). No transitive routing (A↔B and B↔C does not give A↔C) and no overlapping CIDRs. Great for 2–3 VPCs.
  • Transit Gateway — a regional cloud router; each VPC/VPN/DX is an attachment. Transitive by design, centralized route tables, scales to thousands of VPCs. ~$0.05/hr per attachment + $0.02/GB.
  • VPC Endpoints — Gateway type — route-table target for S3 and DynamoDB only. Free. Traffic never leaves the AWS backbone; controlled by a prefix list.
  • VPC Endpoints — Interface type (PrivateLink) — an ENI with a private IP for 100+ services (SSM, ECR, SQS, SNS, Kinesis) or your own NLB-fronted service. ~$0.01/hr per AZ + $0.01/GB; DNS resolves to the private IP; SG-controlled.
PeeringTransit GatewayPrivateLink
TopologyFull mesh (n²)Hub-and-spokeService exposure
TransitiveNoYesN/A (single endpoint)
ScopeWhole VPC ↔ VPCMany VPCs + hybridOne service only
CIDR overlapNot allowedNot allowedAllowed (no routing)
CostData onlyAttach + GBHourly + GB

Route 53 — DNS & Routing Policies

Route 53 is authoritative DNS plus a traffic router. A hosted zone holds records for a domain: public zones answer the internet, private zones answer only inside associated VPCs (internal service discovery). The AWS-only Alias record is the workhorse — it points at ELB, CloudFront, or S3, works at the zone apex (where CNAME is illegal), resolves with no extra lookup, and is free.

RecordMaps toNote
A / AAAAIPv4 / IPv6Direct address
CNAMEAnother hostnameNot valid at apex
AliasAWS resourceApex-safe, free, health-aware
MX / TXT / NSMail / metadata / delegationSPF, DKIM, subdomain NS
PolicyBehaviorUse case
SimpleOne record, no health checkSingle resource
WeightedSplit by weight (e.g. 80/20)A/B, canary rollout
LatencyLowest-latency region winsMulti-region perf
FailoverPrimary→secondary on health failActive-passive DR
GeolocationBy user's country/continentLocalization, compliance
MultivalueUp to 8 healthy answersCheap health-checked LB

Health checks probe an endpoint (HTTP/HTTPS/TCP) on an interval; failover, multivalue, and weighted policies consult them to withdraw dead targets. Alias records with evaluate_target_health = true inherit the ELB's own health.

resource "aws_route53_record" "primary" {
  zone_id = aws_route53_zone.main.zone_id
  name    = "app.example.com"
  type    = "A"
  alias {
    name                   = aws_lb.primary.dns_name
    zone_id                = aws_lb.primary.zone_id
    evaluate_target_health = true
  }
  failover_routing_policy { type = "PRIMARY" }
  set_identifier  = "primary"
  health_check_id = aws_route53_health_check.primary.id
}

CloudFront — the Edge CDN

CloudFront is a global CDN of edge PoPs that caches content close to users, terminates TLS at the edge, and shields the origin. A distribution has one or more origins (S3, ALB/EC2 custom origin, MediaPackage) and a set of cache behaviors that map path patterns to an origin plus a cache/origin-request policy.

  • Cache behavior — path pattern (e.g. /static/*) → origin, with TTLs and which headers/cookies/query strings form the cache key.
  • TTL & invalidation — objects live for their TTL; forcing early eviction via invalidation costs money, so version asset filenames instead.
  • OAC (Origin Access Control) — the modern replacement for OAI; locks an S3 origin so objects are reachable only through CloudFront (SigV4-signed), never via the public bucket URL.
  • Security — free ACM TLS certs, AWS WAF and Shield for L7/DDoS, signed URLs/cookies for paid content.
  • Edge compute — CloudFront Functions (lightweight JS, header/URL rewrites, sub-ms) vs Lambda@Edge (Node/Python, heavier logic like auth or image resize).
CloudFront FunctionsLambda@Edge
RuntimeJS (edge)Node / Python
LatencySub-millisecondMilliseconds
TriggersViewer req/respViewer + origin req/resp
UseHeader/URL rewrite, redirectsAuth, image resize, A/B

API Gateway — REST, HTTP & WebSocket

API Gateway is a managed front door for APIs: it authenticates, throttles, transforms, caches, and routes to Lambda, HTTP backends, or AWS services directly. Pick the API flavor by feature-vs-cost, not habit.

REST APIHTTP APIWebSocket API
Cost/latencyHigher~70% cheaper, lower latencyPer-message + connection-minutes
FeaturesFull: validation, transforms, WAF, API keys, cacheLean: JWT, proxy, CORSPersistent bidirectional
AuthorizersIAM, Cognito, LambdaJWT, Lambda, IAMLambda ($connect)
Best forFeature-rich public APIsServerless microservicesChat, live dashboards
  • Authorizers — IAM (SigV4), Cognito User Pools, or a Lambda authorizer for custom/3rd-party JWT logic. HTTP APIs add native JWT validation.
  • Throttling — account and per-stage/per-method rate + burst limits; Usage Plans + API Keys enforce per-client quotas (monetization, tiering).
  • Stages — named deployments (dev/test/prod), each with its own variables and throttles; canary releases shift a % of traffic to a new deployment.
  • Caching — REST APIs can provision a response cache with a TTL to cut backend calls and latency.
Resources:
  Api:
    Type: AWS::ApiGatewayV2::Api
    Properties:
      Name: orders-http-api
      ProtocolType: HTTP
  Stage:
    Type: AWS::ApiGatewayV2::Stage
    Properties:
      ApiId: !Ref Api
      StageName: prod
      DefaultRouteSettings:
        ThrottlingRateLimit: 1000    # req/s steady
        ThrottlingBurstLimit: 2000   # burst bucket

Packet Walk: User to Private EC2

Tie it together by tracing one request end to end. Notice where NAT is and is not involved, and how stateful SGs let the response flow back with no extra rules.

User browser
   |  1. DNS: Route 53 resolves app.example.com -> CloudFront / ALB
   v
CloudFront edge (optional) -- TLS, cache check, WAF
   |  2. miss -> origin fetch over HTTPS
   v
Internet Gateway  (region edge of VPC)
   |  3. 0.0.0.0/0 route brought traffic to the public subnet
   v
Public subnet: ALB  (ALB-SG allows 443 from 0.0.0.0/0)
   |  4. listener rule -> target group, internal routing
   v
Private subnet: EC2 app  (App-SG allows 8080 FROM ALB-SG only)
   |  5. queries DB via App-SG -> DB-SG (5432)
   v
Data subnet: RDS
   ^
   |  6. response retraces path; SGs are STATEFUL so replies
   |     need no return rule. NAT is NOT used -- all in-VPC.
   +-- outbound to internet (patch pull) WOULD use NAT GW.
MODULE 16

AWS Security & Compliance

IAM policy evaluation, KMS envelope encryption, WAF, and the shared-responsibility model.

Shared Responsibility Model

AWS splits security into two accountable halves. The dividing line moves depending on the abstraction level of the service you pick — the more managed the service, the more AWS owns.

  • AWS — security of the cloud — physical data centers, hypervisor, host OS patching, network fabric, managed-service internals (e.g. the RDS engine host, Lambda runtime sandbox).
  • Customer — security in the cloud — IAM policies, guest OS patching (EC2), security groups, encryption choices, data classification, application code, and who can call what.
ModelCustomer patches OS?Customer owns
IaaS (EC2)YesGuest OS, runtime, app, data, firewall, IAM
Container (ECS/EKS on EC2)Node OS yesImage, task role, app, data
Serverless (Lambda, Fargate)NoCode, IAM, data, dependencies
Managed (S3, DynamoDB)NoAccess policy, encryption config, data

IAM Principals & Policy Types

A principal is any entity that makes a signed request. IAM answers one question per request: is this principal authorized for this action on this resource under these conditions?

  • Users — long-lived identity for a human or legacy app. Has a console password and/or access keys. Access keys are the thing that leaks — prefer roles.
  • Roles — an identity with no long-term credentials. Assumed to mint short-lived STS credentials. Used by services (EC2, Lambda), cross-account access, and federated SSO.
  • Service principals — AWS services (e.g. lambda.amazonaws.com) named in a role's trust policy so the service can assume it.
  • Root user — the account owner; unrestricted, cannot be limited by IAM or SCP. Lock it: hardware MFA, no access keys, billing only.

Permissions come from up to six policy types evaluated together. Know which are guardrails (cap the max) versus grants (add permission).

Policy typeAttached toRole in evaluation
Identity-basedUser / group / roleGrants — what the principal can do
Resource-basedResource (S3 bucket, KMS key, SQS)Grants — names a Principal; enables cross-account
SCPOrg OU / accountGuardrail — caps max perms, never grants
RCP (resource control policy)Org OU / accountGuardrail — caps max perms on resources in the org, never grants
Permission boundaryUser / roleGuardrail — caps that identity's max perms
Session policyPassed at AssumeRoleGuardrail — caps the temporary session

Policy Evaluation Logic

The single most tested IAM fact: evaluation is deny-biased. Everything starts denied; an allow can lift that; any explicit deny — from any policy type — is final.

Request → collect ALL applicable policies
  1. Explicit DENY anywhere?  ──► DENY  (wins, always)
  2. SCP / RCP / boundary / session allow the action?  no ──► DENY
  3. Explicit ALLOW in identity or resource policy?  no ──► DENY (implicit)
  4. Otherwise ──► ALLOW

Precedence:  explicit deny  >  explicit allow  >  implicit (default) deny

For guardrails, the effective permission set is an intersection: a principal can only do what identity policy AND SCP AND RCP AND permission boundary AND session policy all permit. Widening one does nothing if another is narrower.

  • Same account — identity or resource policy granting is enough (a union of grants), still subject to guardrails.
  • Resource policy naming a user or session ARN — within the same account, a resource policy that names an IAM user ARN or an assumed-role session ARN as Principal is not capped by the implicit deny of identity policies, boundary or session policy (an explicit deny still wins). One naming the role ARN is still capped by boundary and session policy.
  • Cross account — you need a grant on both sides: the resource policy in Account B must name Account A's principal, AND Account A's identity policy must allow the action.
  • Permission boundary use case — let developers create roles without privilege escalation: any role they mint is capped by the boundary you attached, so they cannot grant more than they hold.

STS, AssumeRole & Instance Profiles

Roles are useless until assumed. STS (Security Token Service) exchanges a trust relationship for temporary credentials — an access key, secret key, and a session token — that expire in 15 minutes to 12 hours (1 hour default; role chaining is hard-capped at 1 hour).

  1. The role's trust policy (a resource-based policy on the role) says who may assume it via sts:AssumeRole.
  2. A principal calls AssumeRole; STS checks the trust policy, then returns short-lived creds scoped by the role's permission policy (and any session policy).
  3. Creds auto-expire — nothing to rotate, nothing to leak long-term.

An instance profile is the container that binds an IAM role to an EC2 instance. The EC2 metadata service (IMDS) surfaces auto-rotating credentials at a link-local endpoint; the SDK reads them transparently. Always enforce IMDSv2 (token-based) to block SSRF credential theft.

{
  "Version": "2012-10-17",
  "Statement": [{
    "Sid": "AllowEC2ToAssume",
    "Effect": "Allow",
    "Principal": { "Service": "ec2.amazonaws.com" },
    "Action": "sts:AssumeRole"
  }]
}

Trust policy above; the permission policy below scopes what the app can actually touch — least privilege, specific ARNs, no wildcards.

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "ReadAppBucket",
      "Effect": "Allow",
      "Action": ["s3:GetObject", "s3:ListBucket"],
      "Resource": [
        "arn:aws:s3:::acme-app-data",
        "arn:aws:s3:::acme-app-data/*"
      ],
      "Condition": {
        "IpAddress": { "aws:SourceIp": "10.0.0.0/16" }
      }
    },
    {
      "Sid": "ReadDbSecret",
      "Effect": "Allow",
      "Action": "secretsmanager:GetSecretValue",
      "Resource": "arn:aws:secretsmanager:us-east-1:123456789012:secret:prod/db/credentials-*"
    }
  ]
}

KMS & Envelope Encryption

KMS creates and guards cryptographic keys inside FIPS-validated HSMs. The root key material — the KMS key (formerly CMK) — never leaves KMS in plaintext. To encrypt bulk data efficiently, KMS uses envelope encryption.

ENCRYPT
  1. App calls GenerateDataKey(KeyId)
  2. KMS returns: plaintext data key  +  data key encrypted under the KMS key
  3. App encrypts data with plaintext data key (fast, local, AES-256)
  4. Store: ciphertext  +  encrypted data key ; wipe plaintext key from RAM

DECRYPT
  1. App sends encrypted data key to KMS Decrypt
  2. KMS unwraps it with the KMS key, returns plaintext data key
  3. App decrypts data locally, then discards the key

Why envelope: only the tiny data key crosses the wire to KMS, so large payloads never transit KMS (throughput + cost), and the durable KMS key stays HSM-bound.

Key typeRotationPolicy controlCost
AWS ownedAWS-managed, opaqueNoneFree
AWS managed (aws/s3)Automatic, annualCannot edit policyNo monthly fee; pay per API call
Customer managedOptional auto (default 365 days; configurable 90–2,560) + on-demandFull key policy + grants~$1/key/month + $0.03/10K requests
Imported (BYOK)On-demand only (you import new material); no automaticFull control~$1/key/month + requests
  • Key policy — the primary access control on a customer-managed key. Even a full IAM admin is denied unless the key policy (or a grant) allows it; the policy must enable IAM delegation via the account root.
  • Grants — programmatic, temporary permission delegation to a principal for specific operations, ideal for AWS services acting on your behalf without editing the key policy.
  • Rotation keeps old backing keys — old ciphertext still decrypts; only new encryptions use the new material. The key ARN is stable, so consumers need no change.
  • SSE integration — S3 (SSE-KMS), EBS, RDS, and Secrets Manager all call GenerateDataKey/Decrypt under the hood; you just point them at a key ARN.

WAF & Shield

WAF is a layer-7 firewall that inspects HTTP(S) requests before they reach your origin. You attach a Web ACL (an ordered rule list) to CloudFront, ALB, API Gateway, AppSync, or Cognito user pools. Shield handles the layer 3/4 DDoS problem WAF cannot see.

Rule typeCatchesAction options
AWS Managed RulesCore rule set, SQLi, XSS, known bad inputs, IP reputation, bot controlAllow / Block / Count / CAPTCHA / Challenge
Rate-based> N requests per evaluation window (default 5 min; 1, 2, 5 or 10 min configurable) from one IP or key (brute force, L7 flood)Block / CAPTCHA over threshold
IP set / geo matchAllow/block lists, geo-blocking by countryAllow / Block
String / regex matchHeaders, URI, body, query argsAllow / Block / Count
  • Count mode — deploy a new rule in Count first to measure false positives before flipping it to Block. This is the safe rollout pattern interviewers want to hear.
  • Shield Standard — free, always on, absorbs common SYN/UDP-flood and reflection attacks at the edge.
  • Shield Advanced — ~$3,000/month, adds the Shield Response Team (SRT, needs Business/Enterprise Support), cost-protection credits for scale-out during an attack, and richer L7 detection alongside WAF.

Secrets Manager vs Parameter Store

Both store sensitive values encrypted with KMS and gate access with IAM. The split is rotation, cross-account, and cost — secrets that must rotate versus config that just needs to be safe.

DimensionSecrets ManagerSSM Parameter Store
Built forSecrets (DB creds, API keys)Config + secrets (SecureString)
RotationNative, Lambda-drivenNone built-in
Cross-accountYes (resource policy)Standard: no; Advanced: limited
Generate passwordsYesNo — stores only
Cost~$0.40/secret/month + APIStandard free; Advanced ~$0.05/param/month
resource "aws_secretsmanager_secret" "db" {
  name                    = "prod/db/credentials"
  recovery_window_in_days = 7
}

resource "aws_secretsmanager_secret_rotation" "db" {
  secret_id           = aws_secretsmanager_secret.db.id
  rotation_lambda_arn = aws_lambda_function.rotate.arn
  rotation_rules { automatically_after_days = 30 }
}

Compliance & Audit

Compliance is proving your controls work. The Well-Architected Security Pillar frames it: strong identity foundation, traceability, defense in depth, encryption everywhere, automate security, prepare for incidents. Three services provide the traceability auditors demand.

ServiceQuestion it answersMechanism
CloudTrailWho called which API, when, from where?Immutable API audit log across all regions
ConfigIs this resource configured compliantly over time?Config snapshots + rules, drift + history
GuardDutyIs something malicious happening right now?ML threat detection on CloudTrail, VPC Flow, DNS logs
Security HubWhat is my aggregate posture?Aggregates + correlates findings from GuardDuty, Inspector, Macie and CSPM into exposure/threat views; benchmark scoring (CIS, PCI) is Security Hub CSPM
  • GuardDuty — agentless; flags reconnaissance (port scans), instance compromise (crypto-mining, malware C2), account compromise (unusual logins, credential exfil), and S3 data-exfiltration patterns.
  • Config — catches drift: e.g. an S3 bucket that became public or a security group opened to 0.0.0.0/0, with auto-remediation hooks.
  • AWS Artifact — self-service portal for AWS's own SOC 2, ISO, PCI DSS reports and to sign the HIPAA BAA — evidence for their half of the shared model.
MODULE 17

AWS Integration & Messaging

Decouple services: SQS queues, SNS pub/sub, EventBridge, Step Functions, and fan-out patterns.

Why Decouple At All

Synchronous request/response couples producer and consumer in latency, availability, and scale: if the downstream is slow or down, the caller blocks or fails. Messaging inserts a durable buffer so the two sides scale and fail independently. The three primitives you must distinguish cold in an interview:

  • Queue (SQS) — point-to-point, one message consumed by exactly one worker in a group. Pull model. Load-leveling.
  • Topic (SNS) — pub/sub, one message pushed to N subscribers. Push model. Fan-out.
  • Event bus (EventBridge) — pub/sub with content-based routing rules and a schema catalog. Push, many targets, rich filtering.

SQS: Standard vs FIFO

SQS is a fully managed pull-based queue. A producer calls SendMessage; a consumer polls ReceiveMessage, does work, then DeleteMessage. Deletion — not receipt — is what removes a message, which is the root of SQS's at-least-once semantics.

PropertyStandardFIFO (.fifo suffix)
ThroughputNearly unlimited300 msg/s (3,000 with batches of 10); high-throughput mode raises this per message-group
OrderingBest-effortStrict order within a MessageGroupId
DeliveryAt-least-once (dupes possible)Exactly-once processing
DedupNone5-minute dedup window by MessageDeduplicationId or content hash
ParallelismUnbounded consumersOne in-flight message per group; use many groups to parallelize

FIFO ordering and parallelism are the same knob: the MessageGroupId. All messages sharing a group are strictly ordered and processed one at a time; different groups run concurrently. Pick the group to match your ordering domain — e.g. userId so a single user's events stay ordered while users scale out.

import boto3
sqs = boto3.client("sqs")

# FIFO send: group preserves order, dedup id suppresses retries within 5 min
sqs.send_message(
    QueueUrl=url,
    MessageBody='{"event":"account.closed","userId":"u-42"}',
    MessageGroupId="u-42",              # ordering domain
    MessageDeduplicationId="close-u42-2026-07-01",  # idempotency key
)

Message Lifecycle: Visibility, Polling, DLQ

When a consumer receives a message it becomes invisible for the visibility-timeout window rather than being deleted. If the consumer finishes and calls DeleteMessage in time, it's gone. If it crashes or is too slow, the timeout expires and the message reappears for redelivery. This is exactly how SQS guarantees at-least-once without losing work — and exactly why duplicate processing happens.

  1. Producer SendMessage → message durably stored across AZs.
  2. Consumer ReceiveMessage → message hidden for the visibility timeout; ReceiveCount increments.
  3. Work succeeds → DeleteMessage removes it. Work fails/timeout → message becomes visible again.
  4. When ReceiveCount > maxReceiveCount, the redrive policy moves it to a Dead-Letter Queue for inspection instead of looping forever.
  • Short polling — returns immediately, may return empty even when messages exist (samples a subset of servers). Default; more empty receives = more cost.
  • Long polling — set WaitTimeSeconds up to 20; waits for a message, cuts empty responses and API cost. Effectively always enable it.
  • DLQ — a separate queue set via redrive policy; alarm on its ApproximateNumberOfMessagesVisible and use redrive-to-source to replay after a fix.

SNS: Pub/Sub and Fan-Out

SNS is push-based pub/sub. Publishers send to a topic; SNS immediately replicates each message to every subscribed endpoint. There is no queue-style storage and no polling (the exception: FIFO topics can archive messages for up to 365 days and replay them) — if a subscriber is down, SNS retries per protocol and then drops (unless the subscriber is a durable target like SQS). Supported subscriber protocols:

CategoryProtocolsTypical use
App-to-App (A2A)SQS, Lambda, HTTP/S, Amazon Data FirehoseFan-out to workers, webhooks, buffering to durable queues
App-to-Person (A2P)Email, Email-JSON, SMS, mobile push (APNS/FCM)Alerts, notifications, OTP/marketing SMS

Message filtering lets each subscription attach a filter policy so a subscriber receives only the subset it cares about — matched against message attributes or (opt-in) the message body. This turns one topic into many logical streams and avoids per-consumer filtering logic.

{
  "eventType": ["order.placed", "order.cancelled"],
  "region":    ["us-east-1"],
  "amount":    [{ "numeric": [">=", 1000] }]
}

SNS also offers FIFO topics (ordered, deduplicated) which fan out only to SQS queues (FIFO queues for end-to-end ordering, standard queues for lower cost with best-effort ordering) and reach Lambda via those queues; HTTP/S, email and SMS subscribers are not allowed.

The SNS + SQS Fan-Out Pattern

The canonical decoupling pattern: publish once to an SNS topic; subscribe several SQS queues, one per consumer team. SNS gives parallel delivery and filtering; SQS gives each consumer its own durable buffer, retries, and DLQ. Consumers can be added/removed without the publisher knowing. A raw HTTP or Lambda subscriber that's temporarily down loses messages; an SQS subscriber does not — the message waits in the queue.

                         filter: type=image.uploaded
   Producer                         ↓
  (upload svc) --Publish--> [ SNS topic ] --fan-out--> [ SQS: thumbnails ] --> Lambda (resize)
                                 |  |  |
                                 |  |  +-------------> [ SQS: logging   ] --> Worker (audit)
                                 |  +----------------> [ SQS: analytics ] --> Worker (index)
                                 +-------------------> Lambda (virus scan, direct sub)

  Each SQS queue: own visibility timeout + maxReceiveCount --> own DLQ.
  • Buffering — a traffic spike (flash sale) floods the topic; each queue absorbs it so slow consumers never drop work.
  • Isolation — the analytics consumer failing does not back-pressure thumbnail generation; separate queues, separate DLQs.
  • Access policy — the SQS queue policy must allow sns.amazonaws.com to SendMessage, scoped by the topic ARN — a classic setup gotcha.

EventBridge vs SNS

EventBridge is a serverless event bus built for event-driven routing. Like SNS it's push pub/sub, but it adds first-class routing rules that match on the full event payload, a schema registry, event archive/replay, and native ingestion from ~130 AWS services and SaaS partners (Datadog, Stripe, Shopify, Zendesk). Choose SNS when you need cheap, low-latency, high-throughput fan-out; choose EventBridge when routing logic and integrations dominate.

DimensionSNSEventBridge
ModelTopic fan-outBus + rules (content routing)
FilteringAttributes / body matchRich pattern match on any field of the event JSON
TargetsSQS, Lambda, HTTP, SMS, email, Firehose20+ AWS targets (Lambda, SFN, SQS, Kinesis, API destinations...)
SourcesYour publishersYour apps + AWS services + SaaS partners; scheduled events
ExtrasNone (no storage)Schema registry, archive & replay, input transformer
Latency / throughputVery low latency, very high fan-outHigher latency (~0.5 s), lower default PutEvents quota
Reach for it whenSimple broadcast, A2P, huge throughputRouting many event types, SaaS/AWS integration, replay
{
  "source": ["com.shop.orders"],
  "detail-type": ["OrderPlaced"],
  "detail": { "amount": [{ "numeric": [">", 500] }], "tier": ["gold"] }
}

Step Functions: Orchestration

SQS/SNS/EventBridge give you choreography — services react to events with no central brain. Step Functions gives you orchestration: a state machine (defined in Amazon States Language, ASL) that explicitly sequences steps, branches, retries, and handles errors, with full execution history for debugging. Use it when a workflow has multi-step business logic, human-visible state, or compensation on failure (saga).

PropertyStandard workflowExpress workflow
Max durationUp to 1 yearUp to 5 minutes
Execution semanticsExactly-onceAt-least-once (async) / at-most-once (sync)
RateLower start rate; long-runningVery high volume (100k+/s)
PricingPer state transitionPer request + duration/memory (cheaper at high volume)
HistoryFull, in-consoleVia CloudWatch Logs only
FitOrder fulfillment, ETL, human approvalHigh-rate event processing, IoT ingest, short APIs
{
  "StartAt": "ChargeCard",
  "States": {
    "ChargeCard": {
      "Type": "Task",
      "Resource": "arn:aws:lambda:...:charge",
      "Retry": [{ "ErrorEquals": ["States.TaskFailed"], "MaxAttempts": 3, "BackoffRate": 2 }],
      "Catch": [{ "ErrorEquals": ["States.ALL"], "Next": "RefundAndFail" }],
      "Next": "ShipOrder"
    },
    "ShipOrder":     { "Type": "Task", "Resource": "arn:...:ship", "End": true },
    "RefundAndFail": { "Type": "Task", "Resource": "arn:...:refund", "Next": "Fail" },
    "Fail":          { "Type": "Fail" }
  }
}

Choosing the Primitive: SQS vs SNS vs EventBridge vs Kinesis

The single most common design question. Decide by consumption model (pull vs push, one vs many), whether you need ordering/replay, and retention.

ServiceModelOrderingRetention / replayUse when
SQSQueue, pull, 1 consumer per msgFIFO within group (else best-effort)Up to 14 days, no replay after deleteLoad-leveling, async work offload, buffering spikes
SNSTopic, push, N subscribersFIFO topics onlyNone (fire-and-forget)Fan-out, A2P alerts, broadcast to many endpoints
EventBridgeBus, push, rule-routedNo ordering guaranteeArchive + replay of eventsEvent routing on payload, AWS/SaaS integration, schedules
Kinesis Data StreamsLog, pull, many consumers re-readStrict order per shard1 day default, up to 365 days; full replayOrdered high-volume streaming, analytics, multiple independent readers
  • SQS vs Kinesis — both buffer, but SQS deletes on consume (competing consumers) while Kinesis keeps an ordered, replayable log that many consumer groups read independently by offset.
  • SNS vs EventBridge — both broadcast; SNS is faster/higher-throughput fan-out, EventBridge trades latency for content routing, SaaS sources, and replay.
  • Combine them — EventBridge/SNS at the front for routing/fan-out, SQS behind each consumer for durability and retries.
MODULE 18

AWS Observability & Governance

See and control your account: CloudWatch metrics/logs/alarms, CloudTrail, X-Ray, Config, Organizations.

The Three Pillars, Mapped to AWS

Observability is the ability to explain a system's internal state from its external outputs. Monitoring tells you when something broke; observability tells you why. Three signal types carry that weight, and each maps to a first-party AWS service.

  • Metrics — aggregated time-series numbers (CPU, p99 latency, error rate). Cheap to store, fast to alert on, low cardinality. Answers "what is happening?" → CloudWatch Metrics.
  • Logs — discrete, high-detail event records. Answers "what exactly happened at 14:32:01?" → CloudWatch Logs.
  • Traces — a single request's path across many services, with per-hop timing. Answers "where did the time go?" → X-Ray (or OpenTelemetry via ADOT).
PillarShapeStrengthAWS service
MetricsNumeric, aggregatedAlerting, dashboards, trendsCloudWatch Metrics
LogsStructured/text eventsRoot-cause debuggingCloudWatch Logs + Insights
TracesCorrelated request spansCross-service latency, dependenciesX-Ray / ADOT

CloudWatch Metrics: Namespaces, Dimensions, Resolution

A CloudWatch metric is uniquely identified by a namespace plus its dimension set. AWS services publish standard metrics for free; you publish custom ones via PutMetricData or the CloudWatch agent.

  • Namespace — the container, e.g. AWS/EC2, AWS/ApiGateway, or your own Custom/OrderService.
  • Dimensions — up to 30 name-value pairs that scope a metric, e.g. InstanceId=i-0abc. Every distinct dimension combination is a separate billable metric.
  • Resolution — standard (60s) is free for AWS metrics; high-resolution (1s) custom metrics cost more and enable sub-minute alarms.
  • Statistic — Average / Sum / Min / Max / SampleCount / percentiles (p90, p99) are computed at query and alarm time.

Retention is automatic and tiered — data is rolled up to coarser granularity as it ages, so a 1-second point does not survive as a 1-second point for a year:

Period of data pointRetained for
< 60s (high-res)3 hours
60s (1 minute)15 days
300s (5 minute)63 days
3600s (1 hour)455 days (~15 months)
aws cloudwatch put-metric-data \
  --namespace "Custom/OrderService" \
  --metric-name OrdersProcessed \
  --unit Count --value 1 \
  --dimensions Env=prod,Region=us-east-1

CloudWatch Logs, Insights & EMF

Logs are organized as log groups (one per app/function, e.g. /aws/lambda/checkout) containing log streams (one per source instance/execution). Retention is set per group — from 1 day to Never — and defaults to Never, which quietly accrues cost.

  • Metric filters — pattern-match log events and emit a metric (e.g. count of "ERROR 500"), turning text into an alarmable number without a query.
  • Subscription filters — stream events in near-real-time to Lambda, Firehose (→ S3), or OpenSearch for archival or search.
  • Logs Insights — an interactive query language billed per GB scanned; great for ad-hoc forensics on a bounded time window.
  • EMF (Embedded Metric Format) — write a specially-shaped JSON log and CloudWatch auto-extracts metrics from it, so a single structured log line yields both a searchable event and a metric with no separate PutMetricData call.
fields @timestamp, @message
| filter @type = "REPORT"
| stats avg(@duration) as avg,
        pct(@duration, 50) as p50,
        pct(@duration, 95) as p95,
        pct(@duration, 99) as p99
  by bin(5m)
| sort p99 desc

EMF is the idiomatic way to emit custom app metrics from Lambda — the extraction happens asynchronously off the log, so it adds no latency to the request path:

{
  "_aws": {
    "Timestamp": 1751328000000,
    "CloudWatchMetrics": [{
      "Namespace": "Custom/OrderService",
      "Dimensions": [["Env"]],
      "Metrics": [{ "Name": "Latency", "Unit": "Milliseconds" }]
    }]
  },
  "Env": "prod",
  "Latency": 142,
  "orderId": "o-9931"
}

Alarms, Composite Alarms & Dashboards

An alarm watches one metric (or a metric-math expression) against a threshold over N evaluation periods and transitions between OK, ALARM, and INSUFFICIENT_DATA, firing actions on transition.

  • Actions — notify an SNS topic, trigger an Auto Scaling policy, or perform an EC2 action (stop/terminate/reboot/recover). Set both alarm_actions and ok_actions so recovery is announced too.
  • Composite alarms — combine child alarms with boolean logic (AND/OR/NOT) to page only on genuine incidents and suppress noise.
  • Alert on symptoms, not causes — "error rate > 1% for 5 min" is actionable; "CPU at 80%" often is not.
resource "aws_cloudwatch_composite_alarm" "app_health" {
  alarm_name    = "app-health"
  alarm_rule    = "ALARM(cpu_high) OR ALARM(error_rate)"
  alarm_actions = [aws_sns_topic.critical.arn]
}

Dashboards render metric widgets, metric-math (e.g. errors/requests*100), and even live Logs Insights query results in one pane. Define them as JSON in IaC so they version alongside the app.

CloudTrail: The Audit Trail

CloudTrail records the AWS API calls made in your account — who did what, when, and from which IP. It is your control-plane audit log, not a performance monitor.

Event typePlaneExamplesLogged by default?
Management eventsControlRunInstances, CreateBucket, CreateUserYes (free, one copy)
Data eventsDatas3:GetObject, lambda:InvokeNo — high volume, extra cost
  • Event History — free, searchable, immutable 90-day view of management events in the console; no trail required.
  • Trails — persist events to S3 (and optionally CloudWatch Logs). Make them multi-region so a bad actor can't hide activity in an unwatched region.
  • Organization trail — a single trail defined in the management account that captures every member account, so members can't disable their own auditing.
  • Log file integrity validation — SHA-256 hashes plus digitally-signed digest files let you prove logs weren't tampered with — key for compliance.

X-Ray: Distributed Tracing

X-Ray stitches per-service timing into an end-to-end picture of one request, and aggregates traces into a service map — a live topology graph annotated with latency and error/fault rates per node and edge.

  • Trace — the full request journey, keyed by a trace ID propagated in headers.
  • Segment — the work done by one service; subsegments capture its downstream calls (DynamoDB, an external API, S3).
  • Annotations — indexed key-value pairs you can filter traces by (e.g. order_id). Metadata — non-indexed detail for debugging only.
  • Sampling — default reservoir of 1 req/sec guaranteed plus 5% of the rest; custom rules can trace 100% of 5xx and 1% of /health.
from aws_xray_sdk.core import xray_recorder, patch_all
patch_all()  # auto-traces boto3, requests, etc.

@xray_recorder.capture('process_order')
def process_order(order_id):
    xray_recorder.put_annotation('order_id', order_id)  # searchable
    return table.get_item(Key={'id': order_id})['Item']

Enable it declaratively — Lambda via tracing_config { mode = "Active" }, API Gateway via xray_tracing_enabled = true — so the trace already spans the edge before your code runs.

AWS Config: Compliance & Drift

Where CloudTrail records API calls, AWS Config records resource state over time and continuously evaluates it against rules. It answers "is this resource compliant, and how did its configuration change?"

  • Configuration items — point-in-time snapshots of a resource's settings and relationships; the timeline shows every change.
  • Config rules — managed or custom (Lambda-backed) checks, e.g. "no S3 bucket is public", "EBS volumes are encrypted", flagging resources COMPLIANT / NON_COMPLIANT.
  • Remediation — attach an SSM Automation document to auto-fix violations (e.g. re-enable bucket block-public-access).
  • Conformance packs — bundles of rules mapped to frameworks (PCI, CIS, HIPAA) deployable org-wide.
QuestionService
Who made this API call, when, from where?CloudTrail
What is this resource's config, and is it compliant?AWS Config
Is the system healthy / fast right now?CloudWatch
Where did this request's latency go?X-Ray

Organizations, SCPs & Cost Guardrails

At scale you don't run one account — you run many, grouped under AWS Organizations. This gives consolidated billing, org-wide CloudTrail/Config, and, critically, Service Control Policies (SCPs): guardrails that cap the maximum permissions any principal in a member account can have — even the root user.

  • SCPs are a permission ceiling, not a grant — the effective permission is the intersection of the SCP and the account's IAM policies. An SCP can deny, never allow.
  • Organizational Units (OUs) — group accounts (prod, dev, sandbox); attach SCPs at the OU for inherited guardrails.
  • Common guardrails — deny disabling CloudTrail/Config, deny leaving the org, restrict to approved regions, block public S3.
  • Cost/billing alarms — the EstimatedCharges metric (namespace AWS/Billing, us-east-1 only) plus AWS Budgets alert before a runaway spend becomes a surprise invoice.
{
  "Version": "2012-10-17",
  "Statement": [{
    "Sid": "DenyStopCloudTrail",
    "Effect": "Deny",
    "Action": ["cloudtrail:StopLogging", "cloudtrail:DeleteTrail"],
    "Resource": "*"
  }]
}
aws cloudwatch put-metric-alarm \
  --alarm-name billing-over-500 \
  --namespace AWS/Billing --metric-name EstimatedCharges \
  --dimensions Name=Currency,Value=USD \
  --statistic Maximum --period 21600 \
  --threshold 500 --comparison-operator GreaterThanThreshold \
  --evaluation-periods 1 --region us-east-1 \
  --alarm-actions arn:aws:sns:us-east-1:111122223333:billing-alerts
MODULE 19

AWS Cost Optimization

FinOps on AWS: pricing models, Savings Plans vs RIs vs Spot, rightsizing, and tagging.

The Pricing Levers

The cloud is only cheaper than on-prem if you manage it. Every EC2 hour can be purchased under one of five models, trading commitment for discount. The mental model: reserve your steady-state baseline, burst the peak on On-Demand, and run anything interruptible on Spot.

ModelCommitmentFlexibilityMax discountBest for
On-DemandNoneMaximum0%Spiky / unpredictable, short-term
Compute Savings Plan$/hr, 1 or 3 yrHigh — any family, region, OS, tenancy~66%Mixed, evolving fleets (EC2 + Fargate; Lambda covered but only up to ~17%)
EC2 Instance Savings Plan$/hr, family + regionMedium — size flexible within family72%Stable EC2 fleets
Reserved InstanceInstance type + AZ, 1 or 3 yrLow (Convertible RI can swap)72%Redshift, and RDS/ElastiCache where Database Savings Plans do not fit
SpotNone — 2-min reclaim noticeLowest90%Batch, CI, stateless, ML training w/ checkpoints
Dedicated HostPer-hostVariesBYOL valueLicensing compliance (socket-bound)

Savings Plans vs Reserved Instances

Savings Plans replaced RIs as the default commitment vehicle. Instead of reserving a specific instance, you commit to a dollars-per-hour of compute spend; AWS auto-applies the discount cheapest-first across matching usage. Database Savings Plans (1-year, no upfront, up to 35%) now cover Aurora/RDS, DynamoDB, ElastiCache for Valkey and other database services. RIs still matter for what neither Savings Plans family covers — e.g. Redshift reserved nodes.

  • Compute SP — one commitment covers EC2, Fargate, and Lambda (Lambda discount is only up to ~17%, not the ~66% EC2 headline); swap families/regions freely. Start here.
  • EC2 Instance SP — locks family + region for ~6% more discount; use only for large, stable fleets.
  • Database Savings Plans — 1-year, no-upfront, up to 35% off across Aurora/RDS, DynamoDB, ElastiCache for Valkey, DocumentDB and more, regardless of engine, size or Region. Not combinable with RDS RIs or DynamoDB reserved capacity on the same workload.
  • Reserved Instances — still the commit path for Redshift and database usage Database Savings Plans do not list; Convertible RIs can be exchanged.
  • Baseline rule — commit to ~70% of steady-state usage, never 100% of peak. Reserving over-provisioned resources locks in waste.
           Usage over time
  ┌───────────────────────────────────
  │        ╱╲      ╱╲   ╱╲
  │   ╱╲  ╱  ╲    ╱  ╲ ╱  ╲   <- On-Demand / Spot (the peaks)
  │  ╱  ╲╱    ╲  ╱    V    ╲
  │ ─────────────────────────  <- Savings Plan baseline (commit here)
  └────────────────────────────────────

Rightsizing with Compute Optimizer

Most teams over-provision by 2-3x. Rightsizing means matching instance type to observed utilization — and it comes before reserving, so you commit to the smaller footprint. Eliminate, then rightsize, then reserve.

  1. Collect 2+ weeks of metrics — CPU, memory (needs CloudWatch agent), network, disk I/O.
  2. Feed AWS Compute Optimizer (free) — it flags over/under-provisioned EC2, EBS, Lambda, ECS-on-Fargate and Auto Scaling groups with ranked recommendations.
  3. Change one tier at a time, verify p99 latency holds, then repeat.
  4. Prefer Graviton (m7g/c7g/r7g) and burstable T-family for low-average, spiky CPU.
# Pull Compute Optimizer EC2 recommendations
aws compute-optimizer get-ec2-instance-recommendations \
  --query 'instanceRecommendations[?finding==`OVER_PROVISIONED`].
           {Id:instanceArn,Current:currentInstanceType,
            Rec:recommendationOptions[0].instanceType}' \
  --output table

Storage Cost: Tiers, gp3, and Lifecycle

Storage waste is quiet: orphaned volumes, forgotten snapshots, and hot data sitting in Standard forever. Two moves dominate — migrate EBS gp2 to gp3, and let S3 lifecycle rules age data down the cost ladder automatically.

S3 class$/GB-mo (us-east-1)Access patternRetrieval
Standard$0.023FrequentInstant
Intelligent-Tiering$0.023 + monitor feeUnknown / mixedInstant, auto-tiers, no retrieval fee
Standard-IA$0.0125Monthly (30-day min)Instant
Glacier Instant$0.004QuarterlyMilliseconds
Glacier Flexible$0.0036YearlyMinutes-hours
Glacier Deep Archive$0.00099Compliance / cold12-48 hours
  • gp3 over gp2 — gp3 is ~20% cheaper per GB and decouples IOPS/throughput from size (3,000 IOPS baseline free). Migrate in place, no downtime.
  • Delete unattached — available-state EBS volumes, unassociated Elastic IPs ($3.65/mo each), and snapshots older than 90 days bleed money silently.
  • Abort multipart uploads — add a lifecycle rule to purge incomplete uploads after 7 days; they accumulate invisibly.
{
  "Rules": [{
    "ID": "age-down-logs",
    "Status": "Enabled",
    "Transitions": [
      { "Days": 30,  "StorageClass": "STANDARD_IA" },
      { "Days": 90,  "StorageClass": "GLACIER_IR" },
      { "Days": 365, "StorageClass": "DEEP_ARCHIVE" }
    ],
    "Expiration": { "Days": 2555 },
    "AbortIncompleteMultipartUpload": { "DaysAfterInitiation": 7 }
  }]
}

Data Transfer: The Silent Bill

Data transfer is the #1 surprise line item. Compute and storage are visible; the bytes moving between them are not. Three culprits dominate: internet egress, NAT Gateway processing, and cross-AZ chatter.

PathCostNote
Internet -> AWS (ingress)FreeUploads are free
AWS -> Internet (egress)$0.09/GB (first 10TB)Tiers down at scale
Same AZFreeCo-locate hot paths
Cross-AZ (same VPC)$0.01/GB each way ($0.02 round-trip)App-in-AZ-a to DB-in-AZ-b
Cross-Region$0.02/GBReplication, DR
NAT Gateway processing$0.045/GB + hourlyOn top of egress
S3/DynamoDB Gateway EndpointFreeReplaces NAT for these
CloudFront -> user$0.085/GB (first 10TB)AWS origin -> edge is free; < direct egress

The fix pattern: route AWS-service traffic through VPC endpoints instead of NAT, keep chatty compute-and-storage pairs in the same AZ, front public content with CloudFront, and compress everything (gzip/brotli/zstd cut 60-80% of bytes).

The Serverless Cost Model

Serverless flips the model from paying-for-provisioned to paying-per-request. That is great at low/spiky volume and can bite at massive scale, where a right-sized always-on instance is cheaper. Know where the crossover is.

  • Lambda — billed on GB-seconds (memory x duration) + $0.20 per 1M requests. Memory also scales CPU, so more memory can be faster and cheaper — tune with Lambda Power Tuning. Use arm64 (-20%). At 1B+ invocations/mo, requests alone are ~$200 before compute.
  • Fargate — pay per vCPU-second + GB-second; no idle node cost. Most tasks over-allocate 2-3x — watch Container Insights. Fargate Spot saves up to 70%; Compute SP applies here too.
  • Aurora Serverless v2 — scales in 0.5-ACU steps (~$0.12/ACU-hr); great for variable DB load, no paying for idle peak capacity. Min 0 ACU enables auto-pause (idle 5 min–24 h, ~15 s resume); at min 0.5+ compute keeps billing.
  • Watch the exhaust — CloudWatch Logs ingestion is $0.50/GB; verbose logging with no retention policy grows unbounded.
# Lambda cost intuition (approx, us-east-1)
GB_SECOND = 0.0000166667          # per GB-second (x86)
REQUEST   = 0.20 / 1_000_000      # per request
def monthly(invocations, ms, mb):
    gb = mb / 1024
    secs = ms / 1000
    return invocations * (gb * secs * GB_SECOND + REQUEST)
# 50M calls, 200ms, 512MB  -> ~$93/mo   (arm64 ~ -20%)

Cost Visibility & Tagging

You cannot optimize what you cannot attribute. Visibility is a stack: raw data (CUR), interactive analysis (Cost Explorer), guardrails (Budgets), and ML tripwires (Anomaly Detection). All of it is powered by cost allocation tags — untagged spend lands in an unattributable bucket.

ToolPurposeCadence
Cost ExplorerTrends, forecast, group-by dimension/tagWeekly
AWS BudgetsThreshold alerts (80/100/120%), actual + forecastAlways-on
Cost Anomaly DetectionML alerts on unusual spend, per service/tagDaily
CUR + AthenaLine-item chargeback, split shared costsMonthly
Compute Optimizer / Trusted AdvisorRightsizing + idle-resource findingsQuarterly

Enforce tags at creation with an Organizations SCP so untagged resources cannot launch, then activate the keys as cost allocation tags in the billing console.

{
  "Sid": "RequireCostTags",
  "Effect": "Deny",
  "Action": ["ec2:RunInstances","rds:CreateDBInstance","ecs:CreateService"],
  "Resource": "*",
  "Condition": { "Null": {
    "aws:RequestTag/Team": "true",
    "aws:RequestTag/Environment": "true",
    "aws:RequestTag/CostCenter": "true"
  }}
}
# Minimum tag taxonomy for allocation + chargeback
Team:        platform-eng      # who owns it
Environment: production        # prod | staging | dev
Project:     recommendations   # product / service
CostCenter:  CC-1234           # finance billing code
Owner:       jane@corp.com     # accountable human

The FinOps Loop

FinOps is the operating model that keeps costs low after the one-time cleanup. It is a continuous three-phase loop owned jointly by engineering and finance — not a spreadsheet audited once a year.

  1. Inform — visibility, allocation, showback/chargeback. Every team sees its own bill; shared costs (NAT, Transit Gateway) split proportionally.
  2. Optimize — eliminate waste, rightsize, commit (Savings Plans/RIs), adopt Spot and new instance families (Graviton, Inferentia).
  3. Operate — automate: budget alerts to Slack, anomaly detection, scheduled stop/start for non-prod, Config rules for untagged resources, quarterly commitment reviews.

The ordering discipline that makes it work: eliminate, then rightsize, then reserve. Reserving before rightsizing bakes in over-provisioning for the whole commitment term.

MODULE 20

AWS Reliability: DR & HA

Design for failure: Multi-AZ vs multi-region, RTO/RPO, and the four DR strategies.

HA vs DR: Two Different Problems

Interviewers punish candidates who conflate these. High Availability keeps you running through routine failures inside one region; Disaster Recovery brings you back after a region-scale catastrophe. You need both — they solve different failure classes at different cost points.

  • High Availability (HA) — minimize downtime during normal operations. Scope is intra-region (multi-AZ). Failover is automatic and continuous. Examples: RDS Multi-AZ, ALB across AZs, Auto Scaling. Handles instance, component, and AZ failures.
  • Disaster Recovery (DR) — resume operations after a major disaster. Scope is cross-region (or cross-cloud). Failover often requires a human decision or an explicit runbook trigger. Examples: S3 Cross-Region Replication, Route 53 failover, Aurora Global Database. Handles full-region outages and widespread events.
DimensionHigh AvailabilityDisaster Recovery
Failure handledInstance / AZ / componentEntire region, natural disaster
Fault domainAvailability ZoneRegion
ReplicationSynchronousAsynchronous
FailoverAutomatic (seconds)Manual / triggered (minutes)
Cost~2x the tier2%–120% of prod, by strategy

Fault Domains: AZ vs Region

Every AWS reliability decision is really a bet on a fault domain. An Availability Zone is one or more discrete datacenters with independent power, cooling, and networking, linked to sibling AZs by low-latency (<1–2ms) private fiber. A Region is a fully isolated geographic boundary — separate control planes, separate blast radius.

Multi-AZ (intra-region)Multi-Region
Replication modeSynchronous (zero-lag)Asynchronous (lag > 0)
Inter-node latencySub-millisecond to ~2msTens to hundreds of ms
Achievable RPOZero (no data loss)Seconds to minutes
Data transfer costCheap / often free intra-AZCross-region egress charged
Operational complexityLow — one control planeHigh — DNS, IAM, quotas, drift per region
Protects againstDatacenter lossRegion loss

The uptime math sets the stakes: 99.9% is 8.76 hours of downtime/year, 99.99% is 52.6 minutes, and 99.999% ("five nines") is just 5.26 minutes. Each additional nine costs disproportionately more — which is why you match the fault domain to the requirement rather than buying max redundancy everywhere.

RTO vs RPO

These two numbers drive every architecture choice. Define them first; the design follows. They sit on opposite sides of the disaster on the timeline.

  • RPO (Recovery Point Objective) — how much data you can afford to lose, measured backward from the disaster. "RPO = 1 minute" means at most one minute of writes vanish. It maps directly onto your replication lag.
  • RTO (Recovery Time Objective) — how long you can be down, measured forward from the disaster. "RTO = 15 min" means service must be restored within 15 minutes.
      <-------- RPO -------->|<--------- RTO --------->
                            |
    Last durable       DISASTER              Service
    replicated write   strikes               restored
    ------o------------------X------------------o--------> time
          |                                     |
    data you may lose                    downtime window
WorkloadRPO targetRTO target
Banking / payments0 (no loss)< 15 min
E-commerce~1 hour~1 hour
Dev / test24 hours24 hours
Cold archive1 week1 week

The Four DR Strategies

AWS frames DR as a spectrum from cheap-and-slow to expensive-and-instant. The choice is an economic one: pay continuously for standby capacity, or pay in recovery time when disaster hits.

StrategyWhat runs in DR regionRTORPOCost (% of prod)Complexity
Backup & RestoreNothing — only backups in S3Hours to daysHours2–7%Low
Pilot LightDB replica + core infra, app off10s of minutesMinutes7–20%Medium
Warm StandbyScaled-down full stack, runningMinutesSeconds to minutes30–60%Medium-High
Multi-Site Active/ActiveFull stack serving live trafficNear-zeroNear-zero80–120%Very High
  1. Backup & Restore — snapshots and objects replicated to another region; you rebuild everything on disaster. Cheapest, slowest. Good for dev/test and non-critical archives.
  2. Pilot Light — a minimal always-on core (chiefly a replicating database) sits idle; on failover you scale up app servers around it. The "spark" is always lit.
  3. Warm Standby — a fully functional but scaled-down copy runs continuously and can take real traffic immediately, then scales out. Failover is just a scale-up plus DNS flip.
  4. Multi-Site Active/Active — both regions serve production concurrently behind a global router. There is no "failover" — you just stop sending traffic to the dead region.

Data Replication: The RPO Engine

Your DR strategy is only as good as its data layer. These are the managed replication primitives, ordered roughly by achievable RPO.

MechanismModeTypical lag / RPOFailover model
RDS Multi-AZSynchronous, same region0 (HA only)Automatic, 1–2 min, same endpoint
RDS Multi-AZ ClusterSemi-sync, 1 writer + 2 readable standbys0Automatic, ~35s
RDS cross-region read replicaAsync, cross regionSeconds to minutesManual promote to standalone
Aurora (in-region)6 copies across 3 AZs0Automatic, < 30s
Aurora Global DatabaseStorage-level, cross region< 1s (typ. 100–200ms)Switchover (planned, RPO 0, typically < 30 s on current engine versions); managed failover (unplanned, RPO of seconds, RTO of minutes)
DynamoDB Global TablesAsync, active-active multi-region< 1sNone needed — write anywhere
S3 Cross-Region ReplicationAsync object replicationMinutesRepoint reads to DR bucket

Aurora Global Database hits sub-second RPO because it does not ship the binlog — dedicated storage-layer infrastructure streams changes in parallel to the secondary region's own 6-copy volume, decoupled from the database engine's CPU. DynamoDB Global Tables goes further with active-active writes and last-writer-wins conflict resolution, so any region accepts reads and writes with no promotion step.

import boto3

def promote_rds_replica(db_instance_id):
    """Pilot-light / warm-standby failover: promote a cross-region
    read replica to a standalone writable primary."""
    rds = boto3.client('rds')
    rds.promote_read_replica(
        DBInstanceIdentifier=db_instance_id,
        BackupRetentionPeriod=7,
    )
    rds.get_waiter('db_instance_available').wait(
        DBInstanceIdentifier=db_instance_id
    )

def switchover_aurora_global(global_id, target_cluster_arn):
    """Planned switchover (formerly "managed planned failover"):
    secondary is synced first, so RPO = 0."""
    rds = boto3.client('rds')
    rds.switchover_global_cluster(
        GlobalClusterIdentifier=global_id,
        TargetDbClusterIdentifier=target_cluster_arn,
    )

def failover_aurora_global(global_id, target_cluster_arn):
    """Unplanned regional outage: promote a secondary now.
    May lose seconds of writes that had not replicated (RPO > 0)."""
    rds = boto3.client('rds')
    rds.failover_global_cluster(
        GlobalClusterIdentifier=global_id,
        TargetDbClusterIdentifier=target_cluster_arn,
        AllowDataLoss=True,
    )

Health Checks & Route 53 Failover Routing

DNS is the classic cross-region failover lever. Route 53 health checks probe your primary; when they fail, the failover routing policy answers queries with the secondary's record instead. The pattern: one PRIMARY record bound to a health check, one SECONDARY record as the backstop.

resource "aws_route53_health_check" "primary" {
  fqdn              = "primary.example.com"
  port              = 443
  type              = "HTTPS"
  resource_path     = "/health"   # app-level, not just TCP
  failure_threshold = 3
  request_interval  = 10
}

resource "aws_route53_record" "failover_primary" {
  zone_id        = aws_route53_zone.main.zone_id
  name           = "api.example.com"
  type           = "A"
  set_identifier = "primary"

  failover_routing_policy { type = "PRIMARY" }

  alias {
    name                   = module.primary.alb_dns
    zone_id                = module.primary.alb_zone_id
    evaluate_target_health = true
  }
  health_check_id = aws_route53_health_check.primary.id
}

resource "aws_route53_record" "failover_secondary" {
  zone_id        = aws_route53_zone.main.zone_id
  name           = "api.example.com"
  type           = "A"
  set_identifier = "secondary"

  failover_routing_policy { type = "SECONDARY" }

  alias {
    name                   = module.dr.alb_dns
    zone_id                = module.dr.alb_zone_id
    evaluate_target_health = true
  }
}
  • Health checks must be application-level — probe a /health path that touches the DB, not a bare TCP port. A green TCP check on a broken app is a false negative you'll only discover mid-incident.
  • AWS Global Accelerator is the lower-latency alternative for active-active — anycast IPs shift traffic away from an unhealthy endpoint group in seconds, with no DNS caching in the path.

Backup: AWS Backup & Snapshots

Backups are the floor of every DR strategy and the whole of Backup & Restore. AWS Backup centralizes policy across RDS, EBS, DynamoDB, EFS, and more — a single plan with lifecycle transitions and cross-region copy.

resource "aws_backup_plan" "daily" {
  name = "daily-backup-plan"

  rule {
    rule_name         = "daily-backup"
    target_vault_name = aws_backup_vault.main.name
    schedule          = "cron(0 5 ? * * *)"   # 05:00 UTC daily

    lifecycle {
      cold_storage_after = 30    # tier to cold storage
      delete_after       = 365   # retain one year
    }

    copy_action {                # cross-region DR copy
      destination_vault_arn = aws_backup_vault.dr_region.arn
      lifecycle { delete_after = 90 }
    }
  }
}
  • 3-2-1 rule — 3 copies, on 2 media types, with 1 offsite (here, the cross-region vault copy).
  • Point-in-time recovery (PITR) — enable it for RDS/DynamoDB to recover to any second, not just to the last snapshot.
  • Immutable / vault-locked backups — WORM protection so ransomware or a rogue credential cannot delete your recovery point.

Chaos Engineering & Game Days

DR that is never exercised decays silently as infrastructure drifts from runbooks. AWS Fault Injection Simulator (FIS) turns "we think it fails over" into measured evidence, with stop conditions to cap the blast radius.

  • FIS experiments — terminate EC2 in a target AZ, inject network latency, fail a percentage of API calls, drain ECS tasks, throttle DynamoDB, or sever AZ connectivity.
  • Stop conditions — wire the experiment to a CloudWatch alarm (e.g. error-rate) so it auto-aborts before it hurts real users.
  • Game days — scheduled, announced drills that run an actual region failover end-to-end, with stakeholders present, measuring the RTO/RPO you truly achieve versus the target.
resource "aws_fis_experiment_template" "az_failure" {
  description = "Simulate AZ failure in us-east-1a"
  role_arn    = aws_iam_role.fis.arn

  action {
    name      = "terminate-instances"
    action_id = "aws:ec2:terminate-instances"
    target { key = "Instances", value = "az-instances" }
  }

  target {
    name           = "az-instances"
    resource_type  = "aws:ec2:instance"
    selection_mode = "ALL"
    resource_tag { key = "Environment", value = "production" }
    filter {
      path   = "Placement.AvailabilityZone"
      values = ["us-east-1a"]
    }
  }

  stop_condition {
    source = "aws:cloudwatch:alarm"
    value  = aws_cloudwatch_metric_alarm.error_rate.arn
  }
}
MODULE 21

AWS AI/GPU Infrastructure

GPU instances, distributed training/inference, vector databases, and AI platform services.

GPU & Accelerator Instance Families

Neural nets are matrix multiplies, so throughput scales with parallel FLOPs and memory bandwidth (HBM), not clock speed. On AWS the accelerator family is chosen by job type (train vs infer), model size (drives HBM needed), and ecosystem lock-in (CUDA vs AWS Neuron). P/G run NVIDIA GPUs with full CUDA; Trn/Inf run AWS silicon compiled through the Neuron SDK.

  • P5 (8x H100, 640 GB) — frontier LLM training, multi-node FSDP; 3,200 Gbps EFA, NVLink for tensor parallelism.
  • P4d/P4de (8x A100, 320/640 GB) — production training + large-model inference; 400 Gbps EFA.
  • G5 (A10G 24 GB) / G6 (L4 24 GB) / G6e (L40S 48 GB) — inference, fine-tuning, small training. Balanced $/perf.
  • G4dn (T4 16 GB) — cheapest NVIDIA GPU; prototyping, quantized inference, video.
  • Inf2 (Inferentia2) — inference-only ASIC, up to 4x better $/throughput on supported transformers/CNNs.
  • Trn1 (Trainium, 512 GB HBM) — training ASIC, ~40-50% cheaper than equivalent NVIDIA when the model compiles.
InstanceAcceleratorAccel MemNetworkOn-Demand $/hrSweet spot
g4dn.xlarge1x T416 GB25 Gbps~$0.53Cheap inference/proto
g5.xlarge1x A10G24 GB10 Gbps~$1.01Real-time inference, fine-tune
inf2.xlarge1x Inferentia232 GB15 Gbps~$0.76Cost-optimized inference
trn1.32xlarge16x Trainium512 GB800 Gbps~$21.50Cost-optimized training
p4d.24xlarge8x A100320 GB400 Gbps~$32.77Production LLM training
p5.48xlarge8x H100640 GB3,200 Gbps~$98.32Frontier multi-node training

When is a GPU even warranted? Classical ML (XGBoost, random forests, scikit-learn) and single-sample low-QPS inference often run cheaper on CPU/Graviton. Reach for a GPU only when the workload is a large, batched matrix multiply.

import torch
if torch.cuda.is_available():
    d = torch.cuda.current_device()
    print(torch.cuda.get_device_name(d))          # NVIDIA A100-SXM4-40GB
    props = torch.cuda.get_device_properties(d)
    print(f"{props.total_memory/1e9:.0f} GB HBM")  # 40 GB

Distributed Training

Once one GPU is saturated, you scale out. The parallelism strategy depends on whether the model fits in a single GPU's HBM.

StrategyWhat is splitUse whenComm pattern
Data parallel (DDP)The batch; each GPU holds a full model copyModel fits in 1 GPUAllReduce gradients (NCCL)
Tensor parallelA single layer's matmul across GPUsLayer too big; needs NVLinkPer-layer, very chatty
Pipeline parallelContiguous layer blocks per GPUModel > 1 GPU; has bubble idleActivations between stages
FSDP / ZeRO-3Params + grads + optimizer sharded 1/NLarge models, avoid DP memory wasteAll-gather layer on demand

Multi-node scaling lives or dies on the network. EFA (Elastic Fabric Adapter) bypasses the OS kernel (RDMA-like): AllReduce across 64 GPUs drops from ~200 ms over TCP to ~5 ms. EFA is available on many instance types (P4d/P5 and other GPU families such as larger G5/G6/G6e sizes, Trn1/Trn2, HPC and big general-purpose sizes; not every size, e.g. not Inf2), so check the supported list. Place the nodes in one AZ in a cluster placement group (same rack/switch) for the lowest latency so NCCL rides the fabric.

# Single instance, 8 GPUs: torchrun --nproc_per_node=8 train.py
import torch.distributed as dist
from torch.nn.parallel import DistributedDataParallel as DDP
dist.init_process_group("nccl")          # NCCL rides EFA between nodes
model = DDP(model.cuda(), device_ids=[local_rank])
# SageMaker hides cluster provisioning + EFA wiring
from sagemaker.pytorch import PyTorch
est = PyTorch(entry_point="train.py", instance_count=4,
              instance_type="ml.p4d.24xlarge",   # 4x8 = 32 A100s
              distribution={"torch_distributed": {"enabled": True}},
              use_spot_instances=True, checkpoint_s3_uri="s3://bkt/ckpt/")
est.fit({"train": "s3://bkt/data/"})

Inference Serving

Inference is latency- and cost-sensitive, and often always-on, so hosting choice matters more than for training. Match the serving mode to the traffic shape.

OptionLatencyCost modelScale-to-zeroBest for
SageMaker Real-Time50-200 msper instance-hrNo (min 1)Steady online traffic
SageMaker Serverless+ cold startper invokeYesBursty / low volume
SageMaker Batch Transformminuteslowest (job)YesOffline scoring
Bedrock200 ms+per tokenYes (managed)Foundation models, no ops
Inf2 (self/SM)10-50 msper instance-hrAutoHigh-throughput $/req at scale
ECS/EKS + GPU10-100 msper instance-hrManualFull control (vLLM/TGI)

Bedrock removes GPU management entirely: pay per token for Claude, Llama, Titan, Mistral. Auto-scale a self-hosted endpoint on SageMakerVariantInvocationsPerInstance, and use production variants for canary/blue-green rollout.

import boto3, json
br = boto3.client("bedrock-runtime")
r = br.invoke_model(
    modelId="anthropic.claude-3-sonnet-20240229-v1:0",
    body=json.dumps({"anthropic_version": "bedrock-2023-05-31",
                     "max_tokens": 1024,
                     "messages": [{"role": "user", "content": "Summarize FSDP."}]}))
print(json.loads(r["body"].read())["content"][0]["text"])

Vector Databases for RAG

RAG grounds an LLM in your data: embed documents into vectors, store them, and at query time retrieve the nearest neighbors by cosine/dot-product similarity. Brute-force search is O(n), so vector stores use ANN indexes for sub-linear latency.

  • HNSW — layered proximity graph, O(log n) queries, fast inserts, high RAM. Default in OpenSearch and pgvector. Tune m (edges/node) and ef_search (candidates) for recall vs speed.
  • IVF/IVFFlat — k-means clusters; search only the nearest nprobe lists. Lower memory, slower inserts (re-clustering). Better when memory-bound.
  • Dimensions — Titan Embed v2 = 1024 (flexible 256/512/1024), Cohere = 1024, OpenAI text-embedding-3-small = 1536. Cosine is the text default.
StoreScaleLatencyHybrid searchACIDBest for
OpenSearch k-NNBillions10-50 msExcellent (BM25 + vector)NoSearch at scale
pgvector (RDS/Aurora)<10M20-100 msGood (SQL filters)YesExisting Postgres
MemoryDB (Redis)Millions1-5 msGoodNoUltra-low latency
Bedrock Knowledge BasesAuto200-500 ms e2eLimitedN/AManaged RAG, no ops
{ "mappings": { "properties": {
  "embedding": {
    "type": "knn_vector", "dimension": 1024,
    "method": { "name": "hnsw", "space_type": "cosinesimil",
      "engine": "faiss", "parameters": { "ef_construction": 512, "m": 16 } } } } } }
CREATE EXTENSION vector;
CREATE TABLE docs (id serial PRIMARY KEY, content text,
                   category text, embedding vector(1024));
CREATE INDEX ON docs USING hnsw (embedding vector_cosine_ops)
  WITH (m = 16, ef_construction = 200);
-- metadata filter THEN nearest-neighbour; <=> is cosine distance
SELECT content, 1 - (embedding <=> :q) AS similarity
FROM docs WHERE category = 'engineering'
ORDER BY embedding <=> :q LIMIT 5;

Parallel Processing for ML Data

Preprocessing and offline scoring are embarrassingly parallel — fan out across many workers. Pick the service by task duration and whether you need GPUs.

ServiceModelGPUBest for
AWS Batch (array jobs)per instance-sec, one API launches 10k tasksYes (auto-selects)Genomics, rendering, bulk transforms
EMR (Spark)per instance-hr, transient clustersLimitedTB/PB ETL, feature engineering
Step Functions Distributed Mapper transition, up to 10k concurrencyNo (Lambda)S3-inventory fan-out, <15 min tasks
Lambda + SQSper invokeNoShort, event-driven bursts

Batch array jobs shard by index — each container reads AWS_BATCH_JOB_ARRAY_INDEX to claim its slice. Step Functions Distributed Map reads directly from an S3 listing and batches items per Lambda.

{ "Type": "Map",
  "ItemReader": { "Resource": "arn:aws:states:::s3:listObjectsV2",
    "Parameters": { "Bucket": "src", "Prefix": "images/" } },
  "ItemBatcher": { "MaxItemsPerBatch": 100 },
  "MaxConcurrency": 1000,
  "ItemProcessor": {
    "ProcessorConfig": { "Mode": "DISTRIBUTED", "ExecutionType": "STANDARD" },
    "StartAt": "ProcessBatch",
    "States": { "ProcessBatch": {
      "Type": "Task", "Resource": "arn:aws:lambda:...:ProcessBatch", "End": true } } },
  "End": true }

Watch for stragglers (one slow shard stalls the job — use Spark speculative execution or SQS work-stealing), data skew (salt hot keys), and the fan-in tail (aggregation can dwarf the fan-out if unplanned).

Storage & Cost for GPU Workloads

A starved GPU is wasted money, so training storage must feed data faster than the GPUs consume it. S3 is the durable source of truth; a high-throughput cache sits between S3 and the accelerators.

LayerRoleThroughputNote
S3Data lake + model artifactsHigh (parallel)Use VPC Gateway Endpoint to skip NAT $0.045/GB
FSx for LustreShared scratch for training250 MB/s per TiB, sub-msAuto-imports from S3; POSIX mount
EBS gp3 / NVMeLocal checkpoints/OSup to 80k IOPSInstance-store NVMe for hot data
EFSShared model serving filesElasticRead-only mount across inference tasks
resource "aws_fsx_lustre_file_system" "train" {
  storage_capacity            = 4800          # GB
  deployment_type             = "PERSISTENT_2"
  per_unit_storage_throughput = 250           # MB/s per TiB
  data_repository_association {
    file_system_path    = "/data"
    data_repository_uri = "s3://my-training-bucket"   # lazy-load from S3
  }
}

On cost: Spot saves 60-90% and training is inherently retryable, so it is the default for training — with checkpoints to S3 every 15-30 min so a 2-minute interruption notice costs at most one interval. p4d.24xlarge falls from ~$32.77/hr On-Demand to ~$9.83/hr Spot; a 100-hr job goes $3,277 to ~$983. SageMaker Managed Spot handles checkpoint/resume automatically. Reserve or use Savings Plans for always-on inference instead.

Architecting RAG on AWS

The canonical GenAI system design question ties the whole module together: an ingestion path that vectorizes documents and a query path that retrieves-then-generates.

INGEST:  S3 docs -> Lambda (chunk 512 tok / 100 overlap)
                  -> Bedrock Titan Embed v2 (1024-d) -> OpenSearch k-NN (HNSW)
                                                     -> metadata -> DynamoDB

QUERY:   User -> API GW -> Lambda -> embed query -> OpenSearch (k-NN + BM25 hybrid)
              -> top-5 + metadata filter -> Cohere Rerank (Bedrock)
              -> prompt w/ context -> Bedrock Claude -> Guardrails -> response
MODULE 22

AWS Architecture Patterns & Decisions

Battle-tested reference architectures and a service-selection decision matrix.

There Is No Best Architecture

Senior interviews probe judgment, not recall. AWS ships 200+ services; a real system uses fewer than 15. The signal an interviewer wants is that you derive an architecture from constraints rather than reaching for whatever is trendy. State this explicitly: there is no best architecture, only the one that is right for a specific set of constraints.

  • Team size — 3 engineers cannot operate EKS + service mesh + a data platform. Operational capacity is a first-class constraint, not an afterthought.
  • Scale profile — steady, spiky, or zero-to-hero? Spiky and scale-to-zero favor serverless; sustained high utilization favors reserved containers or EC2.
  • Budget — a startup optimizes for a low floor and pay-per-use; an enterprise optimizes for predictability and committed-use discounts.
  • Timeline — an MVP due in 6 weeks and a 5-year platform demand opposite altitudes of investment.
  • Domain — fintech needs ACID, audit trails, and strong isolation; social needs eventual consistency and cheap fan-out.

The interview move: restate requirements as numbers, pick the highest level of abstraction that meets them (Lambda > Fargate > EC2 > EKS in ascending operational cost), and name what would make you revisit the choice.

Reference Architectures at a Glance

Memorize seven canonical patterns. Each is a named answer you can pattern-match onto a prompt, then defend with its tradeoff. Below is the compressed map; the following sections drill into the ones interviewers push hardest on.

PatternKey servicesWhen to usePrimary tradeoff
3-tier webALB + Auto Scaling Group (EC2/Fargate) + RDS/AuroraFamiliar CRUD app, SQL data, steady traffic, team knows serversYou own capacity & patching; scales vertically at the DB tier
ServerlessAPI Gateway + Lambda + DynamoDBSpiky/unknown traffic, MVP, small team, scale-to-zero economics15-min ceiling, cold starts, vendor lock-in, DynamoDB access-pattern rigidity
Event-drivenEventBridge + SNS + SQS (+ Lambda)Many consumers of one event, async OK, decoupling neededEventual consistency, harder end-to-end tracing & debugging
MicroservicesECS/EKS + Cloud Map / Service Connect service discovery (App Mesh discontinued 30 Sep 2026)Large org, independent deploy cadence, per-service scalingOperational & cognitive overhead; needs a mature platform team
Static site / SPAS3 + CloudFront (+ OAC)Marketing site, docs, single-page app front endNo server-side compute; personalization needs an API tier
Data lakeS3 + Glue + Athena (+ Lake Formation)Big data, exploration, schema-on-read, ML feature sourceGovernance required or it rots into a "data swamp"
StreamingKinesis Data Streams / Amazon MSK (+ Firehose)Ordered real-time events, replay, multi-consumer telemetryShard/partition capacity planning; ~200ms+ end-to-end latency

3-Tier Web and Serverless in Depth

The 3-tier pattern is the default request-response shape: a load balancer fronts a stateless compute tier that Auto Scaling grows and shrinks, backed by a managed relational database. It is the right answer when the data is relational, queries need JOINs and ad-hoc reporting, and the team is SQL-proficient.

  1. Route 53 resolves to CloudFront, which caches static assets and terminates TLS at the edge.
  2. An ALB (Layer 7) does path-based routing to an Auto Scaling Group of Fargate tasks or EC2 instances across multiple AZs.
  3. Compute stays stateless; session and cache state live in ElastiCache Redis.
  4. Aurora/RDS holds durable state, with Multi-AZ for HA and read replicas for read scaling.

The serverless variant collapses the compute and scaling tiers into API Gateway + Lambda and swaps the relational store for DynamoDB. It is the right answer when access patterns are known and simple, traffic is bursty or can drop to zero, and you want no servers to patch. The catch: DynamoDB rewards you only if you can draw every access pattern on a whiteboard before building. If you can't, you want RDS.

Dimension3-tier (ALB + ASG + Aurora)Serverless (API GW + Lambda + DynamoDB)
Data modelRelational, JOINs, ad-hoc queriesKey-value / known access patterns
ScalingMinutes (ASG warm-up), DB scales vertically~100ms, per-request concurrency
Idle costYou pay for running instancesScales to zero — pay nothing
Latency floor~1ms warm behind ALB~10ms warm, 100ms–several s cold
Ops burdenCapacity planning, patching (EC2)Minimal; AWS runs the fleet
resource "aws_dynamodb_table" "orders" {
  name         = "orders"
  billing_mode = "PAY_PER_REQUEST"  # on-demand: true pay-per-use with Lambda
  hash_key     = "PK"
  range_key    = "SK"

  attribute { name = "PK" type = "S" }  # e.g. TENANT#123
  attribute { name = "SK" type = "S" }  # e.g. ORDER#2026-07-01

  stream_enabled   = true             # fan out changes to read models / search
  stream_view_type = "NEW_AND_OLD_IMAGES"
}

Serverless vs Containers vs VMs

Almost every architecture reduces to one compute decision, and interviewers love to make you defend all three legs. The heuristic: pick the highest abstraction that fits, and only descend when a hard constraint forces you to.

CriterionLambda (serverless)Fargate/EKS (containers)EC2 (VMs)
Max duration15 minUnlimitedUnlimited
GPU / custom kernelNoFargate no; EKS on EC2 yesYes
Scaling speed~100ms~30–60s~3–5 min
Ops overheadMinimalLow (Fargate) / high (EKS)High
Cost at low volumeCheapest (scales to zero)Moderate flat floorWasteful when idle
Cost at high steady volumeExpensiveGoodCheapest (Savings Plans/Spot)

Event-Driven and Streaming

Synchronous chains are only as fast as their slowest hop and couple services tightly. Event-driven architecture inverts this: a producer emits an event and moves on; consumers react independently. The three async primitives are not interchangeable — pick by the shape of the delivery, not by habit.

  • SQS — a queue, one message processed once by one consumer. Standard is at-least-once with best-effort ordering and near-unlimited throughput; FIFO gives exactly-once processing (5-min dedup window) and strict order per message group, capped by default at 300 msg/s (3,000 with batching; high-throughput mode raises it). Use for decoupling and work buffering.
  • SNS — pub/sub fan-out, one message to many subscribers. Use for notifications; pair with an SQS queue per consumer for durability.
  • EventBridge — an event bus with content-based routing rules and SaaS integrations. Use when many producers route to many consumers with filters, and you want a configurable-retention replay archive.
  • Kinesis / MSK — an ordered, replayable stream. Use for real-time clickstream, IoT telemetry, and log aggregation where ordering (per shard/partition) and multi-consumer replay matter. Kinesis is 1 MB/s per shard; MSK is managed Kafka for teams already in that ecosystem.

The senior distinction: choose Kinesis over SQS when you need ordering, replay, AND multiple independent consumers reading the same events — for example, one real-time path plus one analytics path plus an anomaly detector, all off a single stream partitioned by user_id.

{
  "Source": "com.myapp.orders",
  "DetailType": "OrderCreated",
  "Detail": { "orderId": "abc123", "total": 42.00 },
  "EventBusName": "orders-event-bus"
}
                 +----------------------+
  Order Service ->|  EventBridge bus     |
                  +----------------------+
                    |        |         |
        rule: pay   |   rule: stock    |  rule: notify
                    v        v         v
                 Lambda     SQS       SNS
                (charge) (fulfil)  (email/SMS)
  One event, three reactions, zero coupling between them.

Data Lake and Analytics

When the requirement is "store everything cheaply and query it later," the answer is a data lake, not a warehouse. Raw data lands in S3 in its native format (schema-on-read); Glue crawls it into a catalog; Athena runs serverless SQL directly over S3. Contrast with a data warehouse (Redshift), which stores processed, structured data with schema-on-write, optimized for BI dashboards.

  1. Ingest — Amazon Data Firehose, Glue, or DMS land data in S3.
  2. Store in medallion tiers — raw (bronze) → processed (silver) → curated (gold) prefixes, with lifecycle rules tiering old data to Glacier.
  3. Catalog — a Glue Crawler discovers schema into the Glue Data Catalog on a schedule.
  4. Query — Athena for ad-hoc SQL; EMR/Spark for heavy ETL; Redshift Spectrum or SageMaker for BI and ML.

Cost levers that interviewers reward: partition by date, compress, and store columnar (Parquet). Athena bills $5 per TB scanned, so a Parquet + partition-pruning layout can cut a query's cost by 10–100x versus raw JSON. Without governance (Lake Formation permissions, a catalog, naming), the lake degrades into an unqueryable swamp.

-- Athena scans only the July 1 partition, not the whole bucket
SELECT customer_id, SUM(total) AS revenue
FROM curated.orders
WHERE dt = '2026-07-01'
GROUP BY customer_id
ORDER BY revenue DESC
LIMIT 20;

The Service-Selection Decision Matrix

Interviewers give you a requirement and expect a service in one breath, then the "why." Internalize the mapping so you spend your thinking budget on tradeoffs, not recall. Read each row as requirement → pattern/service → the constraint that makes it fit.

RequirementPattern / serviceBecause
Simple API, bursty trafficAPI Gateway + LambdaScales to zero; cheapest under ~5M req/mo
Long-running service, no GPUFargate (ECS)No 15-min cap; no server management
Kubernetes ecosystem / multi-cloudEKS + KarpenterPortability & CNCF tooling justify the overhead
Relational data, JOINs, < 64TBRDS/Aurora PostgreSQLACID, ad-hoc SQL, evolving access patterns
Key-value at massive scaleDynamoDBSingle-digit ms at any scale; known patterns
Sub-ms reads, sessions, leaderboardsElastiCache RedisIn-memory; rich data structures
Fan-out to many consumersSNS or EventBridgePub/sub vs rule-based routing
Ordered real-time stream, replayKinesis Data StreamsPer-shard order + multi-consumer replay
Files, images, backupsS311 nines durability; cheapest object store
Global static/dynamic deliveryCloudFront + S3Edge caching cuts latency & origin cost
Multi-region active-active writesDynamoDB Global TablesRDS/Aurora have one write region
Foundation models / RAGBedrock (+ Knowledge Bases)Managed LLMs, pay-per-token, no hosting

Well-Architected: The Six Pillars as a Lens

The AWS Well-Architected Framework is the rubric interviewers implicitly grade against. Use its six pillars as a checklist to pressure-test any design you propose; naming them signals maturity.

PillarCore questionLevers
Operational ExcellenceCan we run & evolve it safely?IaC, CI/CD, runbooks, observability
SecurityIs it least-privilege by default?IAM, KMS encryption, no 0.0.0.0/0 SGs
ReliabilityDoes it survive failures?Multi-AZ, health checks, auto-recovery
Performance EfficiencyRight resource for the job?Right-sizing, caching, serverless where it fits
Cost OptimizationAre we paying only for value?Savings Plans, Spot, scale-to-zero, lifecycle tiering
SustainabilityMinimizing footprint?Graviton, efficient regions, right-sizing

Migration: The 6 Rs and Strangler Fig

"Migrate this on-prem system to AWS" is a staple prompt. AWS's 6 Rs give you a vocabulary to triage each workload instead of blindly lifting-and-shifting everything.

StrategyWhat it meansWhen
Rehost"Lift & shift" VMs as-is to EC2Speed matters; refactor later
ReplatformMinor tweaks (self-run DB → RDS)Quick wins without a rewrite
RepurchaseMove to a SaaS productCommodity function (email, CRM)
Refactor / Re-architectRedesign cloud-nativeScaling or agility limits justify cost
RetireDecommission itNobody uses it anymore
RetainLeave it where it is (for now)Compliance or not-yet-worth-moving

For the refactor case, the Strangler Fig pattern is the safe incremental path: put an API Gateway facade in front of the monolith, extract one bounded context at a time (start with the least-coupled domain), route its traffic to a new service, and repeat until the monolith is retired. Extract data via events (EventBridge), not a shared database, and accept temporary duplication. Timeline is months to years, not weeks — saying so is itself a maturity signal.

Phase 1  Clients -> API GW -> Monolith (100%)
Phase 2  Clients -> API GW -> [Orders 20%] + Monolith (80%)
Phase 3  Clients -> API GW -> [Orders][Users] + Monolith (50%)
Phase 4  Clients -> API GW -> [Orders][Users][Payments][Notif]  (monolith retired)
MODULE 23

AWS Virtualization Internals

How EC2 actually isolates you: the Nitro system, hypervisor evolution, and hardware offload.

Hypervisor Taxonomy

Every EC2 instance, Fargate task, and Lambda invoke sits on a hypervisor. Interviewers want you to place the technology precisely: which layer runs the virtual machine monitor (VMM), and how the guest's privileged instructions get trapped.

  • Type-1 (bare-metal) — VMM runs directly on hardware, no host OS underneath. Xen, VMware ESXi, Hyper-V, and the Nitro hypervisor. This is what clouds run.
  • Type-2 (hosted) — VMM is a process on a general-purpose OS. VirtualBox, VMware Workstation, QEMU-on-your-laptop. Extra scheduling hop, so slower.
  • Full virtualization — guest runs unmodified; the VMM emulates real hardware (an Intel e1000 NIC, an IDE controller). Correct but slow: every device register write traps.
  • Paravirtualization (PV) — guest is aware it is virtualized and calls the hypervisor cooperatively (hypercalls, virtio drivers). Fewer traps, higher throughput.
  • Hardware-assisted (HVM) — Intel VT-x / AMD-V add a CPU mode so the guest kernel runs unmodified at near-native speed while sensitive ops trap in silicon. Modern EC2 is HVM + paravirtual I/O (virtio/ENA).
ApproachGuest modified?Privileged-op handlingOverhead
Binary translation (old VMware)NoRewrite guest instructions at runtimeHigh
Classic paravirt (old Xen PV)Yes (hypercalls)Guest calls hypervisor explicitlyMedium
Hardware-assisted (VT-x/AMD-V)NoCPU traps sensitive ops to VMMLow (<5%)
Nitro (HVM + HW offload)NoCPU traps + I/O offloaded to cards~0

How a Guest Is Isolated: Rings, EPT, IOMMU

Isolation is enforced by three independent hardware mechanisms. Know all three cold — they map to the three things a guest could otherwise abuse: the CPU, memory, and DMA-capable devices.

  • Rings + VMX modes — the guest kernel still runs in ring 0, but inside VMX non-root mode. Sensitive instructions (CPUID, MSR/CR access, I/O) cause a VM exit into VMX root mode where the VMM handles them. State lives in the VMCS (Intel) / VMCB (AMD).
  • EPT / NPT (nested page tables) — two-layer translation: guest page tables map GVA→GPA (guest-controlled), then EPT maps GPA→HPA (hypervisor-controlled). The guest can never forge a host physical address.
  • IOMMU (VT-d / AMD-Vi) — the "EPT for devices." A NIC doing DMA is confined to the VM's memory, which is what makes safe PCI passthrough / SR-IOV possible.

Because address translation is now two-dimensional, a TLB miss is expensive — a full walk touches both page-table trees:

x86-64 nested walk (worst case, cold TLB):
  4 guest levels (PML4 -> PDPT -> PD -> PT)  x
  4 EPT levels per guest-physical access
  = up to 24 memory accesses for ONE translation
  => TLB + large pages (2MB/1GB) are critical for VM perf
# Confirm hardware virtualization + IOMMU are live on a host
grep -Eom1 'vmx|svm' /proc/cpuinfo        # vmx = Intel VT-x, svm = AMD-V
dmesg | grep -e DMAR -e IOMMU             # VT-d / AMD-Vi enabled
lscpu | grep -i 'Hypervisor vendor'       # e.g. "KVM" inside a Nitro guest

The Xen Era vs the Nitro System

From 2006 to 2017, EC2 ran on a customized Xen hypervisor. The host CPU ran the hypervisor, a privileged Dom0 Linux, device emulation, network/storage data paths, and encryption — all stealing cycles from your instance. Nitro (launched with the C5 family, late 2017) inverted this: push everything except thin VM lifecycle management off the main CPU and onto dedicated hardware.

DimensionXen era (pre-2018)Nitro system
HypervisorXen + fat Dom0 LinuxThin KVM-based Nitro hypervisor
Network/storage data pathEmulated/PV in software on host CPUOffloaded to Nitro cards (ASIC/FPGA)
Host CPU spent on virt overheadUp to ~30%~1% (near bare-metal)
Bare-metal instancesNot possible*.metal — no hypervisor at all
Root of trust / operator accessSoftware-mediatedNitro Security Chip; no operator shell to guests
Management planeRuns beside guest on hostRuns on cards, isolated from guest

The Nitro hypervisor is deliberately anemic: it does VM create/destroy, vCPU and memory assignment, and little else. There is no general-purpose Dom0 to compromise and no software device model in the hot path — the guest talks to real PCIe devices exposed by the cards.

Nitro Cards: Offloading I/O and Security

The Nitro cards are a set of purpose-built PCIe devices. Each presents itself to the guest as a standard hardware endpoint, so the guest OS uses ordinary drivers while the card does the heavy lifting in silicon.

Nitro componentResponsibilityGuest sees
Nitro Card for VPCVPC networking, overlay encap, security groups, encryption in transitENA NIC
Nitro Card for EBSRemote block storage over NVMe, at-rest encryptionNVMe disk
Nitro Card for Instance StorageLocal NVMe SSD, transparent encryptionNVMe disk
Nitro Card ControllerCoordinates cards, exposes the system to the hypervisor(hidden)
Nitro Security ChipHardware root of trust, secure boot, firmware validation; locks out operator access(hidden)

Because encryption and the storage/network data path live on the card, they cost the customer zero CPU — EBS encryption is "free," and VPC traffic is authenticated/encrypted between hosts without touching your vCPUs.

SR-IOV, ENA, and EFA

The final mile of near-bare-metal I/O is letting the guest talk to hardware queues directly, bypassing the hypervisor per-packet. That is SR-IOV.

  • SR-IOV — one physical NIC exposes many lightweight Virtual Functions (VFs). The IOMMU confines each VF's DMA to one VM, so a guest gets its own hardware queue with no VMM in the data path.
  • ENA (Elastic Network Adapter) — AWS's SR-IOV NIC driver, standard on Nitro. Scales to 100 Gbps (200 Gbps on some newer instances) with multiqueue, checksum, and segmentation offload.
  • EFA (Elastic Fabric Adapter) — ENA plus an OS-bypass path. Its SRD protocol lets MPI/NCCL libraries (via libfabric) write to the fabric from userspace, skipping the kernel TCP stack — the backbone of HPC and large-model GPU training clusters.
# Inspect the ENA device inside a Nitro guest
ethtool -i eth0            # driver: ena
ethtool -S eth0 | grep -e bw_ -e allowance   # bandwidth/allowance exceeded counters

# EFA presence (OS-bypass fabric)
fi_info -p efa            # libfabric provider "efa" => SRD available
lspci | grep -i 'Elastic Fabric'

Watch the allowance_exceeded counters: EC2 network limits are enforced by the Nitro card as token buckets, so a "slow network" is often micro-bursting past the per-instance allowance, not congestion.

Containers vs VMs vs Firecracker MicroVMs

Nitro handles the EC2 layer; serverless needs a lighter unit. AWS built Firecracker, a minimal KVM-based VMM in Rust (~50k lines vs QEMU's ~1.4M), stripping device emulation down to virtio-net, virtio-block, and a serial console. Lambda and Fargate run every tenant workload inside a Firecracker microVM.

PropertyContainerFirecracker microVMTraditional VM (QEMU)
KernelShared host kernelOwn guest kernelOwn guest kernel
Boundarynamespaces + cgroups + seccompVT-x/EPT + tiny VMMVT-x/EPT + large VMM
Boot / start~100 ms<125 ms (often <50 ms)500 ms – several s
Memory overhead~1–5 MB~5 MB~100 MB+
Emulated devicesnone (n/a)~4100+
Density / host1000s1000s (thousands per node)hundreds
Isolation strengthWeakest (shared kernel)Strong (HW-enforced)Strong

Firecracker's jailer wraps the VMM in a chroot, cgroups, namespaces, and a seccomp allowlist of only ~25 syscalls — so even a VMM escape lands in a stripped host sandbox. That is how AWS safely packs untrusted, multi-tenant code onto one bare-metal worker.

What Actually Runs Your Lambda

Trace one invoke top to bottom and you have the whole module in one answer. The request hits the Lambda frontend, a placement service finds or spins a microVM on a bare-metal EC2 worker, and your handler runs inside it.

  1. Invoke arrives at the Lambda frontend (auth, throttling, routing).
  2. Placement service finds a warm Firecracker microVM or cold-starts a new one on a bare-metal Nitro worker.
  3. Firecracker boots a minimal Linux guest (<125 ms) with your runtime + code + deps mounted.
  4. Handler executes; the control plane talks to it over virtio-vsock (no network stack).
  5. MicroVM is frozen/reused for the next invoke, or reaped after idle.
Invoke
  -> Lambda frontend
  -> Placement service (per bare-metal worker)
  -> Firecracker microVM  [KVM guest]
       guest kernel + runtime + your code
  -> Firecracker VMM (Rust, jailer + seccomp ~25 syscalls)
  -> Host KVM on bare-metal EC2 (Nitro)
  -> Nitro cards + VT-x/EPT/IOMMU hardware

Cold vs warm is just microVM lifecycle: a warm path routes to a live VM in ~1–5 ms; a cold path pays Firecracker boot plus runtime init (~200 ms and up depending on language and package size).

{
  "unit_of_isolation": "Firecracker microVM (one per execution env)",
  "host": "bare-metal EC2 worker on the Nitro system",
  "vmm": "Firecracker (KVM-based, Rust)",
  "guest_to_control_plane": "virtio-vsock",
  "cold_start": "Firecracker boot (<125ms) + runtime init",
  "warm_start": "route to existing microVM (~1-5ms)"
}
MODULE 24

Cheat Sheet

Pick services fast. Defaults for new projects.

Default Stack (AWS)

  • Compute: ECS Fargate or EKS
  • Data: Aurora Postgres + DynamoDB
  • Cache: ElastiCache Redis
  • Queue: SQS + EventBridge
  • Object: S3 + CloudFront
  • Auth: Cognito or external IdP

Pick LB

  • HTTP(S) + path/host routing → ALB
  • TCP/UDP, static IP, ultra-low latency → NLB
  • Global anycast → Global Accelerator / CloudFront
  • Cross-region failover → Route 53 health checks

Pick DB

  • Relational + transactions → Aurora / RDS Postgres
  • K-V, ms latency, scale-out → DynamoDB
  • Search → OpenSearch
  • Time-series → Timestream for InfluxDB (managed) / Amazon Managed Prometheus
  • Graph → Neptune
  • Wide-column → Keyspaces (Cassandra)

K8s Sanity

  • Always set requests; limits with care
  • Liveness ≠ readiness; startup probe for slow boot
  • PDB on every Deployment in prod
  • NetworkPolicy default-deny ingress
  • Pin image digest, not tag
  • Use HPA on custom metrics, not just CPU

Cost Quick Wins

  • S3 lifecycle: Standard → IA → Glacier
  • EBS gp2 → gp3 (10–20% cheaper)
  • VPC endpoint for S3/Dynamo to skip NAT
  • Compute Savings Plan @ ~60% baseline
  • Spot for batch/CI/dev
  • Set log retention < 30 days unless required

IaC Hygiene

  • Remote state + state lock
  • One module per logical unit
  • Plan in PR; apply on merge
  • No hardcoded secrets — use SM / Vault
  • Drift detection scheduled
  • Tag everything: env, owner, cost-center
MODULE 25

CI/CD Delivery & Service Mesh

The delivery layer and the mesh: GitOps, progressive delivery, and Istio/Envoy sidecars with mTLS.

The CI/CD Pipeline: Source to Deploy

A pipeline is an automated assembly line that turns a Git commit into a running workload. Each stage is a gate: a failure stops promotion, so a bad commit never reaches production. The canonical stages are source, build, test, package, and deploy — each producing an immutable artifact the next stage consumes.

  1. Source — a push or merge to a branch fires a webhook. The runner checks out the exact commit SHA (never "latest") so the build is reproducible.
  2. Build — compile code, resolve dependencies, produce a binary or container image. The image is tagged with the commit SHA, not latest.
  3. Test — unit tests (fast, run first), then integration and contract tests, then security/dependency scans. Fail fast: cheap checks gate expensive ones.
  4. Package & publish — push the image to a registry (ECR, GCR, Harbor) and other artifacts to an artifact store. This is the promotable unit.
  5. Deploy — roll the versioned artifact into an environment (dev → staging → prod), usually with an approval gate before prod.

The core discipline is build once, promote everywhere: you build the artifact a single time and move that exact bytes-identical image through every environment. Rebuilding per environment reintroduces "works in staging, breaks in prod" drift.

# GitHub Actions: build once, tag by SHA, push to registry
jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - name: Build & push
        run: |
          IMG=ghcr.io/acme/api:${{ github.sha }}
          docker build -t "$IMG" .
          docker push "$IMG"       # immutable, SHA-tagged artifact
  test:
    needs: build
    steps:
      - run: pytest -q            # gate: promotion blocked on failure

Artifacts, Registries & Provenance

An artifact is any build output you keep: a container image, a JAR, an npm tarball, a Terraform plan. The registry is the versioned store for these — a container registry for images, an artifact repository (Artifactory, Nexus) for language packages. The registry is the boundary between CI (build/test) and CD (deploy).

  • Immutability — once api@sha256:9f2c… is pushed, it never changes. Deployments reference the digest, so what you tested is exactly what runs.
  • Provenance / SBOM — a Software Bill of Materials lists every dependency in the image. Signing (cosign/Notary) lets the cluster verify the image came from your pipeline, blocking supply-chain tampering.
  • Retention — registries grow fast; policies garbage-collect untagged and old images. Keep the last N releases plus anything a live deployment references.
# Sign at publish time, verify at admission
cosign sign   ghcr.io/acme/api@sha256:9f2c...
cosign verify --key cosign.pub ghcr.io/acme/api@sha256:9f2c...
# An admission controller rejects unsigned images cluster-wide

GitOps: The Pull Model (ArgoCD & Flux)

Traditional CD pushes: the pipeline holds cluster credentials and runs kubectl apply from outside. GitOps inverts this to a pull model: a controller running inside the cluster continuously watches a Git repo of manifests and reconciles the live state to match. Git is the single source of truth; the cluster converges to it.

AspectPush CD (kubectl/Helm from CI)Pull CD (GitOps: ArgoCD/Flux)
CredentialsCI holds cluster admin keys (blast radius)Controller lives in-cluster; no external creds
Source of truthWhatever CI last ranGit repo, always
DriftManual kubectl edit goes unnoticedDetected and auto-reverted to Git state
RollbackRe-run pipelinegit revert — one commit
AuditCI logsGit history = full change log

The flow: CI builds and pushes an image, then commits an updated image tag into the config repo (often via an automated bump). ArgoCD/Flux sees the commit, syncs, and reports Healthy/Synced. Separating the app repo (code) from the config repo (manifests) keeps a merge to main from silently mutating prod.

# ArgoCD Application: reconcile cluster to Git, self-heal drift
apiVersion: argoproj.io/v1alpha1
kind: Application
metadata: { name: payments, namespace: argocd }
spec:
  source:
    repoURL: https://github.com/acme/deploy.git
    path: envs/prod/payments
    targetRevision: main
  destination: { server: https://kubernetes.default.svc, namespace: pay }
  syncPolicy:
    automated: { prune: true, selfHeal: true }  # revert manual edits

Progressive Delivery: Rolling, Blue-Green, Canary, Flags

Deploying is not the same as releasing. Progressive delivery limits the blast radius of a bad version by exposing it to a shrinking-risk slice of traffic or users before full rollout.

StrategyHow it worksCost / rollbackBest for
RollingReplace pods N at a time, old + new coexist briefly1x capacity; rollback = roll back pods (slow)Default, stateless, backward-compatible changes
Blue-greenFull new stack (green) beside old (blue); flip router2x capacity; rollback = instant flip backFast rollback, hard schema cutovers
CanaryRoute 1%→5%→25%→100% to new, watch metrics~1.1x capacity; rollback = shift traffic backRisky changes, gradual confidence
Feature flagsShip code dark, toggle per-user/segment at runtimeNo redeploy; rollback = flip flagDecoupling deploy from release, A/B tests

The key insight: rolling and blue-green operate at the deploy layer (which pods run), while canary operates at the traffic layer (who gets routed), and feature flags operate at the code layer (which branch executes). Flags let you deploy at 3pm and release at midnight to 1% of users, fully decoupling the two.

Automated Rollback on SLO Breach

Manual canary watching does not scale — a human staring at Grafana at 2am is a liability. Progressive-delivery controllers (Argo Rollouts, Flagger) automate the promote/abort loop: they shift a traffic weight, pause, query the observability backend for the new version's SLIs, and compare against a threshold. Breach → automatic rollback; pass → promote to the next step.

# Argo Rollouts canary with an automated SLO gate
strategy:
  canary:
    steps:
      - setWeight: 5
      - pause: { duration: 5m }
      - analysis:                     # query Prometheus
          templates: [{ templateName: error-rate }]
      - setWeight: 25
      - pause: { duration: 10m }
      - setWeight: 100
---
# AnalysisTemplate: abort if 5xx rate on the canary > 1%
metrics:
  - name: error-rate
    interval: 1m
    failureLimit: 2                    # 2 bad samples -> rollback
    successCondition: result[0] < 0.01
    provider:
      prometheus:
        query: |
          sum(rate(http_requests_total{version="canary",status=~"5.."}[2m]))
          / sum(rate(http_requests_total{version="canary"}[2m]))
  • SLI — the measured signal (error rate, p99 latency, saturation). SLO — the target the SLI must meet (99.9% success). The gate aborts when the SLI crosses the SLO-derived threshold.
  • Baseline vs canary — compare the new version to the current stable running right now, not a static number, to cancel out time-of-day traffic effects.
  • failureLimit — require several bad samples before aborting so one noisy scrape doesn't trigger a false rollback.

Service Mesh: Sidecar, Data Plane vs Control Plane

A service mesh moves cross-cutting network concerns — mTLS, retries, timeouts, routing, telemetry — out of application code and into a dedicated infrastructure layer. It does this by injecting a sidecar proxy (Envoy in Istio; a lightweight Rust micro-proxy in Linkerd) into every pod. All of the pod's traffic is transparently redirected through its proxy, so the app talks plain HTTP to localhost and the proxy handles the network.

  • Data plane — the fleet of sidecar proxies that actually carry request traffic. This is where mTLS, load balancing, retries, and metrics collection happen, on the hot path.
  • Control plane — the brain (Istio's istiod). It has no request traffic through it; it distributes config and certificates to the proxies and watches the Kubernetes API. If the control plane dies, existing proxies keep routing with their last-known config — the data plane fails static, not closed.
  • Sidecar injection — a mutating admission webhook adds the proxy container at pod-creation time, so developers change nothing. Newer Istio "ambient" mode replaces per-pod sidecars with a per-node proxy to cut overhead.
        CONTROL PLANE (istiod): config + CA certs, no traffic
                 |  pushes xDS config & certs
   +-------------+-------------+
   v                           v
+--------- pod A ---------+   +--------- pod B ---------+
| app -> [Envoy sidecar] =====mTLS====> [Envoy] -> app |
+------------------------+   +-------------------------+
        DATA PLANE: proxies carry every request

mTLS & Traffic Control: Shifting, Mirroring, Resilience

Because every hop goes through a proxy the mesh controls, it can enforce identity and shape traffic declaratively. mTLS (mutual TLS) means both sides present certificates: the caller proves who it is and the callee proves who it is. The mesh issues short-lived per-workload certs (SPIFFE identities) and rotates them automatically, so service-to-service traffic is encrypted and authenticated with zero app code — enabling zero-trust networking inside the cluster.

  • Traffic shifting — send a weighted split (e.g. 90/10) across two versions; the substrate for canaries, driven entirely by config.
  • Mirroring (shadowing) — copy live requests to a new version and discard its responses. You test v2 with real production traffic while users only ever see v1's answers — zero user risk.
  • Retries & timeouts — the proxy retries idempotent failures and caps how long a call may hang, keeping one slow dependency from stalling callers.
  • Circuit breaking / outlier detection — eject an endpoint that returns too many 5xx or 503s so it stops receiving traffic until it recovers, preventing cascading failure.
# Istio VirtualService: 10% canary, mirror all traffic to v2, retry + timeout
apiVersion: networking.istio.io/v1beta1
kind: VirtualService
spec:
  hosts: [reviews]
  http:
    - route:
        - { destination: { host: reviews, subset: v1 }, weight: 90 }
        - { destination: { host: reviews, subset: v2 }, weight: 10 }
      mirror: { host: reviews, subset: v2 }   # shadow, responses dropped
      mirrorPercentage: { value: 100 }
      timeout: 2s
      retries: { attempts: 3, perTryTimeout: 500ms, retryOn: 5xx,reset }

Observability & When a Mesh Is Overkill

A mesh's best "free" feature is uniform observability: because every request crosses a proxy, you get consistent golden-signal metrics (request rate, error rate, latency percentiles), a per-hop topology map, and automatic distributed-trace span propagation — for every service, in one format, without touching app code. That is genuine value. But a mesh is not free, and for many teams it is the wrong tool.

  • Latency & resource cost — every call now traverses two extra proxy hops; sidecars add per-pod CPU/memory. On a small fleet this overhead can outweigh the benefit.
  • Operational complexity — you are now running and upgrading a distributed control plane, cert authority, and CRDs. That is a platform-team commitment, not a config toggle.
  • Debugging surface — an extra network layer means new failure modes (mTLS handshake errors, config that didn't propagate, ejected endpoints) that are opaque to app developers.
SignalMesh probably overkillMesh earns its keep
Service count< 5–10 servicesDozens–hundreds of services
mTLS needHandled by cloud LB / app libsZero-trust, compliance-driven encryption everywhere
Traffic controlBasic k8s rolling deploys sufficeCanary/mirroring across many teams
TeamNo dedicated platform teamPlatform team to own upgrades

Rule of thumb: reach for the mesh when the same networking need — encryption, retries, canary routing, tracing — recurs across enough services that solving it per-app is more expensive than running the mesh. Below that threshold, a good HTTP client library, Kubernetes-native rolling deploys, and an ingress controller cover 90% of the need at a fraction of the operational cost. Start with a single capability (often mTLS or observability) rather than adopting the whole feature surface at once.

MODULE 26

AWS Service Reference

One verified card per service: what it is, when to pick it, the limits worth memorizing, the gotchas, and a snippet. Each card links to the deep-dive module that covers it in depth.

Amazon EC2

What it is. Virtual machines on the Nitro system: you own the OS, kernel, packages, storage and network. Instance names encode family, generation and capability (m8g.xlarge = general purpose, gen 8, Graviton). Family and purchase-model basics are in EC2 instance families, pricing models and AMIs and Auto Scaling; GPU and Trainium families are in GPU & accelerator instances.

Pick it when you need specific hardware (GPU, local NVMe, huge memory), a custom kernel or driver, licence-bound hosts, or steady load that packs well. Avoid it as the default for new stateless services: Lambda, Fargate or EKS Auto Mode remove the patching and capacity work.

QuestionCurrent answer (Oct 2026)
Which Arm generation?Graviton3 (m7g/c7g/r7g), Graviton4 (m8g/c8g/r8g, up to ~30% faster than Graviton3), Graviton5 (m9g/m9gd, GA mid-2026 in a limited set of Regions, up to ~25% over M8g). Intel Xeon 6 is c8i/m8i/r8i.
Biggest discounts?Spot up to 90%. Compute Savings Plan up to 66% (also covers Fargate and Lambda). EC2 Instance Savings Plan and Standard RI up to 72%.
Scarce GPUs?Capacity Blocks for ML: start up to 8 weeks ahead, 1–14 days in 1-day steps or up to 182 days in 7-day steps, up to 64 instances per block, selected families only (for example P5, Trn).
Billing?Per second, 60-second minimum, only while running. A stopped instance still bills its EBS volumes.
Quotas?vCPU-based. The Standard (A, C, D, H, I, M, R, T, Z) default starts at 5 vCPUs; G, P, Trn, Inf, X start at 0. AWS raises them with usage, so request GPU quota before you need it. Network interfaces: 5,000 per Region, enforced per AZ.
  • Spot. There is no bidding: you pay the current Spot price. Interruption notice is 2 minutes (EventBridge plus instance metadata); a rebalance recommendation can arrive earlier. In an ASG use a mixed instances policy, many instance types across AZs, price-capacity-optimized allocation and Capacity Rebalancing.
  • IMDSv2. Instances from AL2023 AMIs (and any AMI with imds-support=v2.0) default to token-required with hop limit 2, which containers need. Older AMIs may still allow IMDSv1: set HttpTokens=required in the launch template.
  • Burstable (T). t3, t3a, t4g and t8i launch in unlimited mode by default, so sustained load bills surplus credits instead of throttling. Use standard mode on Spot or when a hard cost cap beats speed.
  • Placement groups. cluster (low latency, one AZ), spread (max 7 running instances per AZ), partition (max 7 partitions per AZ, rack isolation for HDFS or Cassandra).
  • Lifecycle. Instance store survives reboot but not stop, hibernate, terminate or retirement. Launch configurations cannot be created by accounts made on or after 1 Oct 2024: use launch templates. Amazon Linux 2 reached end of support on 30 Jun 2026.
aws ec2 run-instances \
  --image-id resolve:ssm:/aws/service/ami-amazon-linux-latest/al2023-ami-kernel-6.1-arm64 \
  --instance-type t4g.large --subnet-id subnet-0abc --security-group-ids sg-0xyz \
  --iam-instance-profile Name=AppInstanceProfile \
  --metadata-options HttpTokens=required,HttpEndpoint=enabled,HttpPutResponseHopLimit=2 \
  --credit-specification CpuCredits=standard \
  --block-device-mappings '[{"DeviceName":"/dev/xvda","Ebs":{"VolumeType":"gp3","VolumeSize":20,"Encrypted":true}}]'
# shell access with no SSH key and no public IP
aws ssm start-session --target i-0123456789abcdef0

Amazon ECS

What it is. AWS's own container orchestrator with a free, fully managed control plane. You declare a task definition (immutable, versioned: containers, CPU/memory, roles, network mode, volumes), run it as one-off tasks or long-running services behind an ALB/NLB, and pick where tasks land with capacity providers: Fargate, Fargate Spot, EC2 Auto Scaling groups, or ECS Managed Instances (AWS-managed EC2 in your account: GPUs, Graviton, any instance type, Reserved Instances and Savings Plans apply, instances refreshed every 14 days; you pay the EC2 price plus a per-instance management fee). Express Mode provisions cluster, ALB, autoscaling and a URL from one image. Comparison with EKS: ECS vs EKS, the compute decision.

Pick it when you run on AWS only, want the fewest moving parts, and do not need Kubernetes CRDs or portability. Avoid it when the org already standardises on Kubernetes tooling (Helm, operators, GitOps controllers).

LimitValueAdjustable
Tasks per service5,000 (1,000 if ECS service discovery / Cloud Map is used)No
Services per cluster5,000No
Containers per task definition10; task definition size 64 KiBNo
Target groups per service5No
Tasks per RunTask call10No
Fargate vCPU quota6 vCPU default on new accounts, raised automatically with usage; plus launch-rate quotasYes
  • Capacity provider strategy. Only one provider may set base; at least one needs weight > 0. A strategy holds Fargate providers or ASG providers, not both, and a service cannot be switched between the two kinds. Changing the strategy on a running service needs --force-new-deployment.
  • Service Connect. Managed Envoy sidecar plus a Cloud Map namespace: round-robin balancing, outlier detection, 2 retries, 15 s default timeout, CloudWatch app metrics, TLS via AWS Private CA (awsvpc only). Budget about 256 CPU units and 64 MiB extra per task. Not supported with CodeDeploy blue/green, standalone tasks or Windows. It replaces AWS App Mesh, which AWS discontinued on 30 Sep 2026.
  • Two roles. The execution role lets the agent pull from ECR, read secrets and write logs. The task role is what your code assumes. ECS Exec also needs ssmmessages:*Channel permissions on the task role (Fargate platform 1.4.0+).
aws ecs create-service --cluster prod --service-name api \
  --task-definition api:42 --desired-count 3 \
  --capacity-provider-strategy capacityProvider=FARGATE,base=2,weight=1 \
                               capacityProvider=FARGATE_SPOT,weight=4 \
  --network-configuration "awsvpcConfiguration={subnets=[subnet-a,subnet-b],securityGroups=[sg-1],assignPublicIp=DISABLED}" \
  --deployment-configuration "deploymentCircuitBreaker={enable=true,rollback=true}" \
  --service-connect-configuration enabled=true,namespace=prod \
  --enable-execute-command

Amazon EKS

What it is. Upstream Kubernetes with an AWS-run control plane (API servers and etcd across three AZs) billed per cluster per hour. A Kubernetes minor version gets 14 months of standard support, then 12 months of extended support at about six times the standard cluster fee. Very large clusters can pre-buy control-plane capacity with Provisioned Control Plane tiers (XL to 8XL, extra hourly fee). Basics of the Kubernetes objects are in Kubernetes; the ECS comparison is in ECS vs EKS.

Pick it when you need the Kubernetes API (operators, CRDs, Helm, GitOps controllers), multi-cloud or hybrid portability, or an existing Kubernetes team. Avoid it for a handful of services on AWS only: ECS costs less to run and operate.

Data planeWho runs nodesPick when
Auto ModeAWS: Karpenter-based scaling, networking, load balancing, DNS, EBS, GPU driversYou want the least node ops. Nodes are immutable (SELinux, read-only root, no SSH or SSM), live 14 days by default (21 days maximum), and cost an extra per-instance fee on top of EC2.
Managed node groupsYou pick AMI type and size; AWS rolls updatesStable fleets, system pools. Defaults: 30 groups per cluster, 450 nodes per group.
Karpenter (self-installed)You run the controller; it launches right-sized EC2 on demand and consolidatesCustom AMIs, daemons needing host access, Spot-heavy fleets, no Auto Mode fee.
Fargate profilesAWS, per podSmall isolated workloads. No DaemonSets, privileged pods, GPUs or Arm; ephemeral storage up to 175 GiB.
  • Pod Identity vs IRSA. Pod Identity needs the eks-pod-identity-agent add-on (built into Auto Mode), a role trusting pods.eks.amazonaws.com with sts:AssumeRole and sts:TagSession, and an association per service account. One role per account-local service account, cross-account via targetRoleArn role chaining, session tags enable ABAC. It works on Linux EC2 nodes only: use IRSA (OIDC provider per cluster) for Fargate pods.
  • Cluster access. Use access entries (authenticationMode API or API_AND_CONFIG_MAP) instead of the aws-auth ConfigMap. Mode changes are one-way.
  • Upgrades. One minor version at a time. As of Oct 2026, 1.34–1.37 are in standard support and 1.31–1.33 in extended. Extended support is on by default: set supportType to STANDARD if you prefer auto-upgrade over a surcharge. In-place upgrades can be rolled back within 7 days.
  • Defaults. 100 clusters per Region (adjustable), 10 Fargate profiles per cluster, 5,000 Pod Identity associations per cluster.
apiVersion: karpenter.sh/v1
kind: NodePool
metadata:
  name: general
spec:
  template:
    spec:
      nodeClassRef: { group: karpenter.k8s.aws, kind: EC2NodeClass, name: default }
      requirements:
        - { key: karpenter.sh/capacity-type, operator: In, values: [spot, on-demand] }
        - { key: kubernetes.io/arch, operator: In, values: [arm64, amd64] }
        - { key: karpenter.k8s.aws/instance-category, operator: In, values: [c, m, r] }
      expireAfter: 720h
  disruption:
    consolidationPolicy: WhenEmptyOrUnderutilized
    consolidateAfter: 1m
  limits: { cpu: 1000 }
aws eks create-addon --cluster-name prod --addon-name eks-pod-identity-agent
aws eks create-pod-identity-association --cluster-name prod \
  --namespace data --service-account s3-reader \
  --role-arn arn:aws:iam::123456789012:role/s3-reader

AWS Fargate

What it is. Serverless capacity for containers: you hand ECS a task (or EKS a pod) with a vCPU and memory size, and AWS finds, patches and isolates the host. Each task runs in its own isolated VM environment and gets its own ENI and security group. It is a capacity provider, not a separate API. Overview and cost trade-off: Fargate vs EC2 launch type.

Pick it when load is variable, the team is small, or tasks are batch/cron. Avoid it for GPUs, privileged containers, host-level devices, or flat 24/7 load where packed EC2 is cheaper. For those gaps use ECS Managed Instances (see ECS) instead of running your own EC2 fleet.

vCPUMemory (GB)Notes
0.250.5, 1, 2Linux only.
0.51–41 GB steps.
12–8Linux or Windows.
2 / 44–16 / 8–301 GB steps.
816–604 GB steps; Linux platform 1.4.0+.
1632–1208 GB steps.
3260, 120 or 244Newest tier; Linux platform 1.4.0+.
  • Storage. 20 GiB ephemeral included, configurable to 200 GiB on ECS (ephemeralStorage.sizeInGiB; 175 GiB for EKS pods), wiped at task stop. For persistence use EFS, or attach one managed EBS volume per task (configuredAtLaunch) on ECS.
  • Billing. vCPU, memory and storage per second from the start of the image pull until the task ends; 1-minute minimum for Linux (5 for Windows). A public IPv4 on the task is billed separately.
  • Cheaper variants. Fargate Spot up to 70% off (Linux, x86 or ARM; ECS only). Linux ARM64 is lower priced than x86 but exists on ECS only. Compute Savings Plans apply, roughly up to 50%.
  • On EKS Fargate pods need private subnets and an ALB/NLB with IP targets, and cannot use DaemonSets, privileged containers, HostPort/HostNetwork, GPUs or Arm.
  • Quotas. New accounts start with a small On-Demand vCPU quota (6 by default) that grows with usage, and launches are rate-limited (burst 100, sustained 20 per second in most Regions). Check the Service Quotas console before a big scale-out test.
{
  "family": "worker",
  "requiresCompatibilities": ["FARGATE"],
  "networkMode": "awsvpc",
  "cpu": "1024", "memory": "2048",
  "runtimePlatform": { "cpuArchitecture": "ARM64", "operatingSystemFamily": "LINUX" },
  "ephemeralStorage": { "sizeInGiB": 50 },
  "executionRoleArn": "arn:aws:iam::123456789012:role/ecsTaskExecutionRole",
  "taskRoleArn": "arn:aws:iam::123456789012:role/worker-task",
  "containerDefinitions": [{
    "name": "app",
    "image": "123456789012.dkr.ecr.us-east-1.amazonaws.com/worker:v7",
    "essential": true,
    "stopTimeout": 120,
    "readonlyRootFilesystem": true
  }]
}

AWS Lambda

What it is. Event-driven functions: you ship a zip or container image, Lambda runs one request per Firecracker-isolated execution environment and bills requests plus duration (1 ms granularity). Since 2026 AWS names the classic model Lambda Event Functions and sells it beside two newer form factors: Web Functions (a port-listening HTTP server, multi-concurrent, active-CPU billing, Node.js, select Regions) and MicroVMs (stateful, VM-isolated sandboxes for untrusted or AI-generated code). Deep dive: Lambda at Scale, what actually runs your Lambda.

Pick it when load is spiky or idle most of the day, each invocation fits in 15 minutes, and state lives outside (DynamoDB, S3, SQS). Avoid it for GPUs, steady 24/7 high-RPS load where a right-sized container is cheaper, or long-lived raw socket servers. For steady load that still wants the Lambda programming model, look at Lambda Managed Instances (functions on EC2 with multi-concurrent environments and EC2 pricing options such as Savings Plans). For multi-day workflows, look at durable functions (checkpoint and replay, up to one year, no compute charge while suspended).

KnobValueNotes
Memory / CPU128–10,240 MBCPU scales with memory; 1 vCPU at 1,769 MB.
Timeout900 sHard cap for classic functions.
Payload6 MB sync, 1 MB async, 200 MB streamed responseAsync was 256 KB until Oct 2025. Streaming is for Node.js managed runtimes (or custom runtime / Lambda Web Adapter).
Package50 MB zip upload, 250 MB unzipped incl. layers, 10 GB image5 layers per function. Env vars 4 KB total. /tmp 512–10,240 MB.
Concurrency1,000 per Region default (new accounts start lower)Each function scales by 1,000 execution environments per 10 s; functions scale independently. Reserved concurrency must leave 100 unreserved.
Reserved / provisionedReserved: free. Provisioned: billed while allocatedProvisioned needs a published version or alias. Autoscale it with Application Auto Scaling.
  • SQS poller. Starts at 5 concurrent batches, adds up to 300 invokes per minute, caps at 1,250 for standard queues. Batch size up to 10,000 with a batching window (FIFO: 10). Set visibility timeout to at least 6x the function timeout.
  • Cold-start toolbox. SnapStart (Java 11+, Python 3.12+, .NET 8+; published versions only; not with provisioned concurrency, EFS, or >512 MB ephemeral storage), provisioned concurrency, arm64, smaller packages, init code at module scope.
  • Cost. arm64 duration is 20% cheaper. Compute Savings Plans cover Lambda duration and provisioned concurrency at up to 17%. Tiered duration discounts apply at very high volume.
# cap blast radius on the DB: limit the SQS mapping, not the function
aws lambda create-event-source-mapping --function-name orders-worker \
  --event-source-arn arn:aws:sqs:us-east-1:123456789012:orders \
  --batch-size 10 --maximum-batching-window-in-seconds 5 \
  --function-response-types ReportBatchItemFailures \
  --scaling-config MaximumConcurrency=50

# warm capacity on an alias (not $LATEST)
aws lambda put-provisioned-concurrency-config --function-name api \
  --qualifier live --provisioned-concurrent-executions 20

Amazon S3

What it is. Regional object store: flat key namespace, designed for 11 nines of durability (Standard, IA, Intelligent-Tiering and Glacier classes spread data across ≥3 AZs), strong read-after-write and list-after-write consistency, effectively unlimited capacity. In 2026 “S3” is four bucket types: general purpose (all classes), directory buckets (Express One Zone), table buckets (managed Iceberg) and vector buckets (similarity search). Deep dives: object model, classes, lifecycle, security, performance.

Pick it when you need cheap durable blobs, a data-lake substrate, static assets behind CloudFront, backups/log archives, or ML datasets. Do not pick it for POSIX semantics or in-place edits (EFS/EBS), or for low-latency random updates (a database).

LimitValueNote
Object size0 B – 50 TBRaised from 5 TB in Dec 2025 (hard ceiling 48.8 TiB = 10,000 parts × 5 GiB). Single PUT max 5 GB; multipart from ~100 MB. Uploads above 5 TB need the S3 Transfer Manager (Java, Python, AWS CLI) with the CRT
Multipart≤10,000 parts5 MiB – 5 GiB per part (last part may be smaller)
Key length1,024 bytesUTF-8 encoded
Request rate3,500 write / 5,500 read per prefix per secondAuto-partitions; transient 503 SlowDown while it scales; no cap on prefixes per bucket
General purpose buckets10,000 per account (default)Soft quota, raisable via Service Quotas up to 1 million; the old “100 buckets” figure is obsolete
Replication SLARTC: 99.99% of objects in 15 minSLA credit is for 99.9% in 15 min per region pair per month; plain replication has no time guarantee
  • Security baseline. New buckets ship with Block Public Access on, ACLs disabled (bucket-owner-enforced) and SSE-S3 default encryption. Add: aws:SecureTransport deny, SSE-KMS plus Bucket Keys where you need key-level audit, a gateway VPC endpoint, versioning plus a noncurrent-version lifecycle rule.
  • Org-wide BPA. Use an AWS Organizations S3 policy (declares all four BPA settings for member accounts) or an SCP that denies s3:PutAccountPublicAccessBlock. An SCP alone cannot turn BPA on; it can only block changes.
  • Net-new capabilities covered in conditional writes, Express One Zone, S3 Tables, S3 Vectors, Object Lock and replication.
# hardened private bucket (us-east-1 needs no LocationConstraint; other regions do)
aws s3api create-bucket --bucket my-bucket --region us-east-1
aws s3api put-public-access-block --bucket my-bucket \
  --public-access-block-configuration BlockPublicAcls=true,IgnorePublicAcls=true,BlockPublicPolicy=true,RestrictPublicBuckets=true
aws s3api put-bucket-versioning --bucket my-bucket --versioning-configuration Status=Enabled
aws s3api put-bucket-encryption --bucket my-bucket --server-side-encryption-configuration \
  '{"Rules":[{"ApplyServerSideEncryptionByDefault":{"SSEAlgorithm":"aws:kms","KMSMasterKeyID":"alias/app-data"},"BucketKeyEnabled":true}]}'
aws s3api put-bucket-lifecycle-configuration --bucket my-bucket --lifecycle-configuration \
  '{"Rules":[{"ID":"hygiene","Status":"Enabled","Filter":{"Prefix":""},
    "NoncurrentVersionExpiration":{"NoncurrentDays":90},
    "AbortIncompleteMultipartUpload":{"DaysAfterInitiation":7}}]}'

Amazon EBS

What it is. Network-attached block storage for EC2 (and containers via the CSI driver). A volume lives in one AZ and is replicated within that AZ only; durability is 99.8–99.9% for gp2/gp3/io1/HDD and 99.999% for io2 Block Express. Snapshots are incremental, regional, S3-backed. Type table and trade-offs: EBS volume types, tiers. Pick it when you need low-latency random I/O for one instance (boot disks, self-managed databases). Need a shared filesystem across AZs? That is EFS/FSx. Need microsecond local scratch? Instance store.

TypeSizeMax IOPSMax MiB/sNotes
gp3up to 64 TiB80,0002,000Baseline 3,000 IOPS / 125 MiB/s included; 500 IOPS per GiB; max IOPS needs ≥160 GiB; 0.25 MiB/s per provisioned IOPS
io2 Block Express4 GiB – 64 TiB256,0004,000Sub-ms latency, 1,000 IOPS per GiB, Multi-Attach, boot OK; Nitro instances only for the top range
io14 GiB – 16 TiB64,0001,00050 IOPS per GiB; legacy, prefer io2
gp2up to 16 TiB16,0002503 IOPS per GiB with burst credits; migrate to gp3
st1 / sc1125 GiB – 16 TiB500 / 250500 / 250HDD, throughput-oriented (1 MiB I/O), no boot, no Multi-Attach
  • Elastic Volumes. Grow, retype or re-provision a live volume; up to four modifications per rolling 24 hours per volume, each must reach completed before the next (older docs said once per 6 hours). You can never shrink a volume. gp2 to gp3 with no IOPS flag preserves at least the old performance.
  • Instance caps bind first. Each instance type has its own EBS IOPS and bandwidth ceiling; non-Nitro instances top out near 32,000 IOPS. Size the instance and the volume together.
  • Multi-Attach (io1/io2 only): one volume to up to 16 Nitro instances in the same AZ. Needs a cluster-aware filesystem or NVMe reservations; plain ext4/XFS corrupts.
  • Encryption is a per-Region account setting (“always encrypt new volumes”); an existing volume cannot be encrypted in place, copy it or snapshot-and-restore. Only snapshots encrypted with a customer managed key can be shared.
  • Snapshots: Archive tier, Recycle Bin, Snapshot Lock, fast snapshot restore and volume initialization rate are in EBS snapshots & io2 Block Express. Quotas worth knowing: 100,000 snapshots per Region, 5 FSR-enabled snapshots per Region (both adjustable).
VOL=$(aws ec2 create-volume --availability-zone us-east-1a --size 100 \
  --volume-type gp3 --iops 6000 --throughput 250 --encrypted \
  --tag-specifications 'ResourceType=volume,Tags=[{Key=Name,Value=db-data}]' \
  --query VolumeId --output text)
aws ec2 wait volume-available --volume-ids "$VOL"
aws ec2 attach-volume --volume-id "$VOL" --instance-id i-0abc1234567890def --device /dev/sdf

# later: grow live, then extend the filesystem (xfs_growfs / resize2fs) inside the guest
aws ec2 modify-volume --volume-id "$VOL" --size 200 --iops 8000

Amazon EFS

What it is. Serverless, elastic NFS v4.1/v4.0 file system (Linux only; Windows clients are unsupported). Regional file systems keep data in ≥3 AZs (99.99% availability SLA); One Zone uses one AZ (99.9%). Designed for 11 nines durability in every class. One mount target per AZ per file system, reachable from EC2, ECS, EKS, Fargate and Lambda (VPC). Context in EFS vs FSx vs Instance Store. Pick it when many Linux hosts need a shared POSIX tree: web content, CI artifacts, home dirs, EKS ReadWriteMany, Lambda needing a big shared model. Not for a database primary (EBS), SMB/Windows (FSx), or object-native pipelines (S3, or S3 Files if tools demand a file view of a bucket).

Throughput modeRegional per-FS max (read / write)BillingUse when
Elastic (recommended)20–60 GiBps / 1–5 GiBps by Region (quota-raisable)Per GiB read/written, no creditsSpiky or unpredictable; average-to-peak under ~5%
Provisioned3–10 GiBps / 1–3.33 GiBpsFixed MiBps-month above the baseline your storage earnsKnown steady load; average-to-peak above ~5%
Bursting3–5 GiBps / 1–3 GiBpsIncluded; baseline 50 KiBps per GiB stored, burst via creditsThroughput should scale with data size; dev/test
  • Storage classes. Standard (SSD, ~sub-ms reads), Infrequent Access (tens of ms, 128 KiB min billing per file), and Archive (cheapest, 90-day minimum, Regional only, requires Elastic throughput and General Purpose mode). One Zone has Standard and IA only. Class is chosen per file system at creation; lifecycle moves files between classes. Details: throughput & Archive guide.
  • Limits. Single file 47.9 TiB; 1 mount target per AZ; 25,000 connections and 10,000 access points per file system; 1,000 file systems per account; per-client cap 1,500 MiBps on Elastic with recent amazon-efs-utils/CSI driver, else 500 MiBps. Elastic default IOPS: 250,000 read (hot data), 90,000 read (cold), 50,000 write, each raisable up to 10x.
  • Max I/O is a legacy performance mode: higher latency, not supported on One Zone or with Elastic throughput. Use General Purpose.
  • Replication is async to a read-only destination (RPO ~15 min for most file systems); fail over by deleting the replication configuration, which takes minutes and makes the replica writable. In-transit encryption needs the mount helper (mount -t efs -o tls); all locks are advisory; nconnect is unsupported.
FS=$(aws efs create-file-system --performance-mode generalPurpose --throughput-mode elastic \
  --encrypted --tags Key=Name,Value=shared-prod --query FileSystemId --output text)
until [ "$(aws efs describe-file-systems --file-system-id "$FS" \
  --query 'FileSystems[0].LifeCycleState' --output text)" = available ]; do sleep 5; done

for SUBNET in subnet-aaa subnet-bbb subnet-ccc; do   # one per AZ
  aws efs create-mount-target --file-system-id "$FS" --subnet-id "$SUBNET" --security-groups sg-0efs123
done
# IA after 30 d, Archive after 90 d, pull back to Standard on first access
aws efs put-lifecycle-configuration --file-system-id "$FS" --lifecycle-policies \
  TransitionToIA=AFTER_30_DAYS TransitionToArchive=AFTER_90_DAYS TransitionToPrimaryStorageClass=AFTER_1_ACCESS

# on the client (amazon-efs-utils): TLS + IAM authorization
sudo mount -t efs -o tls,iam "$FS":/ /mnt/efs

Amazon S3 Glacier (storage classes) & legacy Amazon Glacier

What it is. Two different things share the name. (1) The S3 Glacier storage classes — Instant Retrieval, Flexible Retrieval, Deep Archive — are ordinary S3 objects with a different class (GLACIER_IR, GLACIER, DEEP_ARCHIVE), same 11 nines across ≥3 AZs, same buckets, KMS, IAM and lifecycle. (2) The original Amazon Glacier vault/archive service has been closed to new customers since 2025-12-15; existing vaults keep working and no migration is forced. Use the S3 classes for anything new. Deeper table: Glacier: archives, vaults & retrieval tiers; restore planning in Glacier restore guide.

ClassAccessMin durationGotcha
Glacier Instant RetrievalMilliseconds, no restore step90 days128 KB minimum billable object size
Glacier Flexible RetrievalRestore first: Expedited 1–5 min, Standard 3–5 h, Bulk 5–12 h (Bulk has no retrieval fee)90 days~40 KB per-object overhead (32 KB at Glacier rate + 8 KB at Standard rate)
Glacier Deep ArchiveRestore first: Standard within 12 h, Bulk within 48 h; no Expedited180 daysSame ~40 KB overhead; early delete or overwrite is billed pro rata
  • Restore model. RestoreObject creates a temporary Standard copy for the number of days you request (expiry rounds up to midnight UTC) while the archived object stays; you pay for both. S3 Batch Operations lifts restore rate: Standard typically starts in about 30 min (Flexible) and about 9 h (Deep Archive) instead of 3–5 h and 12 h. Expedited can need provisioned capacity units for guaranteed throughput, and large objects (250 MB+) take longer.
  • Intelligent-Tiering archive tiers use the same retrieval times but restore differently: no Days, the object returns to Frequent Access, and Standard retrieval is free.
  • Compliance. New designs use S3 Object Lock. Legacy Vault Lock: initiate-vault-lock installs a policy (≤20 KB, one per vault) in InProgress state; you have 24 hours to test, then complete-vault-lock makes it permanently immutable, otherwise it is removed. There is no governance mode in Vault Lock (that exists only in S3 Object Lock).
  • Legacy limits. Archive up to 40,000 GB via multipart (10,000 parts x 4 GB); 1,000 vaults per account. S3-class objects follow S3 limits (up to 50 TB).
aws s3api put-bucket-lifecycle-configuration --bucket backups --lifecycle-configuration '{
  "Rules":[{"ID":"archive","Status":"Enabled",
    "Filter":{"ObjectSizeGreaterThan":131072},
    "Transitions":[{"Days":30,"StorageClass":"GLACIER_IR"},{"Days":365,"StorageClass":"DEEP_ARCHIVE"}],
    "Expiration":{"Days":2555}}]}'

aws s3api restore-object --bucket backups --key 2018/old.tar.gz \
  --restore-request '{"Days":7,"GlacierJobParameters":{"Tier":"Bulk"}}'
# poll: ongoing-request="false" plus an expiry-date means the temporary copy is readable
aws s3api head-object --bucket backups --key 2018/old.tar.gz --query Restore

DynamoDB

Serverless key-value and document store: you model for access patterns up front, and in return get single-digit-ms reads and writes at any table size, with no instances to size or patch. Deep dive on keys, GSIs and single-table design: DynamoDB: Serverless NoSQL.

  • Pick it when every query is expressible as a key lookup or key-range Query, traffic is spiky or huge, and you want multi-Region active-active without running a cluster.
  • Avoid it for ad-hoc joins, unknown access patterns, or heavy analytics (use Aurora, or export/zero-ETL to Athena, Redshift or OpenSearch).
  • On-demand is the default recommendation; move steady, forecastable tables to provisioned plus Auto Scaling. Reserved capacity (provisioned, Standard class, single Region) and Database Savings Plans are the commitment options. The Standard-IA table class cuts storage cost when storage dominates the bill.
  • Global tables come in two modes: MREC (default, async, last-writer-wins, typically under a second) and MRSC (sync, strongly consistent reads from any replica, exactly three Regions).
  • Native vector search (SearchVectors on a vector index) is GA, so embeddings can live next to the items; see vector store options.
ItemValueNote
Max item size400 KBIncludes attribute names; park blobs in S3, keep the key
Read units (per 4 KB)0.5 eventual, 1 strong, 2 transactionalSame ratios for RCU and RRU
Write units (per 1 KB)1 standard, 2 transactionalRounded up per item
Per-partition ceiling3,000 RCU / 1,000 WCUA hot key throttles even with spare table capacity
Per-table default (on-demand and provisioned)40,000 read / 40,000 write unitsAdjustable quota; account cap 80,000 applies to provisioned only
Indexes per table20 GSI (default quota), 5 LSILSI must be created with the table
Tables per Region2,500 initialRaisable toward 10,000 via account team
TransactWriteItems100 actions, 4 MB aggregateSame Region and account only
PITR window1 to 35 days (configurable)Per-second restore granularity
Streams retention24 hoursLonger replay: Kinesis Data Streams destination
# On-demand table with one GSI and deletion protection
aws dynamodb create-table --table-name orders \
  --attribute-definitions AttributeName=PK,AttributeType=S AttributeName=SK,AttributeType=S \
      AttributeName=GSI1PK,AttributeType=S AttributeName=GSI1SK,AttributeType=S \
  --key-schema AttributeName=PK,KeyType=HASH AttributeName=SK,KeyType=RANGE \
  --global-secondary-indexes 'IndexName=GSI1,KeySchema=[{AttributeName=GSI1PK,KeyType=HASH},{AttributeName=GSI1SK,KeyType=RANGE}],Projection={ProjectionType=ALL}' \
  --billing-mode PAY_PER_REQUEST --deletion-protection-enabled

# Turn an EMPTY table into an MRSC global table: replica in us-east-2, witness in us-west-2
aws dynamodb update-table --table-name orders \
  --replica-updates '[{"Create":{"RegionName":"us-east-2"}}]' \
  --global-table-witness-updates '[{"Create":{"RegionName":"us-west-2"}}]' \
  --multi-region-consistency STRONG

ElastiCache (Valkey / Redis OSS / Memcached)

Managed in-memory cache with sub-millisecond reads for sessions, hot reads, counters, leaderboards and rate limits. Valkey is the recommended engine for new work: the cheapest per unit, the only one still gaining features (vector and full-text search, hash-field TTL, optional durability), and wire-compatible with Redis OSS 7.2. Redis OSS stops at 7.1 on ElastiCache. Engine background is in the Redis / Valkey card; the older Redis-vs-Memcached comparison is at ElastiCache: Redis vs Memcached.

  • Serverless — no node sizing, Multi-AZ always on, billed per GB-hour stored plus ECPUs (1 ECPU per KB transferred, more for CPU-heavy commands). Minimum metered storage is 100 MB on Valkey versus 1 GB on Redis OSS and Memcached. Default ceilings are 5 TB and 15M ECPU/s; set --cache-usage-limits to cap spend (the cache then evicts or rejects writes at the cap).
  • Node-based — pick the node type, shards and replicas for steady load and Reserved Nodes. Cluster mode enabled: up to 500 shards but the default is 90 nodes per cluster (raise via quota request); up to 5 replicas per shard. Reserved Redis OSS nodes apply to Valkey nodes, and Valkey is priced 20% (node) and 33% (serverless) below Redis OSS.
  • Durability is now optional on Valkey 9.0+ (node-based, cluster mode and Multi-AZ on, Graviton nodes): a Multi-AZ transactional log with synchronous writes (zero acknowledged-write loss, single-digit-ms writes, extra charge) or asynchronous writes (microsecond writes, up to 10 s at risk).
  • Security — VPC only; TLS and RBAC; IAM auth (Valkey 7.2+, Redis OSS 7.0+, TLS required, token valid 15 min, connection cut after 12 h unless re-authenticated). At-rest encryption cannot be changed after creation. In-transit encryption can be turned on later for Valkey/Redis 7+ via preferred then required mode.
  • Cross-Region — Global Datastore: one writable primary cluster, async read-only secondaries, manual promotion for DR.
NeedPickWhy
Disposable cache in front of a DBElastiCache Valkey, durability offCheapest; data is reconstructable
Spiky or unknown load, no opsElastiCache ServerlessScales on demand; pay for ECPU and GB-hours
Redis-compatible primary storeMemoryDB, or ElastiCache Valkey 9 sync durabilityMulti-AZ log; compare features, SLA and cost for your Region
Microsecond reads in front of DynamoDB onlyDAXAPI-compatible, no cache-aside code
Giant, simple, multi-threaded string cacheMemcachedNo replication or persistence, so node loss loses its shard
# Serverless Valkey, capped at 20 GB and 50k ECPU/s
aws elasticache create-serverless-cache --serverless-cache-name web-cache \
  --engine valkey --major-engine-version 8 \
  --subnet-ids subnet-0aaa subnet-0bbb --security-group-ids sg-0abc \
  --cache-usage-limits 'DataStorage={Maximum=20,Unit=GB},ECPUPerSecond={Maximum=50000}'

# Node-based, cluster mode enabled: 3 shards x (1 primary + 1 replica), TLS, Multi-AZ
# (for Valkey 9.x use engine-version 9.0 and default.valkey9.cluster.on)
aws elasticache create-replication-group --replication-group-id app-cache \
  --replication-group-description "App cache" --engine valkey --engine-version 8.2 \
  --cache-parameter-group-name default.valkey8.cluster.on \
  --cache-node-type cache.r7g.large --num-node-groups 3 --replicas-per-node-group 1 \
  --automatic-failover-enabled --multi-az-enabled \
  --transit-encryption-enabled --at-rest-encryption-enabled \
  --cache-subnet-group-name app-cache-subnets --security-group-ids sg-0abc \
  --snapshot-retention-limit 7

Redis / Valkey (the engine)

Redis and Valkey are in-memory data-structure servers speaking the RESP protocol; ElastiCache and MemoryDB run Valkey and Redis OSS for you, and self-hosting on EC2 is rarely worth the HA, snapshot and patching burden. Service-level choices (serverless, node types, durability, quotas) are in the ElastiCache card; this card is the engine behavior you must understand to design with it.

  • Licensing lineage — Redis was BSD through 7.2.4. In March 2024 Redis moved to dual RSALv2/SSPLv1 (source-available), and the Linux Foundation forked Valkey from 7.2.4 under BSD-3-Clause with vendor-neutral governance (AWS is a major contributor). Redis 8 (2025) added AGPLv3 as a third option. For AWS-managed use none of this reaches you except that new engine features ship in Valkey.
  • Execution model — commands run on one thread per shard (I/O threads offload network work), so each command is atomic and one slow command (KEYS *, huge HGETALL, long Lua script) stalls every client on that shard. Use SCAN and bounded ranges.
  • Sharding — cluster mode splits 16,384 hash slots across primaries. Multi-key commands need all keys in one slot (CROSSSLOT otherwise); force it with a hash tag such as {user:42}:cart. Cluster clients must follow MOVED redirects, so use a cluster-aware client against the configuration endpoint.
  • Structures — strings, hashes, lists, sets, sorted sets, bitmaps, HyperLogLog, geo, streams with consumer groups. Valkey 8.1+ adds a native Bloom filter type; 9.0 adds per-field hash TTL.
  • Pub/Sub is fire-and-forget: a disconnected subscriber misses messages. Use Streams with consumer groups (XACK, XAUTOCLAIM) when you need replay or at-least-once delivery.
  • Persistence — RDB snapshots (fork plus copy-on-write, so budget memory headroom) and a replica; true durability needs MemoryDB or ElastiCache Valkey 9 durability. Single-key SET key token NX PX ttl is a fine lease, but not a correctness-grade lock without fencing tokens.
from redis.cluster import RedisCluster   # valkey-py offers the same API as valkey.cluster.ValkeyCluster

rc = RedisCluster(host="clustercfg.app-cache.xxxxxx.use1.cache.amazonaws.com",
                  port=6379, ssl=True, decode_responses=True)

# Hash tag {user:42}: the braces make both keys hash to one slot, so multi-key calls avoid CROSSSLOT
rc.mset({"{user:42}:profile": "...", "{user:42}:prefs": "..."})
print(rc.mget("{user:42}:profile", "{user:42}:prefs"))

# Lease with compare-and-delete release (single key, so cluster-safe)
UNLOCK = "if redis.call('get',KEYS[1])==ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end"
if rc.set("lock:job-7", "tok-abc", nx=True, px=10000):
    try:
        pass  # critical section; keep it shorter than the lease
    finally:
        rc.eval(UNLOCK, 1, "lock:job-7", "tok-abc")

RDS & Aurora

RDS runs the upstream engines (PostgreSQL, MySQL, MariaDB, Oracle, SQL Server, Db2) on managed hosts. Aurora is the MySQL- and PostgreSQL-compatible engine on a shared, distributed storage layer. Replication, failover and storage internals: RDS vs Aurora. Multi-Region DR numbers: HA vs DR.

  • Pick Aurora for production MySQL/PostgreSQL that needs fast failover, many readers, Global Database, Serverless v2 or Limitless. Pick RDS for Oracle, SQL Server or Db2, for a feature only the upstream engine has, or a small steady database where the cheapest managed option wins.
  • Aurora Serverless v2 now scales from 0 to 256 ACUs (about 2 GiB of memory per ACU) on current platform versions. Minimum 0 enables auto-pause after 300 s to 86,400 s idle; a minimum of 0.5 or more never pauses and keeps billing compute. Resume adds latency to the first connection after a pause, so it suits dev, test and sporadic workloads rather than latency-critical paths.
  • Beyond one writer: Aurora PostgreSQL Limitless (sharding) and Aurora DSQL (serverless, active-active, multi-Region) are compared in Scaling SQL beyond one writer.
  • Storage — Aurora volumes grow to 256 TiB on recent engine versions (PostgreSQL 17.5+, 16.9+, 15.13+; MySQL 3.10+) and 128 TiB on earlier ones. I/O-Optimized removes per-I/O charges and pays off when I/O is roughly 25% or more of total Aurora spend; otherwise Standard is cheaper.
  • Connections — RDS Proxy pools and multiplexes connections (reuse per transaction), supports IAM auth and shortens failover; session-state changes cause pinning and erase the multiplexing gain. Default for Lambda or any bursty client fleet.
  • Analytics — zero-ETL replicates Aurora MySQL, Aurora PostgreSQL and DynamoDB into Redshift without a pipeline; see the Redshift card. Commitments — Reserved Instances, plus Database Savings Plans (1-year, cross-engine and cross-Region, covers serverless).
TopologyFailover (typical)ReadersNote
RDS Multi-AZ instance60–120 s (CNAME flip)Standby is not readableHA only; add read replicas separately
RDS Multi-AZ DB clusterUnder 35 s2 readable standbysMySQL and PostgreSQL
Aurora clusterTens of seconds with a healthy replicaUp to 15, one shared volumeAWS guidance ranges from under 30 s to under 120 s; promote by tier, retry in the client
RDS read replicasManual promote15 (MySQL, MariaDB, PostgreSQL); 5 (Oracle, SQL Server)Async, can be cross-Region
Aurora Global DatabaseSwitchover (planned) or failover (unplanned)Secondary Regions read-onlyCross-Region lag typically under 1 s; one writer Region
# Aurora PostgreSQL Serverless v2 that auto-pauses (pin a current minor version in PG_VERSION)
PG_VERSION=16.9
aws rds create-db-cluster --db-cluster-identifier app-pg --engine aurora-postgresql \
  --engine-version "$PG_VERSION" --master-username dbadmin --manage-master-user-password \
  --vpc-security-group-ids sg-0abc --db-subnet-group-name app-pg-subnets \
  --storage-encrypted --enable-iam-database-authentication --deletion-protection \
  --serverless-v2-scaling-configuration MinCapacity=0,MaxCapacity=16,SecondsUntilAutoPause=600
aws rds create-db-instance --db-instance-identifier app-pg-writer \
  --db-cluster-identifier app-pg --engine aurora-postgresql --db-instance-class db.serverless

# RDS Proxy in front of it (Secrets Manager credentials, IAM auth required, TLS required)
aws rds create-db-proxy --db-proxy-name app-pg-proxy --engine-family POSTGRESQL \
  --auth 'AuthScheme=SECRETS,SecretArn=arn:aws:secretsmanager:us-east-1:123456789012:secret:app-pg-user,IAMAuth=REQUIRED' \
  --role-arn arn:aws:iam::123456789012:role/rds-proxy-secrets \
  --vpc-subnet-ids subnet-0aaa subnet-0bbb --require-tls
aws rds register-db-proxy-targets --db-proxy-name app-pg-proxy --db-cluster-identifiers app-pg

Redshift

Columnar, massively parallel data warehouse for scans and aggregations over billions of rows, with a managed storage layer (RMS on S3) so compute and storage scale separately. It is not an OLTP database. Architecture and the leader/compute-node model: Redshift: Columnar MPP.

  • Redshift Serverless is the default entry point. Capacity is measured in RPUs (1 RPU = 16 GB memory); base capacity starts at 4 RPUs. Compute is billed per second with a 60-second minimum charge and nothing when no queries run; storage is billed separately. Concurrency scaling and Spectrum-style S3 queries are included. Cap spend with maximum RPU-hours (daily, weekly or monthly, with log, alert or turn-off actions) and a max-capacity setting, or set a price-performance target and let AI-driven scaling tune capacity.
  • Provisioned suits steady, high-utilization warehouses and Reserved Nodes. RA3 uses managed storage and Spectrum for S3 queries. RG (Graviton, launched May 2026 as xlarge and 4xlarge; rg.large and rg.12xlarge added Jul 2026) has a built-in data-lake engine, so S3 and Iceberg queries no longer use the Spectrum fleet or its per-TB charge. DC2 is a legacy node family: new designs should pick RA3, RG or Serverless.
  • Concurrency Scaling (provisioned) adds transient clusters; you earn 1 free hour per 24 hours the main cluster runs (credits accumulate up to 30 hours), default cap is 10 scaling clusters. Manual WLM is limited to 50 total query slots; Auto WLM is the recommended mode.
  • Lakehouse — query Apache Iceberg tables in the Glue Data Catalog and write them too (INSERT, UPDATE, DELETE, MERGE) on S3 or S3 Tables, so Athena and EMR see the same data.
  • Ingest — COPY from S3 (Parquet), streaming ingestion from Kinesis Data Streams or MSK into materialized views (no S3 staging), zero-ETL from Aurora MySQL, Aurora PostgreSQL and DynamoDB, and live data sharing across clusters, accounts and Regions without copying (consumer pays compute).
  • Limits worth knowing — 1,600 columns per table; 9,900 schemas per database; up to 128 RA3 nodes per cluster; tables per cluster depend on node type (for example 20,000 for multi-node ra3.xlplus, 200,000 for ra3.4xlarge). Serverless: 200,000 tables, 100 databases and 2,000 connections per namespace/workgroup. Python UDFs are being retired after 2026-06-30; use SQL or Lambda UDFs.
# Serverless warehouse: private, 8 RPU base, capped at 64 RPU, admin password managed in Secrets Manager
aws redshift-serverless create-namespace --namespace-name analytics \
  --admin-username dbadmin --manage-admin-password
aws redshift-serverless create-workgroup --workgroup-name analytics-wg --namespace-name analytics \
  --base-capacity 8 --max-capacity 64 \
  --subnet-ids subnet-0aaa subnet-0bbb --security-group-ids sg-0abc \
  --no-publicly-accessible --enhanced-vpc-routing
-- Co-locate the big fact table with its biggest join partner; sort on the common filter column
CREATE TABLE sales.orders (
  order_id BIGINT, customer_id BIGINT, order_ts TIMESTAMP, amount DECIMAL(12,2)
) DISTSTYLE KEY DISTKEY (customer_id) SORTKEY (order_ts);

COPY sales.orders FROM 's3://my-bucket/orders/dt=2026-10-19/'
IAM_ROLE 'arn:aws:iam::123456789012:role/redshift-copy' FORMAT AS PARQUET;

Amazon VPC — Design Checklist & Endpoint Types

A VPC is your regional, software-defined network: CIDR, per-AZ subnets, route tables, gateways, and layered filters (SG, NACL, Network Firewall). Deep dives live at VPC Anatomy, Route Tables & NAT Economics, SG vs NACL and Peering vs TGW vs PrivateLink; this card is the quota-and-currency cheat sheet. Four decisions dominate: CIDR plan (immutable per subnet), AZ layout, egress path, and how private traffic reaches AWS APIs and other VPCs.

VPC endpoint typeReachesMechanismCost model
GatewayS3, DynamoDB onlyRoute-table prefix-list target; not PrivateLink; VPC-local onlyNo charge
InterfaceAWS services, NLB-fronted endpoint services, partner SaaSENI per AZ + private DNS; cross-Region supported for NLB-based services and a list of AWS servicesPer AZ-hour + per GB
Gateway Load BalancerAppliance fleet behind a GWLBRoute-table target, GENEVEPer hour + per GB
ResourceA single DB, IP or DNS name in another VPC or on-prem (no load balancer needed)Resource gateway + resource configuration; works over DX/VPNSee VPC pricing page
Service networkMany VPC Lattice services and resources through one endpointOne ENI set; reachable from on-prem over DX/VPNSee VPC pricing page
  • NAT modes (2025+). Zonal NAT gateway (default) lives in one public subnet and one AZ; one per AZ is the HA pattern. Regional NAT gateway (--availability-mode regional) is one VPC-level resource that expands to AZs where your ENIs exist (up to ~60 min to expand), needs no public subnet, auto-manages EIPs in automatic mode, and does not support private NAT. Keep zonal for private NAT or when you need fixed per-AZ IPs.
  • Public IPv4 is billed hourly for every address, attached or idle, since 2024-02-01 (BYOIP exempt). Audit with Public IP Insights; use IPv6 + NAT64/DNS64, ALB-only exposure, or Session Manager instead of public IPs.
  • VPC Block Public Access blocks IGW/EIGW paths account-wide per Region (bidirectional, or ingress-only which still permits NAT/EIGW egress) with per-VPC/subnet exclusions. It is a guardrail SGs cannot replace.
# One NAT for every AZ, free S3 path, 1-minute flow logs to S3
aws ec2 create-nat-gateway --vpc-id vpc-0abc --availability-mode regional
aws ec2 create-vpc-endpoint --vpc-id vpc-0abc --vpc-endpoint-type Gateway \
  --service-name com.amazonaws.us-east-1.s3 --route-table-ids rtb-0aaa rtb-0bbb rtb-0ccc
aws ec2 create-flow-logs --resource-type VPC --resource-ids vpc-0abc --traffic-type ALL \
  --log-destination-type s3 --log-destination arn:aws:s3:::central-flow-logs/vpc/ \
  --max-aggregation-interval 60

Amazon API Gateway — REST vs HTTP vs WebSocket Limits

Managed API front door: auth, throttling, transformation and routing to Lambda, VPC-private backends or AWS services. The flavor choice is feature-versus-cost (feature table and a CloudFormation snippet are at API Gateway — REST, HTTP & WebSocket); this card pins down the limits that decide it. Simple Lambda-only endpoints are often better served by a Lambda Function URL, GraphQL by AppSync, containers behind a VPC by an ALB.

Limit / featureREST APIHTTP APIWebSocket API
Integration timeout50 ms–29 s default; raisable above 29 s by quota request for Regional and private APIs only (may cost account throttle quota). Response streaming up to 15 min30 s max, fixed29 s
Payload10 MB10 MB128 KB message, 32 KB frame
Endpoint typesEdge-optimized, Regional, PrivateRegional onlyRegional
WAF / API keys / usage plans / validation / cache / canary / resource policyYesNone of these—
JWT authorizerNo (use Lambda authorizer)Native—
Private backendsVPC link to NLB or ALBVPC link to ALB, NLB or Cloud MapHTTP/Lambda
mTLS on custom domainYesYes—
  • 29 s is no longer a universal hard cap. It is the default for REST, and Regional/private REST APIs can be raised by quota request; edge-optimized REST and HTTP APIs cannot. Long work still belongs behind 202 + queue, Step Functions, or streaming.
  • Direct service integrations on HTTP APIs are first-class subtypes (SQS-SendMessage, EventBridge-PutEvents, Kinesis-PutRecord, StepFunctions-StartExecution and -StartSyncExecution, AppConfig-GetConfiguration), all payloadFormatVersion 1.0. REST uses VTL mapping templates instead.
  • Edge-optimized endpoints sit behind a CloudFront distribution that API Gateway owns and you cannot configure. For your own cache policy, WAF at the edge or origin-lock, use a Regional endpoint plus your own distribution, then disable the default execute-api endpoint (--disable-execute-api-endpoint, REST and HTTP).
# HTTP API: JWT auth + direct SQS write, no Lambda in the path
aws apigatewayv2 create-api --name events --protocol-type HTTP \
  --cors-configuration '{"AllowOrigins":["https://app.example.com"],"AllowMethods":["POST"],"AllowHeaders":["content-type","authorization"]}'
aws apigatewayv2 create-authorizer --api-id abcd1234 --name oidc --authorizer-type JWT \
  --identity-source '$request.header.Authorization' \
  --jwt-configuration Audience=my-app,Issuer=https://idp.example.com/
aws apigatewayv2 create-integration --api-id abcd1234 --integration-type AWS_PROXY \
  --integration-subtype SQS-SendMessage --payload-format-version 1.0 \
  --credentials-arn arn:aws:iam::111122223333:role/apigw-sqs-send \
  --request-parameters '{"QueueUrl":"https://sqs.us-east-1.amazonaws.com/111122223333/events","MessageBody":"$request.body"}'

Amazon CloudFront — Origin Protection, Edge Compute & Current Quotas

Global CDN: edge and regional caches, TLS termination, WAF/Shield attachment, and edge compute. Behaviors, policies and the Functions-vs-Lambda@Edge basics are in CloudFront — the Edge CDN; this card carries current quotas, the origin-lockdown options, and what changed recently (VPC origins, KeyValueStore, tag invalidation, flat-rate plans).

OriginLock it to CloudFront withNotes
S3 bucketOrigin Access Control (OAC), bucket policy on cloudfront.amazonaws.com + AWS:SourceArnOAC supports SSE-KMS, PUT/POST/DELETE and Regions launched after Dec 2022; OAI is legacy
Lambda function URL, MediaStore, MediaPackage v2OACSigns origin requests with SigV4
ALB, NLB or EC2 in a private subnetVPC originNo public IP or IGW needed; shareable via RAM; no extra CloudFront fee
Public custom originSecurity group on the com.amazonaws.global.cloudfront.origin-facing prefix list + secret origin headerPrefix list is IPv4; an IPv6 list also exists
  • Invalidation by cache tag now exists. Set CacheTagConfig on the distribution, have the origin return tags in a header (S3: x-amz-meta-cache-tag), then --paths "#product:123". Up to 50 tags per object. The old "no purge by tag" advice is stale; versioned filenames remain the cheapest strategy.
  • Pricing models. Pay-as-you-go, or flat-rate plans (Free/Pro/Business/Premium, one distribution each, WAF, DDoS, Route 53, logging and edge compute bundled, no overage; a WAF web ACL must stay attached). A Security Savings Bundle gives about 30% off pay-as-you-go spend plus WAF credits but does not apply to flat-rate plans. Origin Shield is billed per request reaching it, not per GB.
  • Client IP. CloudFront appends the viewer IP to X-Forwarded-For; with a client-supplied header the real client is the first entry only if no untrusted proxy precedes it, so treat it as spoofable. Origin failover (origin groups) triggers only for GET, HEAD, OPTIONS and is stateless: every request tries the primary first.
  • Function URI rewrites change the path sent to the origin but not which behavior or origin was selected.
// CloudFront Function, runtime cloudfront-js-2.0 (required for KeyValueStore)
import cf from 'cloudfront';
const kvs = cf.kvs();                    // fails if no store is associated with the function
async function handler(event) {
  const req = event.request;
  const seg = req.uri.split('/');         // /blog/... -> value stored under "blog"
  try { seg[1] = await kvs.get(seg[1]); req.uri = seg.join('/'); } catch (e) {}
  return req;                             // change KVS value, no redeploy
}
aws cloudfront create-invalidation --distribution-id E1234ABCD --paths '/index.html' '#product:123'

Amazon Route 53 — Routing, Resolver & Recovery Tooling

Authoritative DNS, domain registration, health checks, and (as Route 53 VPC Resolver, formerly Resolver) the recursive resolver inside every VPC. Record types, routing policies and a failover Terraform sample are at Route 53 — DNS & Routing Policies and Health Checks & Failover Routing. This card covers the quotas and the resilience toolbox, where choosing the wrong primitive is the classic design miss.

NeedToolMechanism and catch
Automatic multi-Region failoverFailover/latency records + health checksData-plane; recovery = TTL + interval × threshold. Alias records have no TTL of their own: ELB targets use a fixed 60 s
Controlled, human-triggered Region cutoverARC routing controlsOn/off switches on a five-endpoint cluster, wired to health checks of type RECOVERY_CONTROL; use the data-plane API, not the console, during an event; safety rules prevent turning every cell off
Evacuate one AZARC zonal shift / zonal autoshiftALB, NLB, EC2 Auto Scaling groups, EKS. Must be enabled per load balancer (off by default); ALB works with cross-zone on or off. Moves new connections only (DNS update); manual shift lasts up to 72 h; autoshift is AWS-initiated with weekly practice runs
Keep editing DNS during a us-east-1 outageAccelerated recovery (public zones)Zone copy kept in us-west-2, control plane fails over within 60 min; must be enabled beforehand; in-flight changes can be stranded
Audit failover capacityARC readiness checkClosed to new customers (existing users unaffected); routing controls, zonal shift/autoshift and Region switch remain supported
  • Alias records to AWS resources carry no query charge, work at the apex, and take no TTL. Use them for ALB, NLB, CloudFront, API Gateway, S3 website and other Route 53 records.
  • DNS Firewall filters VPC Resolver queries against AWS-managed or custom domain lists; DNS Firewall Advanced adds DGA and DNS-tunneling detection. Security groups never touch Resolver traffic, so this is the only filter at that layer.
  • Route 53 Global Resolver gives remote and branch clients an anycast, encrypted-DNS resolver for public and private zones. It launched in preview in Nov 2025 and has been generally available since March 2026 (30 Regions, IPv4 and IPv6 DNS traffic).
# 90/10 weighted canary; alias targets omit TTL (Z35SXDOTRQ7X7K = us-east-1 ALB zone ID)
aws route53 change-resource-record-sets --hosted-zone-id Z0ABCDEF123 --change-batch '{
  "Changes": [
    {"Action":"UPSERT","ResourceRecordSet":{"Name":"api.example.com","Type":"A","SetIdentifier":"blue","Weight":90,
      "AliasTarget":{"HostedZoneId":"Z35SXDOTRQ7X7K","DNSName":"blue-1234567890.us-east-1.elb.amazonaws.com","EvaluateTargetHealth":true}}},
    {"Action":"UPSERT","ResourceRecordSet":{"Name":"api.example.com","Type":"A","SetIdentifier":"green","Weight":10,
      "AliasTarget":{"HostedZoneId":"Z35SXDOTRQ7X7K","DNSName":"green-0987654321.us-east-1.elb.amazonaws.com","EvaluateTargetHealth":true}}}]}'

# Drain one AZ for two hours (zonal shift is off by default on each ALB)
aws elbv2 modify-load-balancer-attributes --load-balancer-arn arn:aws:elasticloadbalancing:us-east-1:111122223333:loadbalancer/app/web/50dc6c495c0c9188 \
  --attributes Key=zonal_shift.config.enabled,Value=true
aws arc-zonal-shift start-zonal-shift --resource-identifier arn:aws:elasticloadbalancing:us-east-1:111122223333:loadbalancer/app/web/50dc6c495c0c9188 \
  --away-from use1-az1 --expires-in 2h --comment "bad deploy in az1"

IAM, Identity Center, SCP/RCP & OIDC Federation

What it is. IAM answers "may this principal do this action on this resource under these conditions?" for every AWS API call. It is free, global, and eventually consistent. Around it sit IAM Identity Center (workforce SSO), Organizations SCPs/RCPs (account-tree guardrails), STS (temporary credentials) and Access Analyzer (external/unused-access findings). Deep dive on evaluation and STS: Policy Evaluation Logic, STS & Instance Profiles; SCP basics: Organizations & SCPs.

Pick it when. Humans → Identity Center (no IAM users). Workloads → roles (instance profile, Pod Identity/IRSA, IAM Roles Anywhere for off-AWS, OIDC for CI). Guardrails across accounts → SCP (limits principals) plus RCP (limits resources). Delegated role creation → permission boundary.

ControlLimitsGrants?Scope / catch
SCPPrincipals in member accountsNoNot applied to the management account; does not affect service-linked roles
RCPResources in member accounts, regardless of caller (including outside the org)NoSubset of services only (about 60 at last check, including S3, STS, KMS, SQS, Secrets Manager, ECR, DynamoDB, CloudWatch Logs, Cognito and OpenSearch; see the Organizations RCP service list); not management account, service-linked roles or AWS managed KMS keys
Permission boundaryOne user/roleNoIntersects with identity policy; does not cap a resource policy that names the session/user ARN directly
Session policyOne STS sessionNoPassed at AssumeRole/federation; cannot exceed the role
Evaluation (single account, in order; first terminal result wins)
  1. Any explicit Deny in SCP / RCP / resource / identity / boundary / session  --> DENY
  2. RCP allows?            no --> DENY   (RCPFullAWSAccess is auto-attached, cannot be detached)
  3. SCP allows?            no --> DENY   (FullAWSAccess is the default SCP)
  4. Resource-based policy grants the principal?  (see exception below)
  5. Identity-based policy allows?   no --> DENY
  6. Permission boundary allows?     no --> DENY
  7. Session policy allows (if session)?  no --> DENY
  8. ALLOW
  • Resource-policy exception. Same account, a resource policy that names an IAM user ARN or an assumed-role session ARN grants directly: an implicit deny in the boundary or identity policy does not block it. A policy naming the role ARN is still capped by boundary and session policy. KMS key policies and role trust policies must always allow explicitly.
  • Identity Center. Use an organization instance (management account or delegated admin); account instances are single-account only. A permission set assigned to a user/group in an account is provisioned as an IAM role (AWSReservedSSO_<name>_<hash>). Identity source: built-in directory, Active Directory, or external IdP (Okta, Entra ID, Google) with SCIM. Permission-set session 1–12 h (default 1 h); access-portal session 15 min–90 days. Multi-Region replication (2026) needs a multi-Region customer-managed KMS key (see KMS). Free.
  • OIDC federation. CI/CD assumes a role with sts:AssumeRoleWithWebIdentity; no stored keys. For GitHub's provider IAM rejects a trust policy lacking a non-wildcard token.actions.githubusercontent.com:sub condition. Pin aud and sub to org/repo/branch.
  • Root hygiene. Centralized root access management lets the management or delegated-admin account delete member-account root credentials and run privileged root tasks via sts:AssumeRoot. Once root credentials management is enabled, new Organizations accounts are created without root credentials.
{
  "Version": "2012-10-17",
  "Statement": [{
    "Effect": "Allow",
    "Principal": { "Federated": "arn:aws:iam::111122223333:oidc-provider/token.actions.githubusercontent.com" },
    "Action": "sts:AssumeRoleWithWebIdentity",
    "Condition": {
      "StringEquals": { "token.actions.githubusercontent.com:aud": "sts.amazonaws.com" },
      "StringLike":   { "token.actions.githubusercontent.com:sub": "repo:my-org/my-repo:ref:refs/heads/main" }
    }
  }]
}

An RCP that makes every S3 bucket in member accounts unreachable from outside the organization, even if a bucket policy says otherwise (AWS services calling on your behalf are exempted):

{
  "Version": "2012-10-17",
  "Statement": [{
    "Sid": "DenyS3ExternalAccess",
    "Effect": "Deny",
    "Principal": "*",
    "Action": "s3:*",
    "Resource": "*",
    "Condition": {
      "StringNotEqualsIfExists": { "aws:PrincipalOrgID": "o-exampleorgid" },
      "BoolIfExists": { "aws:PrincipalIsAWSService": "false" }
    }
  }]
}
QuotaDefaultAdjustable
Roles per account1,000Up to 10,000
Managed policies per role / user20 / 10Up to 25 / 20
Managed policy size; role inline total6,144; 10,240 chars (whitespace excluded)No
Role trust policy length2,048 charsUp to 8,192
SCPs / RCPs attached per root, OU or account10 / 5 (RCPFullAWSAccess counts)No
Role session; chained session1–12 h (default 1 h); 1 h when chainingRole setting
STS requests per account per Region600/s (AssumeRole, GetCallerIdentity, ...)Via Support

KMS: Key Types, Rotation, Multi-Region & XKS

What it is. A regional managed key service whose HSMs are FIPS 140-3 Security Level 3 validated; plaintext key material never leaves the HSM boundary. Encrypt directly handles at most 4,096 bytes, so anything larger uses envelope encryption (GenerateDataKey, encrypt locally, store the wrapped key). The envelope walk-through, key-policy and SSE integration live in KMS & Envelope Encryption; this card adds key types, rotation rules, multi-Region keys, XKS and quotas.

Key / originUseRotation
Symmetric (SYMMETRIC_DEFAULT, AES-256-GCM), AWS_KMS originEncrypt/decrypt, data keys; what S3/EBS/RDS useAutomatic 90–2,560 days, or on demand
Symmetric, imported (EXTERNAL)Bring-your-own key materialOn-demand only, after importing new material; you manage expiry
HMACGenerate/verify MACsManual (new key)
Asymmetric RSA / ECCSign/verify, RSA encrypt, ECC key agreement; public key exportableManual (new key)
ML-DSA 44/65/87Post-quantum sign/verifyManual (new key)
Custom key store: CloudHSM or XKSKeys held in your HSM cluster or external managerManual / your key manager
  • Rotation semantics. The key ID/ARN stays the same; KMS keeps every prior key material version so old ciphertext still decrypts, and new encrypts use the latest. On-demand rotation is capped at 25 per key (hard). AWS managed keys rotate every year and you cannot change that; AWS owned keys are the service's business.
  • Multi-Region keys (MRK). A primary plus replicas in other Regions of the same partition share key ID (mrk- prefix) and key material, so ciphertext made in us-east-1 decrypts in eu-west-1 with no cross-Region call. Each key is otherwise independent: own policy, aliases, grants, tags, state. Rotation is configured on the primary only and propagates. You cannot convert an existing single-Region key. For imported material you must import it into every replica.
  • XKS. Key material lives in your own key manager behind an XKS proxy. AWS documents it as the lowest-TPS, highest-latency option with no SLA coverage, to be used only with an explicit requirement to keep keys outside AWS. Size the proxy for 1,800 requests/s with a 250 ms timeout and keep round trip at or below about 35 ms. Not for high-TPS S3, analytics or DynamoDB paths.
  • Deletion. ScheduleKeyDeletion waits 7–30 days (default 30); the key is unusable while pending. Prefer DisableKey first. A primary with live replicas goes to PendingReplicaDeletion until replicas are gone.
Quota (per account, per Region)Default
Customer managed keys100,000 (adjustable)
Aliases per KMS key / grants per KMS key50 / 50,000 (adjustable)
Symmetric crypto operations (shared across Encrypt, Decrypt, GenerateDataKey, ...)10,000/s; 20,000/s in some Regions; 100,000/s in us-east-1, us-west-2, eu-west-1
RSA, ECC/SM2, ML-DSA crypto operations1,000/s each family
Per custom key store (CloudHSM or XKS), also counts toward the symmetric quota1,800/s (not adjustable)
KEY_ID=$(aws kms create-key --description "orders-prod" --multi-region \
  --key-usage ENCRYPT_DECRYPT --key-spec SYMMETRIC_DEFAULT \
  --query KeyMetadata.KeyId --output text)

aws kms enable-key-rotation --key-id "$KEY_ID" --rotation-period-in-days 365
aws kms create-alias --alias-name alias/orders-prod --target-key-id "$KEY_ID"

# replica in another Region (own key policy, own alias)
aws kms replicate-key --key-id "$KEY_ID" --replica-region eu-west-1

# envelope: plaintext data key + wrapped copy (AES-256)
aws kms generate-data-key --key-id alias/orders-prod --key-spec AES_256 \
  --encryption-context app=orders
{
  "Sid": "PartnerDecryptViaS3Only",
  "Effect": "Allow",
  "Principal": { "AWS": "arn:aws:iam::444455556666:role/partner-reader" },
  "Action": ["kms:Decrypt", "kms:DescribeKey"],
  "Resource": "*",
  "Condition": { "StringEquals": { "kms:ViaService": "s3.us-east-1.amazonaws.com" } }
}

WAF: Web ACLs, Rate Limits, Bot Control, CAPTCHA & Fraud Control

What it is. WAFv2 is a layer-7 request filter. A web ACL (the console now also calls it a protection pack) is an ordered rule list with a default action. Rules run in priority order; the first terminating action (Allow, Block, CAPTCHA, Challenge) wins, while Count and label-adding rules let evaluation continue. It attaches to CloudFront, ALB, API Gateway REST APIs (not HTTP APIs), AppSync, Cognito user pools, App Runner, Verified Access and Amplify. L3/L4 floods belong to Shield; org-wide rollout to Firewall Manager. Overview and pricing shape: WAF & Shield.

CapabilityWhat it doesCatch
Rate-based ruleCounts requests per aggregation instance (IP, forwarded IP, header, cookie, query arg, URI, combos)Window is 60, 120, 300 (default) or 600 s; limit 10 to 2,000,000,000; rechecked about every 10 s; limit applies per instance, not per rule; editing resets counters
Bot ControlCommon: labels and blocks self-identifying bots. Targeted: adds fingerprinting, behavioural heuristics, optional ML rules, with rate limit plus CAPTCHA/ChallengePaid managed group (per request inspected); scope it to URIs that matter
ATP / ACFP (Fraud Control)ATP guards the login endpoint against credential stuffing; ACFP guards sign-up against fake accountsYou must tell the group the login/sign-up path and payload field names; use the JS/mobile SDK for full signal
Anti-DDoS rule groupL7 DDoS: builds a traffic baseline, soft mitigation (silent challenge) then hard blockPlace near the top; do not add a scope-down statement (skews the baseline)
CAPTCHA vs ChallengeCAPTCHA = visible puzzle. Challenge = silent browser check. Both issue a tokenImmunity time default 300 s; CAPTCHA minimum 60 s, Challenge minimum 300 s, max 259,200 s (3 days). Needs a browser that runs JS, so not for pure API clients
  • Capacity. Every rule costs WCUs. A web ACL's base price covers up to 1,500 WCUs; the hard maximum is 5,000 (tiered extra fee above 1,500). A rule group's capacity is fixed at creation (max 5,000).
  • Body inspection. ALB and AppSync inspect only the first 8 KB, fixed. CloudFront, API Gateway, Cognito, App Runner and Verified Access default to 16 KB and can be raised to 64 KB for extra fees. Beyond the limit each rule's OversizeHandling (CONTINUE, MATCH, NO_MATCH) decides; an attacker can pad a payload past the limit, so fail closed with a size-constraint rule.
  • Scope and placement. CLOUDFRONT-scope ACLs, rule groups and IP sets live in us-east-1; REGIONAL ones must be in the resource's Region. WAF logs go to CloudWatch Logs, S3 or Firehose; the destination name must start with aws-waf-logs-. Use log filtering and field redaction to keep PII and noise out.
  • Safe rollout. Put new managed groups in Count (override_action { count {} }), read labelled sampled requests, then promote to Block; use label-match rules to carve out false positives.
resource "aws_wafv2_web_acl" "public" {
  name  = "public-acl"
  scope = "REGIONAL"            # CLOUDFRONT requires the us-east-1 provider
  default_action {
    allow {}
  }

  rule {
    name     = "CommonRuleSetCountFirst"
    priority = 10
    override_action {
      count {}                  # flip to none {} to enforce the group's own actions
    }
    statement {
      managed_rule_group_statement {
        name        = "AWSManagedRulesCommonRuleSet"
        vendor_name = "AWS"
      }
    }
    visibility_config {
      cloudwatch_metrics_enabled = true
      metric_name                = "common"
      sampled_requests_enabled   = true
    }
  }

  rule {
    name     = "LoginRateLimit"
    priority = 20
    action {
      block {}
    }
    statement {
      rate_based_statement {
        limit                 = 100
        evaluation_window_sec = 60
        aggregate_key_type    = "IP"
        scope_down_statement {
          byte_match_statement {
            search_string         = "/login"
            positional_constraint = "STARTS_WITH"
            field_to_match {
              uri_path {}
            }
            text_transformation {
              priority = 0
              type     = "NONE"
            }
          }
        }
      }
    }
    visibility_config {
      cloudwatch_metrics_enabled = true
      metric_name                = "login-rate"
      sampled_requests_enabled   = true
    }
  }

  visibility_config {
    cloudwatch_metrics_enabled = true
    metric_name                = "public"
    sampled_requests_enabled   = true
  }
}
# regional resource (ALB, REST API stage, AppSync, Cognito pool)
aws wafv2 associate-web-acl --web-acl-arn "$WEB_ACL_ARN" --resource-arn "$ALB_ARN"
# CloudFront distribution (needs the current ETag)
aws cloudfront associate-distribution-web-acl --id "$DIST_ID" --if-match "$ETAG" --web-acl-arn "$GLOBAL_WEB_ACL_ARN"

CloudTrail: Trails, Data Events, Insights & the Lake Change

What it is. The account's API audit log: who called what, when, from where. It records control-plane (management) events by default and data-plane (data) events only if you ask. It is not a metrics or alerting system. Concepts, event-history and org-trail basics are in CloudTrail: The Audit Trail; this card adds event selectors, quotas, Insights, delivery timing and the CloudTrail Lake availability change.

ProductWhat you getNote
Event historyLast 90 days of management events per Region, console/LookupEventsFree, no setup, not durable beyond 90 days
TrailDurable delivery to S3, optionally CloudWatch Logs and EventBridgeFirst copy of management events per Region free; extra copies, data events and Insights are billed
Insights eventsAnomaly detection on write API call rate and on API error rate (read and write)Opt-in; first events can take up to 36 h on a trail
Network activity eventsAPI calls made through VPC endpoints, including denied onesOpt-in via event selectors on a trail
CloudTrail LakeManaged event data store queried with SQLClosed to new customers since 2026-05-31; existing customers keep it. AWS points new users to CloudWatch
  • Lake replacement path. CloudTrail can deliver events straight into CloudWatch Logs through telemetry enablement rules (organization, OU or account scope) into managed log groups named aws/cloudtrail/<event-types>, with no per-trail wiring; historical Lake data can be imported into CloudWatch Logs. For new designs, default to: org trail to S3 (Athena for forensics) plus CloudWatch Logs for alerting. Existing Lake stores retain up to 7 years (2,555 days).
  • Data events. Basic selectors cover only S3 objects, Lambda functions and DynamoDB tables; every other resource type, directory buckets, and any eventName or readOnly filter need advanced event selectors. You use basic or advanced on a trail, not both, and applying advanced selectors overwrites basic ones. If you omit a Management selector from an advanced set, the trail stops logging management events.
  • Quotas. 5 trails per Region (cannot be raised; a multi-Region trail counts once in each Region). 5 basic event selectors, 250 data resources, and 500 condition values across advanced selectors per trail. Events over 256 KB cannot be sent to CloudWatch Logs. Log files are at most 50 MB compressed.
  • Timing. S3 delivery averages about 5 minutes after the API call, not guaranteed; Insights events within about 30 minutes of the anomaly. Integrity validation adds signed digest files roughly hourly in a separate S3 prefix; if validation is switched off, the digest chain breaks after an hour.
  • Org trail. Created by the management account or a delegated administrator; member accounts see it but cannot change it. The central bucket policy needs statements for AWSLogs/<management-account-id>/* and AWSLogs/<org-id>/*, each with aws:SourceArn set to the trail ARN in the management account. Add Object Lock, a KMS key whose policy lets cloudtrail.amazonaws.com use it, and an SCP denying cloudtrail:StopLogging/DeleteTrail.
aws cloudtrail create-trail --name org-trail --s3-bucket-name org-cloudtrail-logs \
  --is-multi-region-trail --is-organization-trail --enable-log-file-validation \
  --kms-key-id arn:aws:kms:us-east-1:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab

# advanced selectors: keep management events, add data events for ONE bucket, deletes and writes only
aws cloudtrail put-event-selectors --trail-name org-trail --advanced-event-selectors '[
  {"Name":"Management","FieldSelectors":[{"Field":"eventCategory","Equals":["Management"]}]},
  {"Name":"PII bucket writes","FieldSelectors":[
    {"Field":"eventCategory","Equals":["Data"]},
    {"Field":"resources.type","Equals":["AWS::S3::Object"]},
    {"Field":"readOnly","Equals":["false"]},
    {"Field":"resources.ARN","StartsWith":["arn:aws:s3:::pii-bucket/"]}]}]'
aws cloudtrail start-logging --name org-trail
# CloudWatch Logs Insights over the trail's log group: recent IAM policy changes
fields @timestamp, userIdentity.arn, eventName, requestParameters.roleName
| filter eventSource = "iam.amazonaws.com"
    and eventName in ["PutUserPolicy","AttachUserPolicy","PutRolePolicy","AttachRolePolicy","CreatePolicy"]
| sort @timestamp desc
| limit 50

CloudWatch: Log Classes, Metrics Insights, Application Signals & Limits

What it is. The default AWS telemetry plane: metrics, logs, alarms, dashboards, Synthetics canaries, Container/Lambda Insights, Live Tail and Application Signals (OpenTelemetry-based service map, golden-signal metrics and SLOs). EventBridge (formerly CloudWatch Events) is a separate service. Metric identity, retention ladder, EMF, alarms and the logs-versus-third-party trade-off are already in Metrics, Logs, Insights & EMF and Alarms; this card adds what those sections omit.

Log classUseGives up
StandardEverything: real-time alerting, processing, searchNothing; highest ingestion price
Infrequent AccessAudit, compliance, forensic logs queried ad hoc; ingestion about half of Standard, same storage and Insights chargesSubscription filters and S3 export, metric filters/alarming, Live Tail, GetLogEvents/FilterLogEvents, Contributor/Container/Lambda Insights; data protection policies cost extra per GB
DeliveryLambda logs routed only to S3 or Firehose; kept in CloudWatch for 1 dayInsights queries and other rich features
  • Class is fixed at creation. You cannot flip a log group between Standard and Infrequent Access; migration means a new group (aws logs create-log-group --log-group-class INFREQUENT_ACCESS). Never put a log group you alarm on into IA.
  • Metrics Insights. A SQL-like query across many metrics (SELECT ... FROM SCHEMA(...) WHERE ... GROUP BY ... ORDER BY ... LIMIT). One alarm can watch a whole fleet and picks up new resources automatically. Limits: the most recent 3 hours of data, 10,000 metrics scanned and 500 time series returned per query, 200 Metrics Insights alarms per Region (hard). A multi-time-series alarm needs both GROUP BY and ORDER BY; at most 100 contributors are reported in ALARM.
  • Application Signals. Auto-instruments Java, Python, Node.js and .NET on EKS, ECS, EC2 and Lambda (ADOT/CloudWatch agent underneath), emits request, availability, latency, fault and error metrics, draws the topology map, and manages SLOs with burn-rate alarms. On Lambda, remove X-Ray SDK code first or it conflicts with the layer. Transaction Search can capture spans without sampling.
  • Tracing is moving to OpenTelemetry. The X-Ray SDKs and daemon entered maintenance mode on 2026-02-25 (security fixes only). The X-Ray backend stays fully supported; new work should use ADOT/OpenTelemetry.
  • Recent alarm and query features. Alarms can be created directly on a Logs Insights query (no metric filter step; 2026). Alarm mute rules suppress notifications on a schedule for planned deployments or maintenance (2026). Logs Insights supports scheduled queries that deliver to S3 and EventBridge. CloudWatch has also introduced a separate "Omni" experience (OpenTelemetry-native, SQL over logs/traces, PromQL over metrics); treat it as new and check availability before designing around it.
LimitValue
PutMetricData request1 MB (gzip allowed), at most 1,000 metrics, at most 150 values per metric via Values/Counts, at most 30 dimensions per metric; 500 requests/s per account per Region (adjustable)
Alarm periods10, 20, 30 s (high-resolution, needs StorageResolution=1 data) or a multiple of 60 s; period × evaluation periods ≤ 7 days (≤ 1 day when period < 1 h)
Metric-math alarmReferences at most 10 metrics (hard)
EMFDimensionSet at most 30 keys; every distinct DimensionSet becomes a separate billable custom metric
Log event / PutLogEvents batch1,024 KB per event; 1 MB per batch; 5,000 PutLogEvents calls/s per Region (adjustable)
Metric filters per log group; Live Tail sessions100 (hard); 15 concurrent per account (adjustable)
Logs Insights query runtimeTimes out after 60 minutes; narrow the time range or split the query
# one alarm for every EC2 instance (Metrics Insights, multi-time-series)
cat > q.json <<'JSON'
[{"Id":"q1","ReturnData":true,"Period":60,
  "Expression":"SELECT MAX(CPUUtilization) FROM SCHEMA(\"AWS/EC2\", InstanceId) GROUP BY InstanceId ORDER BY MAX() DESC"}]
JSON
aws cloudwatch put-metric-alarm --alarm-name fleet-cpu-high \
  --metrics file://q.json --comparison-operator GreaterThanThreshold \
  --threshold 85 --evaluation-periods 3 --datapoints-to-alarm 3 \
  --treat-missing-data notBreaching \
  --alarm-actions arn:aws:sns:us-east-1:111122223333:oncall

# cheap cold logs: Infrequent Access class, bounded retention
aws logs create-log-group --log-group-name /audit/app --log-group-class INFREQUENT_ACCESS
aws logs put-retention-policy --log-group-name /audit/app --retention-in-days 365

Amazon SQS

What it is. A fully managed, pull-based message queue: producers SendMessage, consumers ReceiveMessage then DeleteMessage. Storage is unlimited and replicated across AZs; you pay per request and there is no idle cost. Deep dive on semantics: Standard vs FIFO and visibility, polling, DLQ.

Pick it when you need load-leveling, async work offload, or a durable per-consumer buffer behind SNS/EventBridge. Skip it when many independent readers must replay history (Kinesis/MSK) or you need content routing (EventBridge).

LimitValueNote
Max message size1 MiB (1,048,576 bytes)Larger: Extended Client Library (Java/Python) to S3, up to 2 GB, synchronous clients only. Billed per 64 KB chunk, so a 1 MiB send costs 16 requests
Retention60 s to 14 days, default 4 daysDLQ expiry counts from the original enqueue time on standard queues
Visibility timeout0 s to 12 h, default 30 sLambda: set at least 6x the function timeout
Long poll / delay1–20 s wait; 0–15 min delayAlways long poll (ReceiveMessageWaitTimeSeconds=20)
In flight~120,000 standard; 120,000 FIFOSoft; raise via support. Batch API calls max 10 messages
FIFO throughput300 TPS per partition per API action; 3,000 msg/s batchedHigh-throughput mode is region dependent (up to 70,000 TPS, 700,000 msg/s batched in us-east-1, us-west-2, eu-west-1; 2,400 TPS default in other regions)
  • Fair queues (2025). On a standard queue, set MessageGroupId to a tenant id and SQS detects a noisy tenant by its in-flight share and serves quiet tenants first. No ordering, no throughput cap, no consumer change. Billed at an extra fair-queue rate, and an SNS standard topic can forward the group id to subscribed standard queues.
  • FIFO is exactly-once processing inside a 5-minute dedup window; one in-flight message per group, so parallelism equals the number of distinct group ids.
  • Encryption. New queues get SSE-SQS by default (over HTTPS); switch to SSE-KMS only if you need key control, and budget KMS calls.
  • DLQ redrive. StartMessageMoveTask moves messages from a DLQ to the source or a custom queue of the same type; one active task per queue; a redriven message gets a new message id and enqueue time.
DLQ_URL=$(aws sqs create-queue --queue-name orders-dlq \
  --attributes MessageRetentionPeriod=1209600 --query QueueUrl --output text)
DLQ_ARN=$(aws sqs get-queue-attributes --queue-url "$DLQ_URL" \
  --attribute-names QueueArn --query Attributes.QueueArn --output text)

aws sqs create-queue --queue-name orders --attributes "{
  \"VisibilityTimeout\":\"180\",
  \"ReceiveMessageWaitTimeSeconds\":\"20\",
  \"RedrivePolicy\":\"{\\\"deadLetterTargetArn\\\":\\\"$DLQ_ARN\\\",\\\"maxReceiveCount\\\":\\\"5\\\"}\"
}"

# multi-tenant send on a standard queue (fair queues): group id = tenant
aws sqs send-message --queue-url "$ORDERS_URL" \
  --message-body '{"order":42}' --message-group-id tenant-123

# after the consumer bug is fixed: replay the DLQ into the source queue
aws sqs start-message-move-task --source-arn "$DLQ_ARN"

Amazon SNS

What it is. Managed push pub/sub: publish to a topic and SNS fans the message out to every subscription (SQS, Lambda, HTTP/S, Firehose, email, SMS, mobile push). No consumer-side storage, so durability comes from pairing it with SQS. See SNS: Pub/Sub and Fan-Out, the fan-out pattern, and EventBridge vs SNS.

Pick it when one event feeds many consumers with very high fan-out, or for A2P (email, SMS, push). Pick EventBridge instead for routing AWS or SaaS events by rich payload rules; pick SQS for one consumer pool.

DimensionStandard topicFIFO topic
Ordering / deliveryBest-effort, at-least-onceStrict order per message group, dedup
SubscribersSQS, Lambda, HTTP/S, Firehose, email, SMS, pushSQS FIFO and standard queues only; Lambda via an SQS queue; no email, SMS, push or HTTP/S
ThroughputPer-account regional publish quota (30,000 msg/s us-east-1; 300 msg/s in smaller regions)Default 3,000 msg/s or 20 MB/s per topic; FifoThroughputScope=MessageGroup lifts it to the account quota, 300 msg/s per group
Limits100,000 topics; 12.5M subscriptions per topic1,000 topics; 100 subscriptions per topic
Archive and replayNot available1–365 days, per-subscription replay
  • Payload size. 256 KiB default; set the topic attribute MaximumMessageSize up to 1 MiB (SQS, Lambda and Firehose subscribers only, max 100 subscriptions). Above 1 MiB use the Extended Client Library with S3 (payload up to 2 GB).
  • Filtering. Default scope is MessageAttributes; set FilterPolicyScope=MessageBody to match JSON payloads (required for S3, EventBridge, CloudTrail and SES notifications, which carry no attributes). Policy limits: 5 keys, 150 value combinations, 200 policies per topic.
  • Delivery and DLQ. AWS-managed endpoints (SQS, Lambda) are retried for up to 23 days; HTTP/S follows a customizable delivery policy (default 3 retries 20 s apart). Client errors such as a deleted queue are not retried. Attach a subscription DLQ (an SQS queue) or the message is discarded.
  • Message data protection. Data protection policies can audit, deny, or de-identify (mask/redact) sensitive data on publish or delivery, but the feature has been closed to new customers since 2026-04-30 (existing users keep it).
  • SMS. Delivered through AWS End User Messaging SMS (origination IDs, registrations and billing live there). Prefer it directly for high-volume or campaign SMS.
aws sns create-topic --name orders.fifo --attributes '{
  "FifoTopic":"true",
  "ContentBasedDeduplication":"true",
  "FifoThroughputScope":"MessageGroup",
  "ArchivePolicy":"{\"MessageRetentionPeriod\":\"30\"}"
}'

# payload-based filter: only paid orders reach this queue
aws sns subscribe --topic-arn "$TOPIC_ARN" --protocol sqs \
  --notification-endpoint "$QUEUE_ARN" --attributes '{
  "RawMessageDelivery":"true",
  "FilterPolicyScope":"MessageBody",
  "FilterPolicy":"{\"detail\":{\"status\":[\"PAID\"]}}"
}'

Amazon OpenSearch Service

What it is. Managed OpenSearch (Apache 2.0 fork of Elasticsearch 7.10) for full-text search, log/observability analytics, security analytics and vector search, plus OpenSearch Dashboards. Two deployment modes: managed domains (you pick instance types, shards, tiers) and OpenSearch Serverless (collections billed in OCUs). It is a search index, not a system of record: keep the source of truth in DynamoDB/S3/RDS and feed OpenSearch from streams. Used as the vector store in Vector Databases for RAG and Architecting RAG on AWS.

Pick it when you need BM25 plus filters plus aggregations, hybrid lexical/vector queries, or log analytics with tiered retention. Skip it when you need transactions or strict read-after-write (use a database; OpenSearch is near-real-time, refresh about 1 s) or only a small vector index (pgvector may be cheaper).

ChoiceFacts (checked 2026-10)
Serverless: Classic1 OCU = 6 GiB memory plus vCPU; minimum 2 OCUs always on; Classic collections can still be created standalone
Serverless: NextGenCollections live in collection groups that pool OCUs; min can be 0 (scale to zero after 10 idle minutes, about 10 s cold start, requests queued); compute decoupled from storage; GPU-accelerated HNSW builds; per-account regional endpoint on on.aws
Serverless limitsOCU counts of 2, 4, 8, 16 or multiples of 16, up to 1,700 each for indexing and search per group; 1,000 indexes per collection; types: search, time series (hot plus warm), vector search
Managed instance familiesGeneral/memory (m/r/c 7g, 8g, 7i), storage (i4i, i8g), and OpenSearch Optimized OR1/OR2/OM2 (EBS plus synchronous S3 copy) and OI2 (local NVMe plus S3, also usable as a warm tier)
Managed scaleUp to 1,002 data nodes in a 3-AZ domain on OpenSearch 2.17+ with xlarge or larger OR/OM/OI nodes; default per-family limit is lower (check Service Quotas); 5 dedicated masters
Sizing rulesShards 10–30 GiB for search, 30–50 GiB for logs; hard max 65 GiB on Multi-AZ with Standby; request payload 10 MiB (small instances) or 100 MiB
  • Tiers. UltraWarm keeps read-only indexes in S3 behind a node cache and bills primary shard size only (no replica); cost-effective from roughly 2.5 TiB of hot data; no Reserved Instances for warm nodes. Cold storage is S3-only and must be re-attached to UltraWarm to query. ISM actions: warm_migration, cold_migration, cold_delete.
  • Vector engine. Use Faiss (HNSW or IVF, scales to billions) or Lucene (smart filtering, small to mid size). NMSLIB is deprecated from OpenSearch 3.0, so new mappings should not use it. OpenSearch 3.x adds quantization and memory-optimized Faiss search; current managed versions go up to 3.5, and older lines (1.3, 2.11–2.19) have announced end-of-support dates that bill extra under Extended Support.
  • Security layers. Managed: domain resource policy, IAM (es:ESHttp*), plus fine-grained access control inside the cluster; put domains in a VPC with node-to-node and at-rest encryption and TLS policy Policy-Min-TLS-1-2-PFS-2023-10. Serverless: encryption, network and data-access policies (aoss:* permissions); SigV4 service name is aoss (managed uses es).
# OpenSearch Serverless NextGen: pooled capacity, scale to zero (needs a recent AWS CLI v2)
aws opensearchserverless create-collection-group --name search-cg --generation NEXTGEN \
  --standby-replicas ENABLED \
  --capacity-limits "minIndexingCapacityInOCU=0,maxIndexingCapacityInOCU=16,minSearchCapacityInOCU=0,maxSearchCapacityInOCU=16"
aws opensearchserverless create-collection --name product-vectors \
  --type VECTORSEARCH --collection-group-name search-cg
# security: encryption, network and data-access policies must exist (Express Create in the console adds them)
{ "policy": { "description": "logs: hot, UltraWarm at 30d, cold at 90d", "default_state": "hot",
  "states": [
    { "name": "hot",  "actions": [{ "rollover": { "min_primary_shard_size": "30gb", "min_index_age": "7d" } }],
      "transitions": [{ "state_name": "warm", "conditions": { "min_index_age": "30d" } }] },
    { "name": "warm", "actions": [{ "warm_migration": {} }],
      "transitions": [{ "state_name": "cold", "conditions": { "min_index_age": "90d" } }] },
    { "name": "cold", "actions": [{ "cold_migration": { "timestamp_field": "@timestamp" } }], "transitions": [] } ],
  "ism_template": [{ "index_patterns": ["logs-*"], "priority": 100 }] } }
MODULE 27

AWS Decision Guides & Specialized Topics

Service-selection guides and specialized topics that sit across the service modules: choosing between options, and the details interviewers probe.

Deploying a Service on AWS End to End

“Walk me from an empty AWS org to production traffic” is a senior-loop favorite because it tests ordering, not trivia. The runbook below is opinionated: multi-account landing zone, IaC only, OIDC for CI, observability before launch. Each phase has a gate — the condition that must hold before you start the next one.

PhaseWhat you stand upGate (done when)
0. Landing zone & identityOrganizations + Control Tower (it creates the Log Archive and Audit accounts; add one workload account per environment). IAM Identity Center federated to your IdP. Org-wide CloudTrail with log file integrity validation. Budgets, Cost Anomaly Detection, and a CUR 2.0 export (Data Exports) in the management account.Humans enter only via SSO; CI enters only via an OIDC role; no long-lived IAM users or keys exist.
1. Network3-AZ VPC with public, private and data subnets. Gateway endpoints for S3 and DynamoDB (free). Interface endpoints (PrivateLink) for ECR, CloudWatch Logs, STS, Secrets Manager, KMS, SSM. Central egress VPC (NAT + Network Firewall via Transit Gateway) once you have more than 2–3 VPCs.Private subnets reach AWS APIs without a NAT path.
2. Security baselineKMS key per environment, EBS encryption by default, GuardDuty org-wide with the protection plans you need (S3, EKS, Runtime Monitoring, RDS, Lambda, malware), Security Hub, Inspector, WAF web ACL.Findings flow to one place; WAF rules run in Count mode first, then Block.
3. Data layerAurora/RDS Multi-AZ (Aurora Serverless v2 for new web apps), RDS Proxy in front of any Lambda-backed app, DynamoDB on-demand with PITR and deletion protection, ElastiCache (Valkey) for cache, MemoryDB if Redis is the primary store.Restore from backup rehearsed once; credentials come from Secrets Manager.
4. Build & packageMulti-stage Dockerfile, arm64 unless an x86-only dependency blocks it, ECR with registry-level scanning, image signing (AWS Signer + Notation), one IaC module per concern, plan on every PR and apply only from main.A signed, scanned image digest is the only artifact that reaches prod.
5. DeployECS, EKS or Lambda path (below).Alarm-gated rollout with a tested rollback.
6. EdgeCloudFront with a custom domain and an ACM cert (must be in us-east-1), OAC on S3 origins, WAF on the distribution, CloudFront Functions for rewrites, Lambda@Edge only when you need network calls.Origin reachable only through CloudFront.
7. ObservabilityRED + saturation dashboards, composite alarms for paging, OpenTelemetry traces, EMF custom metrics, short app-log retention, Synthetics canaries on public APIs.On-call has a runbook and a paging alarm before launch, not after.
8. Cost & DRTag policy + SCP, NAT Gateway audit, commitments sized to the baseline, DR tier chosen per workload (see failover mechanics).Every resource attributable; RTO/RPO written down per tier.

The three deploy paths in phase 5 differ in what “safe rollout” means:

  • ECS — task definition with separate execution and task roles, awsvpc networking, secrets injected from Secrets Manager/SSM, capacity provider strategy (Fargate base + Fargate Spot weight for burst), Service Connect for east-west calls. ECS now has built-in blue/green plus linear and canary strategies with CloudWatch-alarm rollback and lifecycle hooks; CodeDeploy remains an option.
  • EKS — EKS Auto Mode (or Karpenter on a managed node group), Pod Identity associations for per-workload roles, Argo CD/Flux for GitOps, Argo Rollouts for canary at the Kubernetes layer.
  • Lambda — arm64, heavy init at module scope, reserved concurrency to protect downstreams, provisioned concurrency only when latency demands it. For SQS sources set BatchSize, MaximumBatchingWindowInSeconds and ReportBatchItemFailures; use async destinations (SQS, SNS, Lambda, EventBridge) rather than only a DLQ.
{
  "Version": "2012-10-17",
  "Statement": [{
    "Effect": "Allow",
    "Principal": {"Federated": "arn:aws:iam::111122223333:oidc-provider/token.actions.githubusercontent.com"},
    "Action": "sts:AssumeRoleWithWebIdentity",
    "Condition": {
      "StringEquals": {"token.actions.githubusercontent.com:aud": "sts.amazonaws.com"},
      "StringLike": {"token.actions.githubusercontent.com:sub": "repo:my-org/my-app:ref:refs/heads/main"}
    }
  }]
}
# registry-wide continuous scanning via Inspector (repo-level scan-on-push is deprecated)
aws ecr put-registry-scanning-configuration --scan-type ENHANCED \
  --rules '[{"repositoryFilters":[{"filter":"prod","filterType":"WILDCARD"}],"scanFrequency":"CONTINUOUS_SCAN"}]'

Failover That Survives the Disaster: Static Stability, ARC and Elastic DR

The four DR strategies tell you what to keep warm. The harder interview question is how you actually flip when the region you depend on is the one that is broken. The Well-Architected rule (REL11-BP04) is to rely on the data plane, not the control plane, during recovery. The data plane delivers the service (answer DNS queries, evaluate health checks, serve reads); the control plane configures it (create or edit records, scale groups, launch instances). Data planes are simpler and built for higher availability. Route 53 is the textbook case: its data plane answers queries and evaluates health checks from many locations, while the API/console that edits records runs in a single region (us-east-1) and is outside the SLA. A failover runbook that begins with “edit the Route 53 record” has a hidden dependency on the control plane.

ToolFailure it handlesHow it worksSharp edge
Route 53 health-check failoverEndpoint unhealthyAutomatic, data plane only; record answers switch when the check failsCannot be flipped on purpose; a bad health check endpoint flaps traffic
ARC routing controlsRegion or cell failover you decide to makeOn/off switches backed by a 5-Region cluster; each switch drives a Route 53 health check on a DNS record; safety rules (assertion, gating) stop you turning every switch offFlip them with the cluster data-plane API (CLI/SDK), not the console; bookmark all five cluster endpoints so you never call DescribeCluster mid-incident
ARC zonal shift / autoshiftOne impaired AZ behind an ALB/NLBShifts traffic away from an AZ (manual shift expires within 72 h, extendable); autoshift lets AWS do it on its own telemetry and runs weekly practice runsOpt in per ALB/NLB (works with cross-zone load balancing on or off); pre-scale every AZ to absorb the loss of one — autoshift does not wait for Auto Scaling
ARC Region switchMulti-Region app recovery as a runbookPlans → workflows → execution blocks (scale ASG/ECS/EKS, Aurora Global DB, routing control, Route 53 health check), parallel or sequential; plan evaluation about every 30 min; records actual recovery time per executionDoes not guarantee compute capacity arrives; reserve capacity in the standby Region for critical tiers
AWS Elastic Disaster RecoveryServers (on-prem, EC2, other clouds) with no native replicationContinuous block-level replication into a low-cost staging area; launch converted instances on demandDocs: RPO of seconds, RTO typically 5–20 min; replication keeps running while you launch drill instances
AWS Backup logically air-gapped vaultRansomware, stolen credentials, account lockoutImmutable vault in AWS-owned encryption; share to a recovery account with AWS RAM (planned restore tests) or multi-party approval (emergency, account inaccessible)Backups the attacker can delete are not a recovery plan; restore-test on a schedule

The data tier decides your real RPO. Three Region-spanning options, from least to most exotic:

  • Aurora Global Database — one writer Region, up to 10 secondary Regions, async storage-level replication (RPO typically seconds; for Aurora PostgreSQL set an upper bound with rds.global_db_rpo, which can throttle writes). Two verbs matter: switchover (planned, waits for sync, RPO 0, typically under 30 s on qualifying engine versions) and failover (unplanned, --allow-data-loss, RPO is your replication lag, RTO in minutes). The two clusters need compatible engine versions or you fall back to a manual detach-and-promote.
  • DynamoDB global tables, MRSC mode — zero RPO. Exactly three Regions (three replicas, or two plus a witness); a write is synchronously replicated to at least one other Region before it returns. Costs: higher write and strongly consistent read latency, no transaction APIs, and ReplicatedWriteConflictException if two Regions touch one item (retry). The default MREC mode stays async, last-writer-wins, active-active.
  • Aurora DSQL — serverless distributed SQL, active-active across linked clusters plus a witness Region, designed for 99.99% single-Region and 99.999% multi-Region availability. There is no failover step at all. The price is the programming model: optimistic concurrency, so any transaction can fail with SQLSTATE 40001 (OC000 data conflict, OC001 schema change) and must be retried; one DDL statement per transaction; no SAVEPOINT. Foreign keys became available in August 2026; check the release notes for the current compatibility list.
# flip traffic with the ARC data plane (cluster endpoint + its Region), never the console
aws route53-recovery-cluster update-routing-control-state \
  --routing-control-arn arn:aws:route53-recovery-control::111122223333:controlpanel/EXAMPLE/routingcontrol/EXAMPLE \
  --routing-control-state Off \
  --region us-west-2 \
  --endpoint-url https://host-EXAMPLE.us-west-2.example.com/v1

# Aurora Global Database: planned move (RPO 0) vs unplanned failover (may lose data)
aws rds switchover-global-cluster --region us-east-1 --global-cluster-identifier app-global \
  --target-db-cluster-identifier arn:aws:rds:eu-west-1:111122223333:cluster:app-eu
aws rds failover-global-cluster --region eu-west-1 --global-cluster-identifier app-global \
  --target-db-cluster-identifier arn:aws:rds:eu-west-1:111122223333:cluster:app-eu --allow-data-loss

CQRS, Sagas and the Transactional Outbox on AWS

These three patterns solve one problem from three angles: data that must stay consistent when it lives in more than one place. CQRS gives reads and writes separate models; a saga keeps a multi-service business transaction consistent without a distributed lock; the outbox makes “update my database and publish an event” atomic. They compose: the outbox feeds the event stream, the stream feeds the read model and the saga. Reach for them only when the cost is justified — CQRS on a plain CRUD app is premature optimization, and a saga for two steps is a try/catch.

  Command side                          Query side
  ------------                          ----------
  API -> write model                    API -> read model (shaped for the query)
        DynamoDB / Aurora                     OpenSearch | DynamoDB GSI + DAX | Redis | Athena
              |                                     ^
              +-- change stream (Streams / Pipes) --+    eventually consistent, seconds
              +-- events: EventBridge -> saga steps, other consumers

How a change reaches the read model is the first design choice:

MechanismYou ownNotes
DynamoDB Streams + Lambda event source mappingThe sync codeStream keeps a deduplicated, time-ordered log for up to 24 hours; order is per item (one key lives in one shard), one concurrent invocation per shard. Set retry attempts, maximum record age, batch bisecting and an on-failure destination (SQS/SNS), or one poison record stalls the shard until it expires.
EventBridge PipesThe pipe configManaged poller for DynamoDB streams, Kinesis, SQS, MSK, MQ; event-pattern filter, optional enrichment (Lambda, Step Functions, API Gateway, API destination), many targets including an event bus. You pay only for events that pass the filter.
DynamoDB zero-ETL to OpenSearchAlmost nothingAn OpenSearch Ingestion pipeline loads an initial export snapshot (needs PITR) then follows the stream. Layouts: passthrough, routing one table to many indices, or merge from several tables.

Whatever the transport, the read side must tolerate what streams actually deliver: at-least-once delivery, ordering only within an item, and stream records from one transaction that arrive at different times and interleaved with others — the docs say consumers must not assume transaction atomicity. So make projections idempotent upserts keyed by entity id with a version check (drop an update older than what is stored), handle REMOVE as well as INSERT/MODIFY (a sync that ignores deletes leaves ghost documents), and sign requests to an IAM-protected domain. Tell the user their command was accepted; do not promise the query side shows it yet.

Saga: orchestration or choreography. Choreography (each service reacts to the previous event) is loosely coupled but nobody can answer “where is order 42?”. Orchestration puts the sequence, retries and compensations in one definition. On AWS the default orchestrator is Step Functions (a Task Catch routes to compensating tasks; see Step Functions: Orchestration for the ASL shape). Lambda durable functions are the code-first alternative: checkpoint-and-replay lets one function run for up to a year, but your code must be deterministic outside durable steps. Rules that apply either way: every step has a compensating action; compensations are idempotent and retried; some effects cannot be undone (an email), so compensate semantically (send a correction).

Outbox. Publishing to a bus after committing to the database is a dual write: crash between the two and the event is lost. Instead, write the state change and an outbox item in one DynamoDB transaction, then let the stream publish it.

[
  {"Put": {"TableName": "orders",
           "Item": {"PK": {"S": "ORDER#o-123"}, "SK": {"S": "META"}, "status": {"S": "PLACED"}, "version": {"N": "1"}},
           "ConditionExpression": "attribute_not_exists(PK)"}},
  {"Put": {"TableName": "orders",
           "Item": {"PK": {"S": "OUTBOX#o-123"}, "SK": {"S": "OrderPlaced#1"}, "type": {"S": "OrderPlaced"},
                    "payload": {"S": "{\"orderId\":\"o-123\"}"}}}}
]
# pass the JSON above as --transact-items; --client-request-token makes a retry idempotent for 10 minutes
aws dynamodb transact-write-items --client-request-token order-o-123 --transact-items file://tx.json

# stream only the outbox inserts to the bus; bisect a failing batch, cap retries
aws pipes create-pipe --name orders-outbox --role-arn arn:aws:iam::111122223333:role/pipes-orders \
  --source arn:aws:dynamodb:us-east-1:111122223333:table/orders/stream/2026-01-01T00:00:00.000 \
  --source-parameters '{"FilterCriteria":{"Filters":[{"Pattern":"{\"eventName\":[\"INSERT\"],\"dynamodb\":{\"Keys\":{\"PK\":{\"S\":[{\"prefix\":\"OUTBOX#\"}]}}}}"}]},"DynamoDBStreamParameters":{"StartingPosition":"LATEST","MaximumRetryAttempts":5,"OnPartialBatchItemFailure":"AUTOMATIC_BISECT"}}' \
  --target arn:aws:events:us-east-1:111122223333:event-bus/orders-event-bus

Multi-Tenant SaaS: Silo, Pool, Bridge and Enforced Isolation

“Design a multi-tenant SaaS” is really two questions: how much do tenants share (the deployment model) and what stops tenant A reading tenant B (the isolation mechanism). Candidates answer the first and wave at the second. The AWS SaaS guidance names three deployment models; the senior move is to say that isolation must be enforced by something the application code cannot forget, not by a WHERE tenant_id = ? a developer has to remember.

ModelWhat is sharedIsolation boundaryCost / opsNoisy neighborPick when
SiloNothing; dedicated stack per tenant (stack in one account, or an account per tenant)Infrastructure: account, VPC, IAM boundaryHighest; N deployments to patch and observe, automation mandatoryEliminatedRegulated or large enterprise tenants, per-tenant SLAs, per-tenant cost proof
PoolEverything: compute, tables, bucketsLogical: tenant id in key/row, enforced by IAM or database policyLowest; onboarding is a row, not infrastructureMitigated, never eliminatedMany small, similar tenants; cost-sensitive tiers
BridgeSome layers shared, some per tenant (shared web/app tier, database per tenant) or silo for premium tiers and pool for basicMixed, chosen per serviceMiddle; most real systems end hereIsolated where it hurtsOne layer is the bottleneck or the compliance hot spot; tiered pricing

Enforcement works as a chain; each link removes a way for tenant context to be forged or dropped:

  1. Establish tenant context from a verified token. Put the tenant id in a signed claim (a Cognito pre token generation trigger can add custom claims) and validate the signature at the edge: an API Gateway HTTP API JWT authorizer or a Lambda authorizer. Never read the tenant from the request body, a header, or a JWT you decoded without verifying.
  2. Turn context into credentials. Assume a role with a TenantID session tag, or call AssumeRoleWithWebIdentity with the tags claim in the JWT; the resulting credentials are tenant-scoped. One policy with ${aws:PrincipalTag/TenantID} serves every tenant, so onboarding creates no IAM objects and no quota pressure.
  3. Enforce in the data tier. DynamoDB: tenant id as the leading partition key plus dynamodb:LeadingKeys. Aurora/RDS PostgreSQL: row-level security driven by a runtime parameter the app sets per request. S3: prefix per tenant and the same tag-based policy.
  4. Contain load. Per-tenant throttles (API Gateway usage plans throttle and cap per API key; they are a quota tool, not authentication), reserved concurrency for noisy paths, a queue per tier, and promotion of a heavy tenant from pool to silo.
  5. Make tenants observable. Tenant id in every log line, metric dimension and trace annotation; tag silo resources. Pooled cost cannot be attributed by tags alone, so meter usage per tenant in the application.
{
  "Version": "2012-10-17",
  "Statement": [{
    "Effect": "Allow",
    "Action": ["dynamodb:GetItem", "dynamodb:BatchGetItem", "dynamodb:Query",
               "dynamodb:PutItem", "dynamodb:UpdateItem", "dynamodb:DeleteItem"],
    "Resource": ["arn:aws:dynamodb:us-east-1:111122223333:table/saas-data"],
    "Condition": {
      "ForAllValues:StringEquals": {"dynamodb:LeadingKeys": ["${aws:PrincipalTag/TenantID}"]}
    }
  }]
}
ALTER TABLE orders ENABLE ROW LEVEL SECURITY;
ALTER TABLE orders FORCE ROW LEVEL SECURITY;      -- apply the policy to the table owner too
CREATE POLICY tenant_isolation ON orders
  USING      (tenant_id = current_setting('app.current_tenant')::uuid)
  WITH CHECK (tenant_id = current_setting('app.current_tenant')::uuid);

-- per request, inside the transaction (is_local = true clears it at COMMIT)
BEGIN;
SELECT set_config('app.current_tenant', '5e2c1c0e-3b6e-4a37-9d5a-0b7f0a1c2d3e', true);
SELECT id, total FROM orders;                      -- sees only this tenant's rows
COMMIT;

Managed vs Self-Managed, Stage-Based Evolution and Anti-Patterns

There is no best architecture tells you to derive a design from constraints. Two follow-up questions decide most real designs: for each component, do I run it or rent it? and what should the stack look like at my current stage, and what signal tells me to move? Answering both with measurable triggers instead of fashion is what separates a senior answer.

Run or rent: four questions in order.

  1. Is there a managed AWS service for it? If yes, it is the default. Self-managing is the exception you must justify.
  2. Does it cover roughly 80% of the need? Then live with the 20% gap. A feature gap that blocks the product (an unsupported extension, an engine version you need, kernel- or eBPF-level control) is a legitimate reason to leave.
  3. Can your team operate the self-managed version at 3 a.m.? Count patching and upgrades, backup and restore tests, HA and failover, security hardening, monitoring and on-call, capacity planning. If you cannot staff those, the managed premium is cheaper than it looks.
  4. Is it a differentiator? Build or customise only where it earns competitive advantage; rent everything else and spend engineering time where customers see it.

The cost comparison is managed premium versus engineer-hours of operations plus incident risk, not instance price versus instance price. Self-managing tends to win only when a hard feature gap exists, a regulator requires control the managed service cannot give, or the premium is large enough to fund a dedicated platform team.

StageTypical stackMove on when you see
1. MVPAPI Gateway + Lambda + DynamoDB (or ECS Express Mode / Fargate + Aurora Serverless v2), S3 + CloudFront, Cognito, CloudWatch, SAM/CDK. One region, Multi-AZ managed data.Steady traffic making per-request pricing exceed an always-on service; a 15-minute or cold-start limit hit; relational query needs the key-value model cannot serve.
2. GrowthECS on Fargate, Aurora + ElastiCache (Valkey), SQS, CI/CD, Terraform or CDK, WAF in front.Need for GPUs, custom networking or the Kubernetes ecosystem; multiple teams needing independent deploys; a database tier that read replicas no longer relieve.
3. ScaleECS or EKS (Auto Mode or Karpenter) with commitments and Spot for the baseline and burst, EventBridge + SQS between services, OpenSearch where search is real, GitOps, tiered DR; multi-Region only for the tier-0 path.Org-level concerns: platform team, golden paths, SCP guardrails, cost allocation, per-tier RTO/RPO.
+ AI overlayBedrock or SageMaker endpoints, a vector store matched to latency and scale (pgvector, OpenSearch, S3 Vectors for cold or infrequent retrieval), GPU or accelerator capacity on Spot or reservations, cache for prompt/response reuse.Token or GPU spend dominating the bill; retrieval latency targets that the first vector store cannot meet.

Anti-patterns that interviewers like to plant, each with the fix:

  • Use everything — Kinesis, SQS, EventBridge and SNS all in one small system. Pick the one primitive that fits most flows; add another only for a genuinely different delivery shape (see the primitive comparison).
  • Kubernetes for a single app — one container on EKS with several node pools. Use Fargate directly, or ECS Express Mode, which provisions the service, load balancer, scaling, log group and alarms from an image and two roles.
  • Serverless everything at high steady volume — a hot API on Lambda + API Gateway costing multiples of an always-on service. Re-run the break-even; move the hot path to Fargate or EC2 and keep Lambda for the bursty edges.
  • DynamoDB for everything — relational data forced into key-value, then a search or query service bolted on to answer questions the table cannot. If you cannot list the access patterns up front, start relational.
  • CloudFront in front of uncacheable responses — personalised API output with a near-zero hit ratio adds a hop. Cache what is cacheable, or use it only for TLS termination and WAF at the edge on purpose.
  • Multi-Region for availability — Multi-AZ in one Region already survives a data-centre loss at a fraction of the complexity; go multi-Region only for a stated region-level RTO/RPO.
  • Logs to S3 to Athena for live debugging — batch queries are not an incident tool. Keep CloudWatch Logs (or a search store) hot and archive to S3 for cost.

Commitment Portfolio and Spot Fleet Engineering

The pricing levers and Savings Plans vs RIs sections give you the mental model. This topic adds what changed and what senior interviewers now probe: the four Savings Plan types (databases are covered by a plan now), how to buy commitments safely, and how to engineer Spot so that “up to 90% off” survives contact with production.

InstrumentCoversFlexibilityMax discount (docs)
Compute Savings PlanEC2, Fargate, LambdaAny family, size, Region, OS, tenancy; move EC2 → Fargate freelyUp to 66%
EC2 Instance Savings PlanOne EC2 family in one RegionSize, OS, tenancy, AZ within the familyUp to 72%
SageMaker AI Savings PlanSageMaker AI usageAcross instance families and Regions inside SageMakerSee plan-types page
Database Savings PlanAurora, RDS, DynamoDB, ElastiCache, DocumentDB, Neptune, Keyspaces, Timestream, DMS, OpenSearch Service — serverless and latest-generation provisionedAny engine, family, size, deployment option, Region; 1-year term, no upfrontUp to 35%
Reserved Instances / reserved capacitySpecific instance or service capacityLow; Convertible RIs can be exchangedUp to 72% (EC2 standard RI)
  • Order of operations: eliminate waste, rightsize, then commit to the stable baseline (Compute SP first; Database SP for the database baseline), then fill fault-tolerant work with Spot. A Savings Plan is a $/hour spend commitment and not a capacity reservation; if you must be sure instances exist (DR, launches), buy On-Demand Capacity Reservations and let the plan discount them.
  • Do not stack on one workload: a Database Savings Plan cannot be combined with an RDS Reserved Instance or DynamoDB reserved capacity discount for the same workload; split workloads between the two if you hold both.
  • Buy with a safety net: a plan with an hourly commitment of $100 or less, bought in the last seven days and in the same calendar month, can be returned with a full refund of upfront charges (subject to a return limit). Size with Savings Plans recommendations and the Purchase Analyzer, then watch utilization and coverage.
  • One list of actions: Cost Optimization Hub merges rightsizing, idle-resource and commitment recommendations and de-duplicates the savings (stopping an idle instance lowers what a Savings Plan could save). Use it to rank work; use Compute Optimizer for the per-resource detail.

Spot, engineered. You pay the Spot price in effect (there is no bidding; the optional max price defaults to the On-Demand price). Everything else is about not being surprised:

  1. Be flexible. Many instance types across families, sizes, generations and every AZ. Attribute-based instance type selection (InstanceRequirements, which requires vCPU count and memory) expresses that once and picks up new generations automatically.
  2. Use price-capacity-optimized — AWS’s recommendation for most Spot workloads: it picks pools with low interruption risk and low price. capacity-optimized still fits similarly priced pools or very costly interruptions; lowest-price raises interruption rates.
  3. Listen for two signals. The rebalance recommendation (elevated risk; best effort and sometimes arrives with the notice) and the two-minute interruption notice. Enable Auto Scaling Capacity Rebalancing to replace at-risk instances early; drain from the load balancer and checkpoint on SIGTERM.
  4. Pick where to run. Spot placement score rates Regions or AZs from 1 to 10 for your target capacity and instance mix; it is a guideline, never a guarantee.
  5. Keep a floor. A small On-Demand base so the service stays up when a pool dries up; Spot for everything above it.
# aws autoscaling update-auto-scaling-group --cli-input-json file://spot-asg.json
cat > spot-asg.json <<'EOF'
{
  "AutoScalingGroupName": "spot-workers",
  "CapacityRebalance": true,
  "MixedInstancesPolicy": {
    "InstancesDistribution": {
      "OnDemandBaseCapacity": 2,
      "OnDemandPercentageAboveBaseCapacity": 0,
      "SpotAllocationStrategy": "price-capacity-optimized"
    },
    "LaunchTemplate": {
      "LaunchTemplateSpecification": {"LaunchTemplateName": "worker", "Version": "$Latest"},
      "Overrides": [{"InstanceRequirements": {
        "VCpuCount": {"Min": 4, "Max": 8},
        "MemoryMiB": {"Min": 16384, "Max": 65536},
        "InstanceGenerations": ["current"],
        "BurstablePerformance": "excluded"}}]
    }
  }
}
EOF

Non-production scheduling is the cheapest lever and needs no discount negotiation: run dev stacks 12 hours on weekdays and you pay for about 60 of 168 hours, roughly a 64% cut. Drive it with EventBridge Scheduler using a universal target that calls ec2:stopInstances/startInstances, or the tag-driven Instance Scheduler on AWS solution (hub-and-spoke for multiple accounts). Remember stopped instances still bill for their EBS volumes.

From ClickOps to Governed IaC: Import, Drift and Guardrails

“We have a production account built by hand in the console. How do you move to Infrastructure as Code?” The wrong answer is a big-bang rewrite. The senior answer is a sequence that never stops production and ends with a state where drifting is hard and noticed fast: freeze the boundary, import by priority, make the pipeline the only writer, then detect what slips through. The Terraform concepts and tooling comparison sections cover the tools; this is the adoption and governance workflow they leave out.

  1. Draw the line. Everything new is IaC from today. No exceptions, no “just this one bucket”.
  2. Inventory and import by change frequency. Import the resources that change most (security groups, IAM roles, app stacks) first; leave stable foundations (the VPC) for later. Generate code, then review it — generated code is a baseline, not a design.
  3. Put a pipeline in front of apply. Plan or change set on every pull request, apply only from the main branch with an OIDC-assumed role (see end-to-end deployment).
  4. Make the pipeline the only writer. Org-level guardrails deny mutating calls from everyone except the pipeline and a break-glass role.
  5. Detect residual drift on a schedule and decide per finding: revert the resource, or adopt the change into code.
NeedCloudFormation / CDKTerraform
Adopt existing resourcesIaC generator: a region-wide scan (expires after 30 days) produces a template you import as a stack or migrate into a CDK app. Manual import needs a full-stack template and a DeletionPolicy on every imported resource.import blocks, plus terraform plan -generate-config-out=generated.tf (experimental since v1.5; the output file must not exist yet).
Preview a changeChange setterraform plan (saved plan file for the apply step)
Detect driftDrift detection per stack or resource. Only properties explicitly in the template are compared; unsupported resource types cannot be checked. AWS Config managed rule cloudformation-stack-drift-detection-check runs it periodically and on change.A scheduled plan in CI (a non-empty diff with no code change is drift)
State and lockingManaged by the service; none to operateRemote state in S3; prefer native use_lockfile — DynamoDB-based locking is deprecated and scheduled for removal in a future minor version
Multi-account rolloutStackSets or a pipeline per accountOne pipeline and state per account/environment; modules for reuse
# CloudFormation: start a drift check, poll it, list what changed
ID=$(aws cloudformation detect-stack-drift --stack-name prod-network \
       --query StackDriftDetectionId --output text)
aws cloudformation describe-stack-drift-detection-status --stack-drift-detection-id "$ID"
aws cloudformation describe-stack-resource-drifts --stack-name prod-network \
  --stack-resource-drift-status-filters MODIFIED DELETED
# Terraform: adopt a hand-built bucket, then generate its configuration
import {
  to = aws_s3_bucket.logs
  id = "my-existing-logs-bucket"
}
# terraform plan -generate-config-out=generated.tf   (review before apply)

terraform {
  backend "s3" {
    bucket       = "my-org-tfstate"
    key          = "prod/logging/terraform.tfstate"
    region       = "us-east-1"
    encrypt      = true
    use_lockfile = true   # needs s3:GetObject/PutObject/DeleteObject on key.tflock
  }
}
{
  "Version": "2012-10-17",
  "Statement": [{
    "Sid": "OnlyPipelineChangesProdInfra",
    "Effect": "Deny",
    "Action": ["ec2:Create*", "ec2:Delete*", "ec2:Modify*", "ec2:RunInstances", "ec2:TerminateInstances",
               "rds:Create*", "rds:Delete*", "rds:Modify*",
               "elasticloadbalancing:Create*", "elasticloadbalancing:Delete*", "elasticloadbalancing:Modify*"],
    "Resource": "*",
    "Condition": {"ArnNotLike": {"aws:PrincipalArn": ["arn:aws:iam::*:role/ci-deploy-*", "arn:aws:iam::*:role/break-glass"]}}
  }]
}

Service-to-Service Communication on ECS

Microservices on ECS need a way to find each other, spread load, survive task churn and, ideally, encrypt and observe the hop. AWS App Mesh used to fill the "mesh" slot but was discontinued on 30 Sep 2026, so any design that still names it is out of date. The live options are an internal load balancer, Cloud Map DNS, Service Connect and VPC Lattice. Pick by how much behaviour you need in the data path. Comparison of ECS and EKS as a whole is in ECS vs EKS; mesh concepts in general are in Service Mesh.

OptionHow it worksYou getWatch for
Internal ALB / NLBService registers tasks in a target group; callers hit the LB DNS name.Central health checks, L7 path or host routing, connection draining, and works with rolling, built-in blue/green and CodeDeploy deployments.Extra hop and an LB bill per environment; one LB can front many services through listener rules.
ECS service discovery (Cloud Map DNS)Tasks auto-register A or SRV records in a private namespace; callers resolve a name.No proxy, no LB, simple.Client-side load balancing only. Resolver caching delays removal of dead tasks. Capped at 1,000 tasks per service.
Service ConnectECS injects a managed Envoy sidecar; services publish short names in a shared namespace.Round-robin balancing, passive outlier detection, 2 automatic retries, 15 s default timeout, per-service CloudWatch metrics, optional TLS via AWS Private CA. No extra charge beyond the sidecar's CPU and memory.Same namespace required; existing tasks need a redeploy to see new endpoints; no CodeDeploy blue/green, standalone tasks or Windows; TLS needs awsvpc.
VPC LatticeECS registers tasks as IP targets in a Lattice target group behind a service network.Cross-VPC and cross-account reach (via RAM), IAM auth policies, header and path routing, weighted shifts, works across ECS, EKS, Lambda and EC2.A separate managed service with its own pricing model; extra moving parts for a single-cluster app.
client task                                   server task (service "orders")
+-----------------+                           +--------------------------+
| app --> http://orders:8080                  | Envoy sidecar --> app :8080|
|        |                                    |   ^                      |
| Envoy sidecar  --- round-robin, retries --> | (listens on containerPort)|
+-----------------+     picks a healthy task  +--------------------------+
        names resolved from the Cloud Map namespace (e.g. "prod")
{
  "serviceConnectConfiguration": {
    "enabled": true,
    "namespace": "prod",
    "services": [{
      "portName": "http",
      "discoveryName": "orders",
      "clientAliases": [{ "port": 8080, "dnsName": "orders" }],
      "timeout": { "idleTimeoutSeconds": 300, "perRequestTimeoutSeconds": 15 }
    }]
  }
}

The container needs a named port for portName to resolve, and the task needs task-level CPU and memory with headroom for the proxy (roughly 256 CPU units and 64 MiB extra, more at high request rates).

  • Default choice. Service Connect for east-west traffic inside one ECS footprint; an ALB only at the edge. Move to Lattice when callers span VPCs, accounts or compute types, or you need IAM-based service auth.
  • Cloud Map alone is fine for stateless calls where a failed connection is cheap and clients already retry. It is the wrong tool when you want health-aware routing without writing it.
  • EKS callers. The App Mesh migration guidance for EKS points to VPC Lattice; ECS callers point to Service Connect.

Lambda: Scaling, Event-Source Mappings and Failure Handling

Lambda has three invocation paths and each one assigns retry responsibility differently. Most production incidents come from assuming the wrong one: a poison SQS message that burns the DLQ, a stream shard blocked for days, or a 429 storm that nobody retries. The lifecycle and cold-start story is in Lambda at Scale; this topic is about what happens when load or failures arrive.

PathWho retriesHow it scalesWhere failures go
Synchronous (API Gateway, ALB, function URL, SDK Invoke)The caller. Throttle returns 429.Up to 1,000 new execution environments per 10 s per function, bounded by the account limit.The error response to the caller.
Asynchronous (S3, SNS, EventBridge, SDK Event)Lambda. Function errors: 2 retries by default (0–2). Throttles and system errors: retried until MaximumEventAge (60 s–6 h).Internal queue in front of the function; payload up to 1 MB.On-failure destination or DLQ; otherwise the event is discarded.
Poll-based (SQS, Kinesis, DynamoDB Streams, Kafka)The event source mapping (ESM) re-reads the batch.SQS standard: 5 batches, +300 invokes/min, cap 1,250. Streams: one batch per shard, or ParallelizationFactor up to 10.SQS redrive policy to a DLQ; streams to an on-failure destination.

Async path

event --> [Lambda internal queue] --> invoke --ok--> on-success destination (optional)
                 ^                     |
                 |   retry (max 2)     +--error--> retry ... --> on-failure destination / DLQ
                 +--- throttled / 5xx: held up to MaximumEventAge (default 6 h)
  • Destinations vs DLQ. A DLQ (SQS or SNS) catches failures only. Destinations route success and failure, to SQS, SNS, another Lambda, EventBridge, or S3 (failure only), with a richer record (request, response or error). AWS treats destinations as the preferred option; if both are set, failures go to both.
  • Idempotency is mandatory. Async and poll paths are at-least-once. Key the side effect on a business id (conditional PutItem, or the Powertools idempotency utility) so a retry or redelivery cannot double-charge.
  • SQS partial failure. Return batchItemFailures (enable ReportBatchItemFailures) so only failed messages return. On FIFO, stop at the first failure and report it plus every unprocessed message, so order within a message group is preserved.
  • Streams default to "block the shard". With default settings (maximum record age and retry attempts both -1, meaning infinite) one bad record can stall a shard until it ages out of the stream (24 hours for DynamoDB Streams, the stream's retention for Kinesis). Set MaximumRetryAttempts, MaximumRecordAgeInSeconds, BisectBatchOnFunctionError and an on-failure destination so a poison record is isolated and skipped.

Protecting what sits downstream

Concurrency is invocation rate times duration, so a 10x burst can become 10x database connections in seconds. Pick the control by where the pressure lands.

ControlEffectUse when
ESM MaximumConcurrency (SQS, 2–1,000)Poller stops fetching; messages stay queued.Queue consumers hitting a database or API with a rate limit.
Reserved concurrencyHard per-function cap and guaranteed slice (also lowers the pool left for others).Sync or async functions; isolating a noisy function. With SQS it throttles batches, which return to the queue and burn receive counts.
SQS provisioned modeDedicated pollers (2–200 min, 2–10,000 max; default 2 and 200); faster scale-out.Spiky queues where default ramp is too slow.
RDS Proxy / pooled HTTP clientMultiplexes connections.Any relational backend: caps connections, not invocations.
# async: fail fast, keep failed events for replay
aws lambda put-function-event-invoke-config --function-name notify \
  --maximum-retry-attempts 1 --maximum-event-age-in-seconds 3600 \
  --destination-config '{"OnFailure":{"Destination":"arn:aws:sqs:us-east-1:123456789012:notify-failed"}}'

# stream: isolate poison records instead of blocking the shard
aws lambda create-event-source-mapping --function-name ingest \
  --event-source-arn arn:aws:kinesis:us-east-1:123456789012:stream/events \
  --starting-position LATEST --batch-size 200 --parallelization-factor 4 \
  --bisect-batch-on-function-error --maximum-retry-attempts 3 \
  --maximum-record-age-in-seconds 3600 \
  --destination-config '{"OnFailure":{"Destination":"arn:aws:sqs:us-east-1:123456789012:ingest-failed"}}'

Lambda in 2026: Which Form Factor, and When

"Lambda" is no longer one thing. Over 2025 and 2026 the same service grew to five options that differ on programming model, concurrency, billing and where code runs. Interviewers now probe whether you can pick among them instead of defaulting to "function plus API Gateway". Baseline mechanics are in Lambda at Scale and the Lambda card; failure and scaling behaviour is in Scaling and Failure Handling.

OptionModel and concurrencyBillingPick it when
Event Functions (the classic Lambda)Handler per event; one request per execution environment; Firecracker microVM, multi-tenant; 15 min max.Requests plus wall-clock GB-seconds (INIT included for on-demand).Bursty, event-driven, queue consumers, glue. The default.
Durable functions (a mode of Event Functions)Checkpoint and replay; a run lasts up to 1 year; waits suspend with no compute charge.Normal duration while running, plus per-operation and stored-data charges.Multi-step, human-in-the-loop, long polling, saga-style workflows written as code.
Managed InstancesEvent Functions on EC2 in your account via a capacity provider; many concurrent requests per environment; containers on Nitro, capacity provider is the security boundary.EC2 price (Savings Plans and RIs apply) plus a 15% management fee on top (discounts do not reduce the fee).High, steady, predictable volume; special CPUs or memory ratios; Lambda ergonomics without per-ms pricing.
Web FunctionsYour HTTP server listens on a port; up to 128 concurrent requests per environment; Node.js 24 on Arm64 at launch; VPC supported.Active CPU time plus memory for the environment's life.Express, Hono, Fastify or Next.js apps and I/O-heavy APIs where idle wait would waste per-ms billing.
MicroVMsStateful VM-isolated sandbox from a Dockerfile image; own HTTPS URL; HTTP/2, gRPC, WebSockets; you control lifecycle.Baseline compute while running, plus active use above baseline.Per-user or per-job sandboxes for untrusted or AI-generated code.

Availability is uneven: Web Functions and MicroVMs launched in a short list of Regions, and Web Functions started on a single runtime. Check Region and runtime before committing.

Durable functions: how replay works

invoke 1:  step A (runs, result checkpointed) -> step B (runs, checkpointed) -> wait 3 days (suspend, $0 compute)
invoke 2:  code re-runs from the top; A and B return stored results instantly;
           continues after the wait -> step C (runs, checkpointed) -> done
  • Determinism rule. Everything outside a step must give the same answer on replay. Do not read the clock, generate random ids, or call services outside a step: the replayed value differs and the run breaks.
  • Limits to know. 30,000 durable operations per execution and 1 MB per checkpoint or callback payload (larger state goes to EFS or S3 Files with a pointer), 100 MB of persisted data per execution. Each step retries independently with configurable backoff.
  • Versus Step Functions. Durable functions keep orchestration in application code inside Lambda. Step Functions is graph-defined with a visual designer and native integrations with 220+ services. Pick code-first for logic tightly coupled to business rules, Step Functions for cross-service, cross-team flows (see Step Functions).

Cold start and latency toolbox

ToolWhat it doesConstraint
SnapStartRestores a cached snapshot of an initialized environment.Java 11+, Python 3.12+, .NET 8+; published versions or aliases only; not with provisioned concurrency, EFS, or >512 MB ephemeral storage.
Provisioned concurrencyKeeps N environments initialized.Billed while allocated; version or alias only.
Response streamingCuts time to first byte; up to 200 MB responses (first 6 MB uncapped, then about 2 MB/s).Node.js managed runtimes natively (check other runtimes; otherwise a custom runtime or the Lambda Web Adapter); billed for full duration even if the client disconnects.
Managed Instances / Web FunctionsMulti-concurrent environments share warm capacity.Code must be thread-safe and avoid per-request global state.

S3 Conditional Writes: Compare-and-Swap on Object Storage

S3 can now enforce a precondition on a write, which turns a bucket into a primitive for locks, leader election and optimistic concurrency without DynamoDB or an external coordinator. Without a precondition, concurrent PUTs to one key silently resolve last-writer-wins. Two headers, both requiring SigV4 and usable on PutObject, CopyObject and CompleteMultipartUpload:

HeaderMeaningPermissionsTypical use
If-None-Match: *Write only if no current object has this key (create-if-absent)s3:PutObjectClaim a lock/lease file, dedupe an upload, protect immutable datasets
If-Match: <ETag>Write only if the current object's ETag still equals yours (compare-and-swap)s3:PutObject + s3:GetObjectOptimistic update of a manifest, checkpoint or table-format metadata pointer

The same idea applies to deletes (DeleteObject/DeleteObjects with If-Match, in general purpose and directory buckets; evaluated against the current version) and to conditional reads on GET/HEAD/COPY by ETag or last-modified. There is no extra charge, but failed requests are billed as normal requests.

  • Outcomes. Success is 200. Lost race or mismatch: 412 Precondition Failed; the first writer to finish wins. 409 Conflict appears for concurrent requests, or when a delete completes first (If-None-Match). If-Match on a key that no longer exists, or whose current version is a delete marker, returns 404: re-create it. After a 409 on CompleteMultipartUpload you must start a new multipart upload.
  • Versioned buckets. If-None-Match only looks at the current version; a delete marker on top counts as absent.
  • Multipart. Conditions are evaluated at CompleteMultipartUpload, not on in-progress parts. If another client wins the key meanwhile, the completion fails with 412.
  • Enforcement. Writers can simply omit the header, which defeats the protocol. A bucket or IAM policy can require it with the s3:if-none-match / s3:if-match condition keys. Scope the deny with s3:ObjectCreationOperation so CreateMultipartUpload/UploadPart, which cannot carry the header, are not blocked.
{
  "Version": "2012-10-17",
  "Statement": [{
    "Sid": "RequireCreateIfAbsentOnLocks",
    "Effect": "Deny",
    "Principal": "*",
    "Action": "s3:PutObject",
    "Resource": "arn:aws:s3:::my-bucket/locks/*",
    "Condition": {
      "Null": { "s3:if-none-match": "true" },
      "Bool": { "s3:ObjectCreationOperation": "true" }
    }
  }]
}
import boto3
from botocore.exceptions import ClientError

s3 = boto3.client("s3")

def try_claim(bucket: str, key: str, owner: str) -> bool:
    """Create-if-absent: exactly one caller gets True."""
    try:
        s3.put_object(Bucket=bucket, Key=key, Body=owner.encode(), IfNoneMatch="*")
        return True
    except ClientError as e:
        if e.response["ResponseMetadata"]["HTTPStatusCode"] in (409, 412):
            return False          # someone else holds it (or a racing delete)
        raise

def cas_update(bucket: str, key: str, mutate) -> None:
    """Optimistic read-modify-write with If-Match; retries on a lost race."""
    while True:
        obj = s3.get_object(Bucket=bucket, Key=key)
        new_body = mutate(obj["Body"].read())
        try:
            s3.put_object(Bucket=bucket, Key=key, Body=new_body, IfMatch=obj["ETag"])
            return
        except ClientError as e:
            if e.response["ResponseMetadata"]["HTTPStatusCode"] not in (409, 412):
                raise             # 404 (key deleted) and other errors are the caller's problem

S3 Express One Zone & Directory Buckets

Express One Zone is the S3 class for the case where request latency, not storage price, is the constraint: training-data shards, shuffle and checkpoint spill, hot Iceberg/Parquet tables, log tailing. It lives only in directory buckets, a separate bucket type bound to one AZ that you choose (by AZ ID, so you can co-locate with compute). Data is stored redundantly across devices inside that AZ, the class is designed for 99.95% availability, and an AZ loss means data loss, so it is a cache or working tier, never your only copy.

DimensionGeneral purpose bucket (Standard)Directory bucket (Express One Zone)
PlacementRegional, ≥3 AZsOne AZ you pick; name base--use1-az4--x-s3
LatencyMilliseconds, higher and more variable than ExpressConsistent single-digit ms; docs cite up to 10x faster than Standard
Request rate3,500 write / 5,500 read per prefix, auto-partitionedUp to 2,000,000 GET and 200,000 PUT per second per bucket; no prefix tuning, keys not lexicographically ordered in LIST
NamespaceFlat keys, prefixesHierarchical directories (/ only delimiter), created and removed automatically
AuthN/ZSigV4 per requests3express:CreateSession, 5-minute bucket-scoped session credentials handled by the SDK
Access boundaryBucket, prefix, tag, objectBucket policy, or access points scoped by prefix and API operation; Block Public Access always on, ACLs off
Features absent—Versioning, Object Lock, ACLs, storage-class transitions (lifecycle can only expire objects and abort multipart uploads)
  • Append. Express is the only S3 class that supports appending: PutObject with x-amz-write-offset-bytes equal to the current size. Up to 5 GB per append and at most 10,000 appends per object (each append counts as a part; CopyObject resets the count). Good for log and video-segment writers.
  • Conditional writes work here too (see above), as do conditional deletes.
  • Data load. The console import action creates an S3 Batch Operations job copying from a general purpose bucket. Common pattern: durable copy in Standard, hydrated Express copy next to the GPU/CPU fleet, read through Mountpoint for S3 or the Hadoop S3A connector.
  • Local Zones. Directory buckets can also be created in Local Zones for data residency: ordinary Local Zones support only the One Zone-IA class, while Dedicated Local Zones support both Express One Zone and One Zone-IA.
  • Cost shape. Higher storage price than Standard, lower request price; it wins when you do many requests per stored GB. Keep compute in the same AZ or you lose the latency edge (there is no extra data-transfer charge for cross-AZ access within the Region). See the pricing page for current numbers.
aws s3api create-bucket --bucket ml-shards--use1-az4--x-s3 --region us-east-1 \
  --create-bucket-configuration 'Location={Type=AvailabilityZone,Name=use1-az4},Bucket={DataRedundancy=SingleAvailabilityZone,Type=Directory}'

# append a chunk: write-offset must equal the object's current size in bytes
aws s3api put-object --bucket ml-shards--use1-az4--x-s3 --key logs/run-42.log \
  --body chunk-002.bin --write-offset-bytes 1048576

S3 Tables: Managed Apache Iceberg on S3

A table bucket is the third S3 bucket type (after general purpose and directory). Inside it you create namespaces and tables; every table is an Apache Iceberg table (Iceberg only, no Delta or Hudi) and a first-class resource with its own ARN and resource policy. The point is that AWS runs the Iceberg housekeeping that teams otherwise script with Spark or Glue jobs. AWS cites up to 3x faster queries and up to 10x more transactions per second than self-managed Iceberg tables on plain S3 (launch claims; measure your own workload).

Maintenance taskWhat it doesDefaults and knobs
CompactionMerges small files into larger ones and applies row-level deletesTarget file size 512 MB (configurable 64–512 MB); strategy auto, binpack, sort or z-order (the last two need a sort order on the table and s3tables:GetTableData)
Snapshot managementExpires old Iceberg snapshotsKeeps at least 1 snapshot; default max age 120 hours (5 days); both configurable per table
Unreferenced file removalDeletes data files no snapshot referencesMarked noncurrent after 3 days, permanently deleted 10 days later (bucket-level; no recovery)
  • Access paths. Enable the integration with the Glue Data Catalog and Athena, Redshift, EMR, Quick, Data Firehose, Glue ETL and SageMaker Unified Studio see the tables. Use Lake Formation grants for column- and row-level security. Spark, PyIceberg and other Iceberg engines connect through the Glue Iceberg REST endpoint.
  • Newer capabilities. An Intelligent-Tiering storage class for tables (Frequent to Infrequent after 30 days, to Archive Instant Access after 90; compaction only touches the Frequent tier) and replication of tables across Regions and accounts.
  • S3 Metadata is built on this: for a general purpose bucket it maintains read-only, managed Iceberg tables in your account, a journal table (near-real-time change log) and an optional live inventory table (hourly refresh). Query them with SQL instead of crawling LIST.
  • Quotas. 100 table buckets per Region per account; 10,000 tables and 10,000 namespaces per table bucket (raise via Support).
TB=$(aws s3tables create-table-bucket --name analytics-tb --query arn --output text)
aws s3tables create-namespace --table-bucket-arn "$TB" --namespace sales
aws s3tables create-table --table-bucket-arn "$TB" --namespace sales --name orders --format ICEBERG \
  --metadata '{"iceberg":{"schema":{"fields":[
    {"name":"order_id","type":"long","required":true},
    {"name":"amount","type":"decimal(10,2)"},
    {"name":"ts","type":"timestamp"}]}}}'

# keep two weeks of time-travel history instead of the 120 h default
aws s3tables put-table-maintenance-configuration --table-bucket-arn "$TB" \
  --namespace sales --name orders --type icebergSnapshotManagement \
  --value '{"status":"enabled","settings":{"icebergSnapshotManagement":{"minSnapshotsToKeep":5,"maxSnapshotAgeHours":336}}}'

S3 Vectors: Object-Priced Vector Search

S3 Vectors (generally available since late 2025) adds a fourth bucket type. A vector bucket holds vector indexes; you PutVectors float32 embeddings with optional metadata and run approximate nearest-neighbour QueryVectors. It is serverless, with no capacity to provision, and is built for large, mostly cold corpora where a dedicated vector database would be overpriced (AWS claims up to 90% lower total cost). It is a pure vector store: no keyword or full-text search.

LimitValue
Vector buckets per Region per account / indexes per bucket10,000 / 10,000
Vectors per indexUp to 2 billion (20 trillion per bucket)
Dimensions1–4,096; float32 only; cosine or euclidean
Metadata per vector40 KB total, 50 keys, filterable part 2 KB; up to 10 non-filterable keys per index
Write path500 vectors per PutVectors; up to 1,000 put/delete requests per second per index (2,500 vectors per second)
QueryTop-K up to 10,000, 100 results per page; ~100 ms or better for frequent queries, under 1 s for infrequent ones
  • Immutable index config. Name, dimension, distance metric and non-filterable keys cannot change after creation. A new embedding model means a new index and a re-embed. Encryption defaults to SSE-S3; SSE-KMS can be set per bucket or index.
  • Metadata filtering narrows a query, but a query that filters or returns metadata needs s3vectors:GetVectors in addition to s3vectors:QueryVectors (otherwise 403). Index mode CLASSIC applies filters in tandem with the search (a filtered query can return fewer than top-K results); ENHANCED pre-filters before it and is the default for vector buckets created on or after 2026-09-30.
  • Integrations. Bedrock Knowledge Bases can use an index as its vector store; OpenSearch can use S3 Vectors as a storage engine in managed clusters, or you can export a hot subset to OpenSearch Serverless when you need sub-100 ms at high QPS and hybrid (keyword plus vector) search.
import boto3

s3v = boto3.client("s3vectors")
s3v.create_vector_bucket(vectorBucketName="kb-vectors")
s3v.create_index(
    vectorBucketName="kb-vectors", indexName="docs-v1",
    dataType="float32", dimension=1024, distanceMetric="cosine",
    metadataConfiguration={"nonFilterableMetadataKeys": ["chunk_text"]},  # big text: stored, not filterable
)
s3v.put_vectors(
    vectorBucketName="kb-vectors", indexName="docs-v1",
    vectors=[{"key": "doc1#0", "data": {"float32": [0.01] * 1024},
              "metadata": {"tenant": "acme", "chunk_text": "..."}}],
)
res = s3v.query_vectors(
    vectorBucketName="kb-vectors", indexName="docs-v1", topK=5,
    queryVector={"float32": [0.01] * 1024},
    filter={"tenant": "acme"}, returnMetadata=True, returnDistance=True,
)
print([v["key"] for v in res["vectors"]])

S3 Object Lock: WORM, Retention Modes & Legal Holds

Object Lock gives write-once-read-many protection per object version, which is the control behind ransomware-resistant backups and SEC/FINRA-style records retention. It only works in versioned buckets (versioning cannot be suspended afterwards) and has been assessed by Cohasset Associates against SEC 17a-4(f), FINRA 4511 and CFTC 1.31. Enabling it on an existing bucket through the API or CLI turns versioning on for you; new buckets can be created with it enabled.

ControlWho can remove or shorten itTypical use
Governance retentionPrincipals with s3:BypassGovernanceRetention sending x-amz-bypass-governance-retention:true (the console sends it by default)Protect against accidents and malware; rehearse a retention policy
Compliance retentionNobody, including root: mode cannot change and the period cannot shorten (it can be extended). Only closing the AWS account deletes the data earlyRegulatory WORM
Legal holdAnyone with s3:PutObjectLegalHold; no expiry, independent of retentionLitigation freeze of specific versions
Event hold (variable retention)Released by authorized principals; retain-until-date is set to release time plus a preset durationRetention that starts at a future event (contract close, audit complete)
  • Default and per-object settings. A bucket default retention (days or years, mode) applies to every new version; an individual version can carry its own retain-until-date. Bound allowed periods with the s3:object-lock-remaining-retention-days condition key. Use S3 Batch Operations to apply or extend retention across existing objects.
  • Deletes still “work”. A DELETE without a version ID adds a delete marker and leaves locked versions intact; deleting a locked version is what is refused.
  • Replication. If the source has Object Lock, the destination must too, and the replication role needs s3:GetObjectRetention and s3:GetObjectLegalHold. Replica modification sync keeps lock settings in sync.
  • Neighbours. EBS Snapshot Lock mirrors the same two modes (cooling-off up to 72 h for compliance); the legacy Glacier Vault Lock has no governance mode (see Glacier). Directory buckets (Express One Zone) do not support Object Lock.
aws s3api create-bucket --bucket audit-logs-123 --region us-west-2 \
  --create-bucket-configuration LocationConstraint=us-west-2 --object-lock-enabled-for-bucket
aws s3api put-object-lock-configuration --bucket audit-logs-123 --object-lock-configuration \
  '{"ObjectLockEnabled":"Enabled","Rule":{"DefaultRetention":{"Mode":"COMPLIANCE","Years":7}}}'

# per-version controls (rehearse in GOVERNANCE first)
aws s3api put-object-retention --bucket audit-logs-123 --key 2026/10/trail.json.gz \
  --retention '{"Mode":"GOVERNANCE","RetainUntilDate":"2027-10-20T00:00:00Z"}'
aws s3api put-object-legal-hold --bucket audit-logs-123 --key 2026/10/trail.json.gz --legal-hold Status=ON
aws s3api delete-object --bucket audit-logs-123 --key 2026/10/trail.json.gz \
  --version-id "$VID" --bypass-governance-retention

S3 Replication & Multi-Region Access Points

S3 replication copies new object versions asynchronously between buckets: CRR across Regions (latency, compliance, DR) or SRR within one Region (log aggregation, prod/test copies, account separation). Both source and destination need versioning; S3 assumes an IAM role you provide. Rules can filter by prefix or tag, change the destination storage class, and replicate to several destinations.

NeedFeatureDetail
Existing objects, failed objects, replicas of replicasBatch ReplicationOn-demand S3 Batch Operations job; live rules only cover new objects, and a replica is not re-replicated by a chained rule
Predictable lagReplication Time Control (RTC)99.99% of objects within 15 minutes; SLA is 99.9% in 15 minutes per Region pair per month; adds metrics and events
Active-activeTwo-way rules + replica modification syncOne rule each direction; sync carries tag, ACL and Object Lock metadata changes made on replicas back to the source
Encrypted objectsSSE-KMS replication settingsKMS-encrypted objects are skipped unless SseKmsEncryptedObjects and a destination key are configured
DeletesDeleteMarkerReplicationV2 configuration can replicate delete markers; by default cross-account delete markers are not replicated
  • Not replicated by default: pre-existing objects, replicas created by another rule, and objects in Glacier Flexible Retrieval, Deep Archive or the Intelligent-Tiering archive tiers (restore and copy them first). Changing a rule's destination does not re-send what already replicated.
  • Object Lock on the source requires Object Lock on the destination plus s3:GetObjectRetention/s3:GetObjectLegalHold for the role (see Object Lock).
  • Multi-Region Access Points (MRAP) give one global endpoint over buckets in several Regions. Requests route to the closest healthy bucket (it uses AWS Global Accelerator), SDKs sign with SigV4A, and you can run active-active or active-passive. A failover control flips routing in about 2 minutes. MRAP does not replicate data: you must create replication rules, ideally two-way, or the passive bucket will be stale and writes made after failover will not flow back.
{
  "Role": "arn:aws:iam::111122223333:role/s3-replication",
  "Rules": [{
    "ID": "crr-to-usw2",
    "Priority": 1,
    "Status": "Enabled",
    "Filter": {},
    "DeleteMarkerReplication": { "Status": "Enabled" },
    "SourceSelectionCriteria": { "ReplicaModifications": { "Status": "Enabled" } },
    "Destination": {
      "Bucket": "arn:aws:s3:::dr-bucket-usw2",
      "StorageClass": "STANDARD_IA",
      "ReplicationTime": { "Status": "Enabled", "Time": { "Minutes": 15 } },
      "Metrics": { "Status": "Enabled", "EventThreshold": { "Minutes": 15 } }
    }
  }]
}

Apply with aws s3api put-bucket-replication --bucket src-bucket-use1 --replication-configuration file://repl.json, then run a Batch Replication job for the backlog.

S3 Files: A Shared NFS View of an S3 Bucket

Amazon S3 Files (generally available since April 2026) is a serverless, EFS-based file system whose contents are a general purpose bucket or a prefix of one. Linux compute (EC2, ECS, EKS, Fargate, Lambda, Batch) mounts it over NFS and gets file semantics (partial writes, append, rename, locking, close-to-open consistency) while the data stays in S3 as the source of truth and remains reachable through the S3 API. It closes the long-standing gap behind “S3 is not a filesystem” in the object model: S3 itself is still an object store, S3 Files is the translation layer.

OptionSemanticsData lives inPick when
Mountpoint for S3Object-native: read large files, create new ones; no in-place edits, no locking, no symlinksS3Read-heavy ML/analytics streaming from one writer, lowest cost
S3 FilesFull NFS semantics, shared by thousands of clients, synced to S3S3 (hot working set cached on file storage)File-based tools and agents that must operate on existing S3 data without copying
EFSFull NFS, standaloneEFS (copy in/out yourself)Shared POSIX state that is not an S3 dataset
FSx for LustreParallel POSIX for HPC, optional S3 linkLustreExtreme single-file-system throughput for HPC
  • Setup. Bucket must have versioning on. Create the file system with the bucket (or prefix) ARN and an IAM role S3 Files assumes (it also manages EventBridge rules named DO-NOT-DELETE-S3-Files*), add a mount target per AZ, allow TCP 2049, then mount with the s3files helper from amazon-efs-utils 3.0.0 or newer (EKS uses the EFS CSI driver). Client IAM: s3files:ClientMount.
  • Sync model. Changes made in S3 appear in the file system typically within seconds (up to 2,400 object changes per second per file system). File writes are batched for about 60 seconds and then exported as one new object version (up to 800 files per second). If both sides change the same file, the bucket wins and the file system copy goes to a lost-and-found directory: pick one primary writer per path.
  • Cost shape. Only the active working set sits on file storage; a configurable expiry (1–365 days, default 30) and a file-size threshold decide what is cached. Reads of 1 MiB or more stream straight from S3 at plain GET cost.
  • Quotas. Up to 25,000 concurrent connections; file size up to 48 TiB; one mount target per AZ per file system.
aws s3api put-bucket-versioning --bucket research-data --versioning-configuration Status=Enabled
aws s3files create-file-system --region us-east-1 \
  --bucket arn:aws:s3:::research-data --role-arn arn:aws:iam::111122223333:role/s3files-sync
# after the file system is available and has a mount target in this instance's AZ:
sudo dnf install -y amazon-efs-utils
sudo mkdir -p /mnt/research
sudo mount -t s3files fs-0abc123def456 /mnt/research

EBS Snapshots & io2 Block Express: Lifecycle, Protection and Restore Speed

The volume-type table is in EBS: volume types; this guide covers what happens to the data protection side. Two facts anchor the volume side: every io2 volume created after 21 Nov 2023 is already io2 Block Express (older io2 volumes convert by modifying size or IOPS), and Block Express is the only EBS type with sub-millisecond latency (average under 500 µs at 16 KiB I/O), 99.999% durability, 1,000 IOPS per GiB and 256,000 IOPS / 4,000 MiB/s / 64 TiB per volume, versus io1 at 99.8–99.9% durability and 50 IOPS per GiB. The snapshot lifecycle is where cost and recovery risk hide:

volume --snapshot--> STANDARD tier (incremental, regional, S3-backed)
                        |  archive rule / modify-snapshot-tier
                        v
                     ARCHIVE tier (full copy, 90-day minimum, restore up to 72 h)
                        |  delete
                        v
                   RECYCLE BIN (retention rule: snapshots/AMIs 1-365 d, volumes 1-7 d)
                        |  expiry
                        v
                     permanently deleted        (Snapshot Lock blocks deletion at any stage)
CapabilityPurposeKey facts
Snapshots ArchiveCheaper long-term retentionArchived snapshots are full copies; 90-day minimum billing; restore takes up to 72 h (temporary 1–180 days or permanent); cannot create a volume or AMI from an archived snapshot; best for monthly/quarterly/yearly snapshots with real unique data (AWS rule of thumb: worth it if savings exceed about 25% of snapshot size); 25 archived snapshots per volume default
Recycle BinUndo accidental deletesTag-level or Region-level retention rules; snapshots and EBS-backed AMIs 1–365 days, volumes 1–7 days; optional rule lock with a 7–30 day unlock delay; longest matching rule wins
Snapshot LockWORM / ransomware protectionGovernance (immediate; IAM-permitted users can change it) or compliance (optional cooling-off 1–72 h, then no unlock or shortening, only extension); duration 1 day to 36,500 days; shared and copied snapshots still work
Fast Snapshot Restore (FSR)Full-speed new volumesEnabled per snapshot per AZ; volumes are fully initialized at creation; default quota 5 FSR snapshots per Region
Volume initialization ratePredictable lazy-load speedProvisioned rate 100–300 MiB/s on create-volume; if you pass a rate for an FSR-enabled snapshot, the rate wins and FSR is not used, so omit it when you want FSR
Data Lifecycle ManagerAutomate all of the aboveTag-targeted policies: schedule, retention, copy tags, cross-Region copy (up to 3 destinations), cross-account share, archive rule, fast-restore rule; 100 custom policies per Region
  • Lazy loading is the restore trap. A volume restored from a snapshot fetches blocks from S3 on first touch, so the first read of each block is slow whatever the volume type. For DR runbooks with an RTO, enable FSR on the snapshots you will restore, or set a volume initialization rate, or pre-read the device before cut-over.
  • Deleting a snapshot is cheap to reason about, not to bill. Blocks still referenced by later incrementals stay; only unreferenced blocks are freed. Archiving a snapshot keeps referenced data on the standard tier and bills it to the next snapshot in the lineage.
  • Encryption and DR. Cross-Region copies need a destination key; only snapshots encrypted with a customer managed key can be shared. AWS Backup can drive the same lifecycle (including archive) with cross-account vaults if you want one policy plane across services.
aws dlm create-lifecycle-policy --description "Daily DB snapshots" --state ENABLED \
  --execution-role-arn arn:aws:iam::111122223333:role/AWSDataLifecycleManagerDefaultRole \
  --policy-details '{
    "ResourceTypes":["VOLUME"],
    "TargetTags":[{"Key":"Backup","Value":"daily"}],
    "Schedules":[{
      "Name":"DailyAt0300","CopyTags":true,
      "CreateRule":{"Interval":24,"IntervalUnit":"HOURS","Times":["03:00"]},
      "RetainRule":{"Count":14},
      "FastRestoreRule":{"AvailabilityZones":["us-east-1a"],"Count":2},
      "CrossRegionCopyRules":[{"TargetRegion":"us-west-2","Encrypted":true,"RetainRule":{"Interval":7,"IntervalUnit":"DAYS"}}]
    }]}'

aws rbin create-rule --resource-type EBS_SNAPSHOT --retention-period RetentionPeriodValue=14,RetentionPeriodUnit=DAYS
aws ec2 lock-snapshot --snapshot-id snap-0abc123def4567890 --lock-mode compliance --cool-off-period 24 --lock-duration 365
aws ec2 modify-snapshot-tier --snapshot-id snap-0abc123def4567890 --storage-tier archive
aws ec2 restore-snapshot-tier --snapshot-id snap-0abc123def4567890 --temporary-restore-days 7

EFS Lifecycle: IA, Archive and Choosing a Throughput Mode

EFS cost has two independent dials: where files live (Standard, Infrequent Access, Archive) and how throughput is bought (Elastic, Provisioned, Bursting). They interact: the Archive class only exists on file systems using Elastic throughput and General Purpose performance mode, and Regional file systems only.

ClassFirst-byte latencyPer-file billing floorMinimum durationAvailability
Standard (SSD)Sub-millisecond reads, ~2.7 ms writesnonenone99.99% Regional / 99.9% One Zone
Infrequent AccessTens of ms128 KiB; 2 KiB of metadata stays in Standardnone99.99% Regional / 99.9% One Zone
ArchiveTens of ms128 KiB; 2 KiB metadata in Standard90 days (pro-rated charge if deleted or truncated earlier)99.9%, Regional only
  1. Three lifecycle policies per file system: Transition into IA (default 30 days without access), Transition into Archive (default 90 days; must be later than the IA setting, files go Standard or IA to Archive), and Transition into Standard (default: never; AFTER_1_ACCESS pulls a file back on its first read). The inactivity timer counts file reads and writes in Standard; listing a directory does not reset it.
  2. Metering. IA and Archive are metered in 4 KiB steps, access to them in 128 KiB steps, and each file costs at least 128 KiB. Since a November 2023 change, files under 128 KiB also tier to IA, but tiny files are still a poor fit: leave them in Standard or compact them.
  3. Pick the throughput mode by load shape. Elastic: spiky, unpredictable, or average-to-peak ratio at or below ~5%. Provisioned: you know the number or run above ~5% average-to-peak; you pay a fixed MiBps-month for the amount over what your Standard data already earns. Bursting: throughput should simply scale with stored data.
  4. Bursting arithmetic. Baseline is 50 KiBps per GiB stored in Standard; burst is 100 MiBps per TiB (minimum 100 MiBps, up to the Region cap). Reads are metered at one third, so read throughput can be 3x. A 100 GiB file system earns a 5 MiBps baseline and, after a quiet day, can burst at 100 MiBps for about 72 minutes; a 1 TiB file system bursts about 12 hours per day. Watch BurstCreditBalance; when it trends to zero, move to Elastic or Provisioned.
  5. Switching rules. You can change mode and raise Provisioned throughput freely, but after switching to Provisioned (or lowering the amount) you cannot return to Elastic/Bursting or lower it again for 24 hours. Plan the order of operations and keep a rollback that does not need the blocked step.
# choose the mode explicitly (CloudFormation/API default is bursting)
aws efs update-file-system --file-system-id fs-0abc123 --throughput-mode elastic
# measured steady load of ~256 MiB/s: buy it flat instead
aws efs update-file-system --file-system-id fs-0abc123 --throughput-mode provisioned --provisioned-throughput-in-mibps 256

# lifecycle: IA at 14 d, Archive at 180 d, return to Standard on first access
aws efs put-lifecycle-configuration --file-system-id fs-0abc123 --lifecycle-policies \
  TransitionToIA=AFTER_14_DAYS TransitionToArchive=AFTER_180_DAYS TransitionToPrimaryStorageClass=AFTER_1_ACCESS

# DR copy; the destination stays read-only until the replication configuration is deleted
aws efs create-replication-configuration --source-file-system-id fs-0abc123 --destinations Region=us-west-2

Glacier Restore at Scale & Archive Tier Decision Guide

Choosing an archive class is a question about how often and how urgently you will read the data back, and the failure mode is discovering the restore plan during an incident. Decide with the table, then design the restore path before you archive.

Access patternBest fitWhy
Unknown or shiftingS3 Intelligent-TieringNo retrieval fees; moves to Infrequent after 30 days and Archive Instant Access after 90 automatically; objects under 128 KB are not tiered. Optional Archive Access (≥90 days) and Deep Archive Access (≥180 days) tiers are asynchronous
Rare reads, need millisecondsGlacier Instant RetrievalArchive price, no restore step, 90-day minimum, 128 KB minimum billable size
1–2 reads per year, can wait hoursGlacier Flexible RetrievalBulk retrieval is free; Expedited for urgent needs; 90-day minimum
Less than once per year, compliance, tape replacementGlacier Deep ArchiveLowest storage cost; Standard in 12 h, Bulk in 48 h; 180-day minimum
  • Restore tiers. Expedited (Flexible only) is typically 1–5 minutes; to guarantee capacity buy provisioned capacity units (one PCU supports at least three expedited retrievals per five minutes and a fixed retrieval throughput per PCU; check the S3 User Guide for the current MB/s figure). Standard is typically 3–5 h (Flexible) or within 12 h (Deep Archive); Bulk is 5–12 h or within 48 h. Standard is the default tier if you do not specify one.
  • Scale pattern. S3 Inventory or a Batch Operations manifest generator filtered by storage class, then an S3InitiateRestoreObject Batch job (ExpirationInDays, GlacierJobTier of BULK or STANDARD). Batch Operations raises restore rate, so Standard restores typically start in about 30 minutes (Flexible) or about 9 hours (Deep Archive) instead of 3–5 h and 12 h.
  • Completion signal. Subscribe to s3:ObjectRestore:Completed (SQS/SNS/Lambda) or the EventBridge event Object Restore Completed and trigger post-processing; do not poll head-object for millions of keys.
  • Temporary copy. The restored copy lives for the days you set and then expires; copy it into Standard if you need it permanently. For Intelligent-Tiering archive tiers you omit the days (the object moves back to Frequent Access), and one Batch job cannot mix Glacier-class and Intelligent-Tiering-archive objects.
  • Cost levers. Retrieval is per GB plus per request; you also pay for the temporary Standard copy; early deletion bills the rest of the minimum; every transition is a request fee. Restore only the objects you need, in prefix-aligned batches, with the shortest viable Days.
aws s3control create-job --account-id 111122223333 --region us-east-1 --priority 1 \
  --role-arn arn:aws:iam::111122223333:role/restore-role --description "DR restore" \
  --operation '{"S3InitiateRestoreObject":{"ExpirationInDays":10,"GlacierJobTier":"BULK"}}' \
  --manifest-generator '{"S3JobManifestGenerator":{"ExpectedBucketOwner":"111122223333",
    "SourceBucket":"arn:aws:s3:::archive-bucket",
    "ManifestOutputLocation":{"ExpectedManifestBucketOwner":"111122223333","Bucket":"arn:aws:s3:::manifest-bucket",
      "ManifestPrefix":"manifests/restore-job","ManifestFormat":"S3InventoryReport_CSV_20211130"},
    "Filter":{"MatchAnyStorageClass":["DEEP_ARCHIVE"]},"EnableManifestOutput":true}}' \
  --report '{"Bucket":"arn:aws:s3:::report-bucket","Prefix":"reports/restore-job","Format":"Report_CSV_20180820","Enabled":true,"ReportScope":"AllTasks"}'

# route restore-completed events to EventBridge
aws s3api put-bucket-notification-configuration --bucket archive-bucket \
  --notification-configuration '{"EventBridgeConfiguration":{}}'

Valkey vs Redis OSS on ElastiCache: Engine Choice and Migration

The engine decision on ElastiCache is no longer "Redis or Memcached". It is a lifecycle, cost and feature decision: Valkey (Linux Foundation, BSD-3-Clause, forked from Redis 7.2.4) is where new ElastiCache capabilities ship; Redis OSS on ElastiCache stops at 7.1; Memcached stays the simple multi-threaded string cache with no replication. Engine mechanics are in the Redis / Valkey card.

DimensionValkeyRedis OSSMemcached
Newest on ElastiCache9.1 (also 7.2.6, 8.0, 8.1, 8.2, 9.0)7.11.6.x
Price vs Redis OSSNode-based 20% lower; Serverless 33% lowerBaselineSeparate price list
Serverless minimum metered storage100 MB1 GB1 GB
Support lifecycleCurrentv4 and v5 left standard support 2026-01-31 (Extended Support, rising annual premium); v6 standard support ends 2027-01-31Per version schedule
Replication, persistenceMulti-AZ, snapshots; optional durability on 9.0+Multi-AZ, snapshotsNone

What each Valkey line added on ElastiCache, so you can name the version a feature needs:

  • 7.2.6 (Oct 2024) — drop-in for Redis OSS 7.2; 8.0 — about 20% more data per node, per-slot metrics, much faster Serverless scale-up.
  • 8.1 — new hash table (lower memory), native Bloom filter type, COMMANDLOG. 8.2 — native vector search on node-based clusters, no extra cost.
  • 9.0 — Multi-AZ durability option, full-text and hybrid (text plus vector) search, per-field hash TTL, numbered databases in cluster mode, Serverless public endpoints (IAM auth and TLS 1.3 required). 9.1 — further memory cuts, HGETDEL, MSETEX, CLUSTERSCAN, per-database ACLs.

The migration path is an in-place engine change that keeps the endpoint:

  1. Inventory engine and version, cluster mode, client libraries, and whether anything depends on post-7.2 Redis-only features. RESP clients need no code change.
  2. Create a parameter group in the target Valkey family with the same settings. Families are not interchangeable: Valkey 8.x and 9.x groups are incompatible with Redis OSS, and Valkey 9 groups are incompatible with 8.x. Do the same per Region for a Global Datastore.
  3. Take a snapshot, then modify the replication group to the Valkey engine. Upgrades from any ElastiCache Redis OSS version are supported; sources older than 5.0.6 need a DNS-based failover of about 30 to 60 seconds.
  4. Verify CacheHits, CacheMisses and EngineCPUUtilization; Redis OSS Reserved Nodes keep applying and cover more Valkey capacity because Valkey units are cheaper.
aws elasticache modify-replication-group --replication-group-id app-cache \
  --engine valkey --engine-version 8.2 \
  --cache-parameter-group-name app-cache-valkey8 \
  --apply-immediately

Caching Strategies, Invalidation and Operating a Cache

Cache-aside, stampede control, leaderboards and locks are covered at ElastiCache: Redis vs Memcached. This topic adds the other write strategies, the invalidation race, memory sizing, and the metrics and playbooks you need once the cache is in production.

StrategyWrite pathFailure modeUse when
Cache-asideApp writes DB, then deletes the keyStale until TTL after the race belowDefault for read-heavy data
Read-throughCache layer loads on missSame as cache-aside; couples cache to the loaderShared library or DAX-style front cache
Write-throughApp writes DB and cache togetherUnread keys waste memory; partial failure leaves them divergedRead-after-write must be fresh
Write-behindWrite cache, flush to DB laterAcknowledged writes lost if the cache node dies firstCounters, analytics, only with durable queueing or Valkey 9 sync durability
Refresh-aheadBackground reload before expiryNeeds hot-key telemetry; wasted loadsFew very hot keys, expensive loads

Invalidation race. Reader A misses and reads the old row; writer B commits the new row and deletes the key; A then writes its old value into the cache and it stays stale until the TTL fires. Updating the database first and deleting the key second keeps the window small (deleting first widens it, because any reader can repopulate the old value before the commit). Always keep a TTL as the backstop, use versioned keys (user:42:v7) when staleness is not acceptable, or drive deletes from change events (DynamoDB Streams or database CDC) instead of from every writer.

import json, random

def get_user(uid):
    key = f"user:{uid}:v1"
    if (hit := rc.get(key)) is not None:
        return json.loads(hit)
    row = db.fetch_user(uid)
    if row is not None:
        rc.set(key, json.dumps(row), ex=300 + random.randint(0, 60))  # jitter avoids synchronized expiry
    return row

def update_user(uid, fields):
    db.update_user(uid, fields)        # 1) commit to the source of truth first
    rc.delete(f"user:{uid}:v1")        # 2) then invalidate; the TTL bounds the rare stale repopulate
  • Eviction — ElastiCache defaults to volatile-lru, which only evicts keys that have a TTL. A cache of mostly TTL-less keys fills up and returns OOM command not allowed. Pure caches usually want allkeys-lru (or allkeys-lfu for skewed access); keep noeviction for stores that must never drop data.
  • Sizing — estimate keys x (key + value + per-key overhead) and measure a real sample with MEMORY USAGE rather than trusting rules of thumb. Add headroom for fragmentation, replication buffers and snapshot fork copy-on-write. Usable memory is only about 75% of the node (25% reserved-memory-percent by default; fixed on Serverless). Example: 10M sessions at about 640 bytes is roughly 6.4 GB raw, about 10 GB with a 1.5x safety factor, so you need a node with at least 13 GiB usable (cache.r7g.xlarge, 26.32 GiB, not .large at 13.07 GiB).
  • Metrics to alarm on — EngineCPUUtilization (nodes with 4+ vCPUs; CPUUtilization for smaller nodes), DatabaseMemoryUsagePercentage (alert well before 100%), Evictions, CacheHits and CacheMisses, CurrConnections (hard limit 65,000 per node), ReplicationLag, and the Network*AllowanceExceeded counters.
  • Connections — use a finite client pool (a few hundred at most). Opening a connection per request adds a TCP (and TLS) handshake to every operation and spends the engine's single command thread on connection setup; a pooled persistent connection avoids both.
aws cloudwatch put-metric-alarm --alarm-name app-cache-memory-high \
  --namespace AWS/ElastiCache --metric-name DatabaseMemoryUsagePercentage \
  --dimensions Name=CacheClusterId,Value=app-cache-0001-001 \
  --statistic Average --period 60 --evaluation-periods 5 --threshold 80 \
  --comparison-operator GreaterThanThreshold --alarm-actions arn:aws:sns:us-east-1:123456789012:ops

Playbook: engine CPU pinned. Check EngineCPUUtilization, not host CPU. Then (1) find the offender with the slow log or command log (KEYS, big SMEMBERS, long scripts), (2) move reads to replicas if reads dominate, (3) add shards if writes dominate, (4) pipeline and use hashes instead of many tiny keys, (5) scale up only after the above. Playbook: connection timeouts. Security groups and subnets first, then using the right endpoint (primary, reader or configuration), then TLS mismatch (a non-TLS client cannot connect to a TLS-enabled cluster), then CurrConnections.

Purpose-Built Databases: DocumentDB, Neptune, Keyspaces, Timestream, MemoryDB

The page covers DynamoDB, Aurora/RDS, ElastiCache and Redshift. Interviewers still probe the rest of the catalogue, usually as "when is a specialised store worth it, and which ones are even available any more". Default to Aurora or DynamoDB and reach for these only when the data model or the migration source demands it.

ServiceModelPick whenFacts to know
DocumentDBJSON documents, MongoDB APIMigrating MongoDB apps; rich queries and aggregations on nested dataCompatible with MongoDB 3.6, 4.0, 5.0 and 8.0 drivers; it emulates the API on AWS storage, so check unsupported operators. CLI/SDK default engine is 5.0.0, set 8.0.0 explicitly. Elastic clusters shard by hash (up to 32 shards, each with a writer and 0–15 replicas). Vector search on 5.0 and 8.0.
NeptuneProperty graph (Gremlin, openCypher) and RDF (SPARQL)Multi-hop relationship queries: fraud rings, recommendations, knowledge graphsOne writer plus up to 15 replicas on a shared volume up to 128 TiB; failover typically under 30 s with no data loss; Global Database to up to 5 other Regions; Serverless option. SPARQL only reads RDF; Gremlin and openCypher only read property graphs.
Neptune AnalyticsIn-memory graph analytics plus vector searchGraphRAG: vector similarity combined with traversals and graph algorithms in one queryHNSW vector index, up to 65,000 dimensions, callable from openCypher.
KeyspacesWide-column, Cassandra (CQL)Moving Cassandra without running nodesServerless; no compaction, tombstone or GC tuning; writes replicated three times across AZs; multi-Region replication available.
TimestreamTime seriesMetrics and IoT historyTimestream for LiveAnalytics is closed to new customers since 2025-06-20 (existing accounts keep running). New work should evaluate Timestream for InfluxDB, Managed Prometheus, or DynamoDB with TTL plus an export path.
MemoryDBDurable Valkey/Redis-compatible storeRedis APIs as the primary database; microsecond key reads, single-digit-millisecond vector searchMulti-AZ transaction log; HNSW vector search; compare against ElastiCache Valkey 9 durability (see ElastiCache).
QLDBLedger (retired)Do not chooseEnd of support 2025-07-31. AWS migration guidance points to Aurora PostgreSQL, but Aurora does not keep an immutable history by default, so audit designs need extra logging or an append-only table.
What is the access pattern?
 |-- joins, ACID, ad-hoc SQL ................ Aurora / RDS   (beyond one writer: see "Scaling SQL")
 |-- key lookups, extreme scale, serverless . DynamoDB
 |-- JSON documents, MongoDB drivers ........ DocumentDB
 |-- traverse relationships N hops deep ..... Neptune (GraphRAG: Neptune Analytics)
 |-- Cassandra CQL workload ................. Keyspaces
 |-- time series ............................ Timestream for InfluxDB / Managed Prometheus
 |-- microsecond reads, loss-tolerant ....... ElastiCache Valkey
 |-- microsecond reads, must not lose ....... MemoryDB / ElastiCache Valkey 9 (sync durability)
 '-- BI over petabytes ...................... Redshift
aws docdb create-db-cluster --db-cluster-identifier docs --engine docdb --engine-version 8.0.0 \
  --master-username dbadmin --master-user-password "$DOCDB_PASSWORD" --storage-encrypted \
  --db-subnet-group-name docs-subnets --vpc-security-group-ids sg-0abc
aws docdb create-db-instance --db-instance-identifier docs-1 --db-cluster-identifier docs \
  --engine docdb --db-instance-class db.r8g.large

Scaling SQL Beyond One Writer: Limitless, DSQL, Global Database

An Aurora or RDS cluster has exactly one writer. When that writer is the bottleneck, or you need writes in more than one Region, the answer depends on what must scale and what you are willing to give up. The page covers replicas and Global Database at RDS vs Aurora and HA vs DR; this topic adds the two newer engines and the decision between them.

OptionWhat scalesWritersTrade-offs
Bigger writer plus up to 15 Aurora readersReads, then vertical writes1Simplest; hits the single-writer ceiling
Aurora Global DatabaseCross-Region reads and DR1 (primary Region)Cross-Region lag typically under a second; switchover or failover to move the writer
Aurora PostgreSQL LimitlessWrite throughput and storage by shardingMany shards behind routersPostgreSQL only; sharded, reference and standard tables; shard keys cannot be updated; serializable isolation unsupported; shard-group capacity 16–6,144 ACUs
Aurora DSQLServerless, active-active, multi-Region writesAny Region in the cluster setOptimistic concurrency, snapshot isolation (Repeatable Read), per-transaction caps, partial PostgreSQL surface
DynamoDB (MRSC global tables)Key-value scale and multi-Region strong consistencyAny replicaNo joins or ad-hoc SQL; no transactions on MRSC tables

Limitless keeps one logical PostgreSQL database in one Region: a router layer accepts connections and pushes statements down to shards, so queries that carry the shard key and join colocated tables are the fast path. Pick shard keys with high cardinality that your hot queries filter on; small, rarely changing lookup tables should be reference tables replicated to every shard. DSQL is a different architecture: no instances, no lock manager. It provides 99.99% availability in one Region and 99.999% across Regions; a multi-Region cluster is two or more peered clusters that each hold a full copy plus a witness Region that holds the log for quorum, and every peer takes strongly consistent reads and writes.

  • Retry is part of the contract. Conflicts are detected at commit and surface as SQLSTATE 40001 (OC000 data conflict, OC001 schema conflict). Re-run the whole transaction with backoff and jitter; the work must be idempotent.
  • Size transactions to the limits — up to 3,000 rows and 10 MiB changed and 5 minutes per transaction; connections last at most 60 minutes, new connections are rate-limited (100 per second steady, burst 1,000, 10,000 established by default), so pool and recycle. Auth is a short-lived IAM token, not a password.
  • Model for it — UUID primary keys avoid coordination hot spots, indexes are created asynchronously, and DDL and DML run in separate transactions.
  • Cost model — DSQL bills DPUs (one unit covering compute, reads, writes, multi-Region writes and CDC) plus storage and scales to zero when idle; failed or aborted transactions still consume DPUs.
import random, time
import psycopg  # psycopg 3

def run_tx(conn, work, max_retries=5):
    """Re-run the WHOLE transaction on a DSQL OCC conflict (SQLSTATE 40001). `work` must be idempotent."""
    for attempt in range(max_retries + 1):
        try:
            with conn.transaction():
                return work(conn)
        except psycopg.errors.SerializationFailure:
            if attempt == max_retries:
                raise
            time.sleep((2 ** attempt) * 0.05 + random.random() * 0.05)  # exponential backoff with jitter
# Single-Region DSQL cluster, then an admin IAM token to use as the psql password
aws dsql create-cluster --deletion-protection-enabled
export PGPASSWORD=$(aws dsql generate-db-connect-admin-auth-token --region us-east-1 --expires-in 3600 --hostname "$CLUSTER_ENDPOINT")
PGSSLMODE=require psql --username admin --dbname postgres --host "$CLUSTER_ENDPOINT"

Choosing a Load Balancer: ALB vs NLB vs GWLB

The page names ALB and NLB in one line each (Networking (VPC), AMIs, Auto Scaling & Load Balancing); this is the full decision guide. The deciding questions are the OSI layer you need to see, whether you need static addresses or PrivateLink, and whether the thing behind it is an app or a network appliance. Classic Load Balancer is the previous generation: do not choose it for new designs.

ALBNLBGWLB
Layer / protocolsL7: HTTP, HTTPS, gRPC, WebSocketL4: TCP, UDP, TLS (QUIC passthrough supported)L3: all IP packets, GENEVE to appliances
RoutingHost, path, header, method, query rules; weighted target groups; redirects and fixed responsesPort and protocol; flow hashFlow hash, 5-tuple stickiness by default (3- or 2-tuple optional)
Target typesInstance, IP, LambdaInstance, IP, ALBInstance, IP
AddressesDNS name only; IPs changeOne static IP per AZ; Elastic IPs for internet-facing, chosen private IPs for internalReached through GWLB endpoints (PrivateLink), not by clients
Client IPIn X-Forwarded-ForClient IP preservation is a target-group setting (always on for UDP and QUIC groups)Original packet preserved end to end
Auth / TLSTerminates TLS; Cognito, OIDC and JWT-validation actions; mTLS (verify or passthrough); WAFTLS listener or passthrough to targets that terminateNone; the appliance inspects
Cross-zone defaultAlways on at LB level (can turn off per target group); no inter-AZ chargeOff; enabling it incurs inter-AZ data transfer chargesOff; set at LB level
Idle timeout60 s defaultTCP 350 s (60–6000 configurable), UDP 120 sFlow-based; tune keep-alives on appliances
Pick it forWeb apps, microservices, Lambda front ends, blue/green by weightNon-HTTP protocols, static IP allow-listing, PrivateLink services, extreme connection countsInline firewalls, IDS/IPS, DPI fleets
  • Static IPs and L7 routing need both: internet-facing NLB with Elastic IPs in front, ALB registered as the NLB target. You pay for two load balancers, and the backend sees only the NLB's private IP in X-Forwarded-For unless the client sent its own header (VPC Flow Logs can recover client IPs).
  • PrivateLink endpoint services are fronted by an NLB (or a GWLB for appliance services). An ALB registered behind an NLB is a common way to expose an HTTP service over PrivateLink.
  • NLB security groups can only be attached at creation time (they can be changed afterwards, but you cannot add the first one later). Health checks follow outbound rules, not inbound rules. With client IP preservation on, target security groups must allow the real client IPs, or reference the NLB's security group.
  • GWLB model: the appliance fleet sits in an inspection VPC; consumers route to a GWLB endpoint with route-table entries, so traffic is bump-in-the-wire with no NAT. Appliances must speak GENEVE on UDP 6081. For symmetric flows through Transit Gateway turn on appliance mode on the inspection VPC attachment (it requires 5-tuple stickiness on the GWLB target group).
  • ALB subnets need a /27 or larger with at least 8 free IPs to scale; for known surges, reserve capacity (LCU reservation) instead of relying on scale-up.
# ALB canary: 90/10 by weight, sticky for 10 minutes
resource "aws_lb_listener_rule" "api" {
  listener_arn = aws_lb_listener.https.arn
  priority     = 100

  action {
    type = "forward"
    forward {
      target_group { arn = aws_lb_target_group.api_v1.arn
                     weight = 90 }
      target_group { arn = aws_lb_target_group.api_v2.arn
                     weight = 10 }
      stickiness {
        enabled  = true
        duration = 600
      }
    }
  }
  condition {
    path_pattern { values = ["/api/*"] }
  }
}

Hybrid Connectivity: Site-to-Site VPN vs Direct Connect

The page lists VPN and Direct Connect in one line each (Cross-VPC / Hybrid). The interview question is "how do I connect a data centre to my VPCs?", and the answer is a choice on four axes: bandwidth and latency predictability, encryption, time to provision, and the failure domain you can afford. The AWS-side termination point (virtual private gateway, Transit Gateway, Direct Connect gateway, Cloud WAN) matters as much as the circuit.

Site-to-Site VPNDirect Connect (DX)DX + encryption
PathIPsec over the internet; two tunnels per connectionPrivate fibre via a DX location; no internet hopSame circuit; MACsec (L2) or IPsec over it
Throughput1.25 Gbps per standard tunnel, 5 Gbps per large-bandwidth tunnel (TGW and Cloud WAN only, not VGW); aggregate with ECMP on TGW with dynamic routingDedicated 1, 10, 100 or 400 Gbps; hosted 50 Mbps to 25 Gbps via a partner; LAGs of up to 4 members (2 for 100 Gbps ports)As DX; MACsec on 10/100/400 Gbps dedicated only, not hosted
LatencyInternet variabilityConsistent, predictableConsistent
ProvisioningMinutesCross-connect plus often a carrier circuit; plan for long lead timeAdd after DX is up
Best forStart-up path, DR backup for DX, low or moderate bandwidthSustained high bandwidth, steady latency, large data transfersCompliance that demands encryption in transit
  • Where it terminates. A virtual private gateway serves one VPC (no ECMP, no large tunnels). A Transit Gateway serves many VPCs and supports ECMP. A Direct Connect gateway fans one private or transit VIF out to VPCs or Transit Gateways across Regions. Use a transit VIF when the target is a Transit Gateway, a private VIF for a VGW, and a public VIF for public AWS endpoints.
  • "DX + VPN" is two designs, not one. (1) Public VIF, then an IPsec VPN to the VGW or TGW public endpoints, riding over DX. (2) Transit VIF and DX gateway, then a private IP VPN to the Transit Gateway, so the tunnel never touches public addresses. If you only need link-layer encryption and have 10/100/400 Gbps dedicated ports, MACsec avoids the IPsec throughput ceiling.
  • VPN as DX backup is the standard cheap resilience layer. Prefer DX routes with BGP (longer AS-path or lower local preference on the VPN) and test the failover; the Resiliency Toolkit has a failover-testing feature.
  • Summarize on-prem prefixes. With the default 100-prefix BGP allocation per private/transit VIF (raisable to 1,000 per address family with inbound prefix controls), advertising hundreds of /24s drops the session; advertise aggregates or a default route.
# 5 Gbps tunnels into a Transit Gateway, dynamic (BGP) routing so ECMP can aggregate
aws ec2 create-customer-gateway --type ipsec.1 --bgp-asn 65010 --ip-address 203.0.113.12
aws ec2 create-vpn-connection --type ipsec.1 --customer-gateway-id cgw-0abc1234 \
  --transit-gateway-id tgw-0abc1234 --options TunnelBandwidth=large,StaticRoutesOnly=false

NAT Gateway Cost & Egress Playbook

The page shows the NAT price arithmetic (Route Tables & NAT Economics, Egress Cost). This is the operational playbook: how to find out what is crossing the NAT, the ladder of fixes in the order they pay off, which NAT mode to pick, and the port-exhaustion failure that looks like a flaky network.

What is billed. Each NAT-gateway hour, plus a data-processing charge on every gigabyte through the gateway regardless of source or destination (so same-Region S3 traffic through NAT is still charged), plus normal EC2 data transfer. Traffic that crosses an AZ to reach a NAT in another AZ also pays inter-AZ transfer.

  1. Measure first. Enable flow logs on the NAT gateway's network interface (or the private subnets) and rank talkers; do not guess. See the query below, and the BytesOutToDestination and ErrorPortAllocation NAT metrics in CloudWatch.
  2. Keep NAT traffic AZ-local. One zonal NAT per AZ with per-AZ route tables, or a regional NAT gateway that follows your workloads. Trusted Advisor flags NAT gateways that break AZ independence.
  3. Gateway endpoints for S3 and DynamoDB in every route table: no hourly or processing charge, and the traffic never meets the NAT.
  4. Interface endpoints for the chatty AWS APIs (ECR, STS, CloudWatch, Secrets Manager, SQS). Each adds an hourly charge per AZ, so enable the ones that actually appear in the top-talker list. For S3 from another Region or from on-prem, use an S3 interface endpoint.
  5. Go IPv6. An egress-only internet gateway has no charge; IPv6-only workloads reach IPv4 destinations through NAT64 on the NAT gateway with DNS64 on the Route 53 VPC Resolver, which keeps NAT in the path for IPv4-only destinations.
  6. Centralize only at scale. A shared egress VPC (TGW to NAT) cuts the NAT-gateway count and enables inspection, but every GB now also pays Transit Gateway data processing and the attachments cost per hour, so model it before moving.
ModeWhere it livesIPsChoose when
Zonal, publicOne public subnet in one AZElastic IPs, 2 default, up to 8You want fixed per-AZ source IPs or per-subnet isolation
Zonal, privateOne private subnetPrivate IPs onlyOverlapping-CIDR or on-prem SNAT via Transit Gateway; no internet
Regional (automatic)Whole VPC; no public subnet needed; auto-expands to AZs with ENIs (up to ~60 min)AWS-managed EIPs, up to 32 per AZDefault for new internet egress; fewer moving parts. Does not support private NAT
Regional (manual)SameYou associate IPs per AZAllow-listed source IPs with a regional footprint
# CloudWatch Logs Insights over flow logs captured on the NAT gateway ENI
filter (dstAddr in ["10.0.0.25"] and isIpv4InSubnet(srcAddr, "10.0.0.0/16"))
| stats sum(bytes) as bytesTransferred by srcAddr, dstAddr
| sort bytesTransferred desc
| limit 20

Troubleshooting "Connection Timed Out": Runbook & Tooling

The page covers the layers (Security Groups vs NACLs) and one happy-path trace (Packet Walk). This is the failure-side counterpart: decode the symptom, walk the path in a fixed order, and use the tool that reads configuration (Reachability Analyzer) before the tool that reads traffic (flow logs).

SymptomUsually meansFirst suspects
Hangs, then timeoutPackets silently dropped (SGs and NACLs drop without a reply)SG rule, NACL rule or missing ephemeral return range, route table, missing IGW/NAT, appliance in the path
Immediate "connection refused"Packet reached the host and something answered with a resetNothing listening, wrong port, listening on 127.0.0.1, OS firewall
Intermittent drops under loadA per-instance or per-gateway allowance is exhaustedConntrack, bandwidth or packet-rate allowance; NAT port exhaustion; DNS packet limit
5xx from a load balancerTarget unhealthy, or idle timeout shorter than backend keep-aliveHealth check path and port, SG from LB to targets, ALB 60 s idle vs backend keep-alive
  1. Reachability Analyzer, both directions. It analyses configuration (SGs, NACLs, routes, gateways, endpoints, TGW) without sending packets and names the blocking component through an explanation code such as ENI_SG_RULES_MISMATCH. Run source-to-destination and destination-to-source.
  2. Flow logs on the destination ENI. Read ACCEPT versus REJECT per direction (table below). A missing record means the packet never arrived: look upstream at routing and gateways.
  3. Route table actually associated with the subnet (an implicit main-table association is the classic surprise), and the return route on the other side (peering, TGW, VPN).
  4. NACL: both directions and the ephemeral range, rule order (lowest number wins).
  5. Instance-level counters: ethtool -S eth0 | grep allowance.
  6. OS and app: process listening, bind address, host firewall.
Flow-log pattern at the destination ENIMeaning
Single REJECT, inboundSecurity group (or inbound NACL) did not allow the packet
ACCEPT inbound, REJECT on the replyStateless NACL blocking the response (ephemeral ports) — the SG is stateful and already allowed it
ACCEPT both ways but client still times outProblem is past the ENI (OS, app) or on the return route
No record at allPacket did not reach the ENI: route, IGW/NAT, peering/TGW, upstream filter
aws ec2 create-network-insights-path --source i-0aaa1111 --destination i-0bbb2222 --protocol tcp --destination-port 5432
aws ec2 start-network-insights-analysis --network-insights-path-id nip-0123456789abcdef0
aws ec2 describe-network-insights-analyses --network-insights-analysis-ids nia-0123456789abcdef0 \
  --query 'NetworkInsightsAnalyses[0].[Status,NetworkPathFound,Explanations[0].ExplanationCode]'

Threat Detection & Posture Services: GuardDuty, Inspector, Macie, Security Hub, Detective

Chapter 14 lists these as one block; interviews ask which one answers which question and what each one actually reads. The page only has GuardDuty and Security Hub as table rows in Compliance & Audit. Prevention (IAM, SCP/RCP, WAF, security groups) stops things; this layer detects, prioritizes and investigates, and all of it is regional (enable in every Region, manage through a delegated administrator in Organizations).

ServiceQuestion it answersWhat it readsCatch
GuardDutyIs something malicious happening now?Foundational: CloudTrail management events, VPC Flow Logs, DNS query logs (independent duplicate streams, no logging to enable). Plans: S3 Protection (CloudTrail S3 data events), EKS audit logs, Runtime Monitoring (agent for EKS, ECS/Fargate, EC2), Malware Protection (EBS volumes, S3 uploads, AWS Backup), RDS/Aurora login events, Lambda network activity, AI Protection (Bedrock, SageMaker events)Detects, does not block. 30-day free trial per account and Region, then paid. Runtime Monitoring is not on by default and needs the security agent
InspectorWhich of my workloads carry known CVEs or exposure?EC2 (hybrid: SSM agent, falls back to agentless EBS-snapshot scan), ECR images (enhanced scanning, on-push and continuous), Lambda functions and layers (standard) plus Lambda code scanning, Code Security for repositories and IaCRescans when a new CVE is published. Lambda scanned only if invoked or updated in the last 90 days
MacieWhere is sensitive data in S3?S3 only. Automated discovery (daily bucket inventory plus object sampling) or targeted discovery jobs; managed plus custom data identifiers, allow listsNot for RDS, DynamoDB or EBS. Sampling is not a full scan
Security HubWhat is my prioritized risk and compliance posture?Findings from GuardDuty, Inspector, Macie and partners in OCSF; correlates them into exposure findings. Security Hub CSPM is the earlier control/standards engine (CIS, PCI, AWS Foundational) in ASFFTwo generations coexist; do not confuse "Security Hub" with "Security Hub CSPM" in docs or pricing
DetectiveHow did this happen and what else did it touch?Behavior graph from CloudTrail, VPC Flow Logs (EC2-originated only), EKS audit logs, GuardDuty and Security Hub findingsInvestigation, not detection; needs GuardDuty history to be most useful
Security LakeCan I query all security telemetry in one place?Normalizes AWS, SaaS and on-prem sources to OCSF into S3 in your accountA data lake you query (Athena, SIEM), not an alerting engine
  • Extended Threat Detection. GuardDuty correlates weak signals across CloudTrail, S3 data events, runtime and EKS audit data into one attack sequence finding (for example compromised credentials followed by data exfiltration), mapped to MITRE ATT&CK and raised as Critical. It is on by default.
  • Severity bands. Critical 9.0–10.0, High 7.0–8.9, Medium 4.0–6.9, Low 1.0–3.9. Route High and Critical to paging, Medium to a ticket queue.
  • Scale pattern. Designate a delegated administrator account per service, auto-enable for new organization accounts, aggregate in Security Hub, and ship OCSF to Security Lake for long retention and SIEM export.
aws guardduty create-detector --enable --finding-publishing-frequency FIFTEEN_MINUTES
aws guardduty enable-organization-admin-account --admin-account-id 111122223333

cat > gd-high.json <<'JSON'
{
  "source": ["aws.guardduty"],
  "detail-type": ["GuardDuty Finding"],
  "detail": { "severity": [{ "numeric": [">=", 7] }] }
}
JSON
aws events put-rule --name guardduty-high-critical --event-pattern file://gd-high.json
aws events put-targets --rule guardduty-high-critical \
  --targets Id=1,Arn=arn:aws:sns:us-east-1:111122223333:secops

Layered Network Protection: Network Firewall, DNS Firewall, Shield Advanced & Firewall Manager

Chapter 14 names Network Firewall and Firewall Manager but never says where they sit. The page covers security groups vs NACLs and WAF & Shield; this guide places the missing pieces so you can answer "which control stops which attack".

ControlLayer / scopeStateful?Use it for
Shield Standard / AdvancedL3/L4 (Advanced also L7 with WAF); edge resourcesManagedVolumetric and protocol floods. Advanced adds response team access (Business/Enterprise support), cost protection for scaling during an attack, L7 DDoS mitigation (WAF Anti-DDoS managed rule group; legacy automatic L7 mitigation sunsets 2027-01-29)
WAFL7 HTTP(S); CloudFront, ALB, API GW REST, AppSync, CognitoPer requestSQLi/XSS, bots, rate limits (WAF card)
Network FirewallVPC L3–L7, in-line via route tables; north-south and east-westBoth: stateless and stateful (Suricata engine)Egress domain allowlist (HTTP host, TLS SNI), IPS signatures, geo/IP filtering, central inspection VPC
Route 53 Resolver DNS FirewallOutbound DNS from VPCsPer queryBlock known-bad domains, stop DNS-tunnel exfiltration, allowlist-only resolution
Security groupENIStateful, allow-onlyPrimary per-workload firewall
NACLSubnetStateless, allow and denyCoarse deny of bad CIDRs, compliance boundary
Firewall ManagerOrganization-wide policy enginen/aDeploys and audits WAF, Shield Advanced, security group, Network Firewall and DNS Firewall policies across accounts
  • How Network Firewall inspects. A firewall endpoint (Gateway Load Balancer-backed, shown as a vpce- route target) lives in a dedicated firewall subnet, one per AZ. Traffic is inspected only if route tables send it there, and symmetrically in both directions. It does not NAT and preserves source and destination IPs. Capacity is up to 100 Gbps per AZ, shared by that AZ's endpoints. Do not place workloads in the firewall subnet: traffic from it is not inspected.
  • Domain filtering. A domain-list rule group inspects the HTTP Host header and the TLS SNI, so it filters HTTPS without decrypting. A leading dot (.example.com) matches the domain and all subdomains. By default only traffic from the firewall's own VPC is inspected; widen HOME_NET for other CIDRs. Do not mix Allow domain lists with Reject or Alert lists under default action ordering: the Allow group's implicit drop fires first.
  • Firewall Manager prerequisites. Organizations with all features, a Firewall Manager administrator account, AWS Config enabled in member accounts, and (for Network Firewall and DNS Firewall policies) AWS RAM sharing. Policies are Regional.
  • Shield Advanced scope. An annual subscription protects specific resources (Elastic IPs/EC2, ELB, CloudFront, Global Accelerator, Route 53). It covers standard WAF fees on those resources, but not Bot Control, CAPTCHA, web ACLs above 1,500 WCUs or extended body inspection. The legacy automatic L7 mitigation added a 150-WCU rule group to the web ACL; it is being replaced by the AWS WAF Anti-DDoS managed rule group (50 WCUs), with auto-upgrade from 2026-10-25 and the legacy feature sunsetting 2027-01-29.
Egress inspection in one VPC (route tables are the control)
  workload subnet   : 0.0.0.0/0  --> firewall endpoint (vpce-...)
  firewall subnet   : 0.0.0.0/0  --> internet gateway ; 10.0.0.0/16 --> local
  IGW edge route tbl: workload CIDR --> firewall endpoint   (return path, symmetric)
# stateful allowlist: only these domains may be reached over HTTP/HTTPS
aws network-firewall create-rule-group --rule-group-name egress-allowlist \
  --type STATEFUL --capacity 100 \
  --rule-group '{"RulesSource":{"RulesSourceList":{
    "Targets":[".amazonaws.com",".github.com"],
    "TargetTypes":["HTTP_HOST","TLS_SNI"],
    "GeneratedRulesType":"ALLOWLIST"}}}'

Compliance Frameworks & Audit Evidence: What AWS Gives vs What You Prove

Chapter 14 summarizes SOC 2, HIPAA, PCI DSS and GDPR. The page's Compliance & Audit stops at CloudTrail, Config, GuardDuty and Artifact. The interview-grade answer separates inherited controls (AWS's half, shown through reports and contracts) from customer controls (your configuration, which you must evidence continuously), and names the services that produce that evidence.

FrameworkAWS providesYou must implement and evidence
SOC 1/2/3, ISO 27001, PCI DSS (AWS is a Level 1 service provider), FedRAMPIndependent audit reports and certificates, downloadable from AWS ArtifactYour own scope: access control, encryption, logging, change management. AWS reports cover only AWS's layer
HIPAABusiness Associate Addendum accepted in Artifact (per account or organization-wide); list of HIPAA-eligible servicesUse only eligible services for PHI, encrypt, audit access, train staff. Having a BAA does not make every service in scope for PHI
PCI DSSAttestation of compliance for AWS infrastructureCardholder-data scope, segmentation, key management, tokenization to shrink scope
GDPRData Processing Addendum incorporated in the AWS Service Terms and applied automatically; Standard Contractual Clauses for transfersLawful basis, data residency (choose Regions), erasure and access requests, breach process, transfer assessments
Evidence pipeline (continuous, not a yearly scramble)
  CloudTrail   : who changed what      --+
  Config       : is it configured right  +--> Security Hub CSPM (CIS/PCI/FSBP controls, scores)
  Config rules / conformance packs       |        |
  Inspector/Macie/GuardDuty findings   --+        +--> auditor view, tickets, auto-remediation
  Artifact     : AWS's own reports and agreements (their half)
  Control Tower: preventive (SCP) + detective (Config) + proactive (CloudFormation hook) controls per OU
  • Artifact. Self-service SOC, PCI and ISO reports plus click-through agreements (BAA, NDA). Hosted in the management account so agreements accepted there flow to member accounts; give auditors read access through a separate security-tooling account and restrict management-account users to the Agreements feature.
  • Control Tower controls. Preventive controls are SCPs (so they do nothing in the management account), detective controls are Config rules, proactive controls are CloudFormation Hooks that fail a non-compliant deployment before it creates resources. Apply per OU.
  • Config conformance packs and Security Hub CSPM. Conformance packs deploy a bundle of Config rules mapped to a framework (see AWS Config); Security Hub CSPM scores controls from standards such as CIS and PCI DSS and aggregates findings across accounts.
  • Audit Manager is closed to new customers. It maps frameworks to controls and auto-collects evidence from CloudTrail, Config, Security Hub CSPM and API snapshots, but AWS no longer onboards new accounts; existing customers continue. For new programs, assemble evidence from Config conformance packs, Security Hub CSPM and Artifact, or use a GRC tool that reads them.

Secrets Manager Rotation Mechanics: Four Steps, Three Labels, Two Strategies

The page's Secrets Manager vs Parameter Store shows the Terraform rotation resource; interviews probe what actually happens inside a rotation and why apps survive it. Chapter 14's version of the steps is wrong (it ends with "delete old version"), so here is the verified flow.

  1. createSecret — the rotation Lambda generates a new password (GetRandomPassword) and stores it as a new secret version labelled AWSPENDING. AWSCURRENT is untouched, so readers keep getting the old value.
  2. setSecret — the function changes the credential in the real system (database user, API provider) to the pending value.
  3. testSecret — the function connects with the pending credential to prove it works.
  4. finishSecret — the function moves AWSCURRENT to the new version; Secrets Manager automatically puts AWSPREVIOUS on the old one, keeping a last-known-good copy.
StrategyHow it worksTrade-off
Single userRotates the one user's password in placeSimple, but there is a short window where connections holding the old password fail until they refetch
Alternating usersFirst rotation clones the user (suffix _clone), then each rotation updates the other user; one credential is always valid while the other is testedHigher availability; needs a separate superuser secret to clone the user; not supported by RDS Proxy; disabled if the username plus 6 characters exceeds the DB limit
  • Labels, not versions, define state. A version with no staging label is deprecated and Secrets Manager may delete it. Never remove AWSPENDING with a separate API call inside a custom function; a lingering AWSPENDING that is not on the AWSCURRENT version makes the next rotation fail as "still in progress".
  • Managed rotation. For RDS-managed master credentials the service rotates for you with no Lambda to own; use it for admin credentials and the superuser secret that alternating-users needs.
  • Application contract. Fetch by label (default AWSCURRENT), cache with a short TTL via the Secrets Manager caching client, and on an authentication failure refetch once and retry. Do not bake passwords into environment variables at deploy time: they go stale at the first rotation.
  • Network and permissions. The rotation Lambda must reach both Secrets Manager (VPC endpoint or NAT) and the database (same VPC or routed), and needs permission to use the secret's KMS key.
aws secretsmanager rotate-secret --secret-id prod/db/credentials \
  --rotation-lambda-arn arn:aws:lambda:us-east-1:111122223333:function:rotate-db \
  --rotation-rules AutomaticallyAfterDays=30

aws secretsmanager get-secret-value --secret-id prod/db/credentials --version-stage AWSCURRENT
aws secretsmanager get-secret-value --secret-id prod/db/credentials --version-stage AWSPREVIOUS   # rollback reference
aws secretsmanager describe-secret --secret-id prod/db/credentials --query VersionIdsToStages

Runbook: An EC2 Instance Won't Connect

The classic troubleshooting question tests whether you walk the path in order (platform, network, host, app) instead of guessing. Work from the outside in and change one thing at a time; the controls that decide reachability are covered in Security Groups vs NACLs and Route Tables & NAT Economics. This topic is the diagnostic sequence that ties them together.

  1. Status checks. The system check covers the AWS host (power, network, host hardware); the instance check covers the guest OS; Nitro instances also report an attached-EBS check. A failed system check on an EBS-backed instance is fixed by stop then start, which normally moves it to new hardware; a reboot keeps the same host.
  2. Security group. Stateful, allow-only. Check the inbound rule for protocol, port and source (including a referenced SG), then any load balancer SG in front. Return traffic is automatic.
  3. Network ACL. Stateless, ordered, allow and deny. You must allow the request and the response, including the client's ephemeral ports; opening 1024–65535 covers NAT gateways, ELB and Lambda clients, while Linux clients typically use 32768–61000.
  4. Route table. Right table associated with the subnet? Public: 0.0.0.0/0 to the IGW. Private: 0.0.0.0/0 to a NAT gateway in a healthy AZ.
  5. Addressing. A public subnet instance still needs a public IPv4 (auto-assign or Elastic IP) for internet ingress. Any public IPv4 is billed, including those on running instances.
  6. Guest OS. Is the daemon listening on the right port and interface? Local firewall rules, full disk, a broken sshd_config or fstab (read the console output).
  7. Evidence. VPC Flow Logs show ACCEPT or REJECT per ENI; a REJECT means an SG or NACL blocked it. One-way flows point to a stateless NACL or asymmetric routing.
SymptomMost likely layerFast check
Connection times outSG, NACL, route or no public IPFlow Logs REJECT; Reachability Analyzer
Connection refusedNetwork is fine; nothing listeningOS service and port; SG is not the cause
Permission denied (publickey)Key pair, user name or authorized_keysCorrect default user for the AMI; EC2 Instance Connect
Instance status check failsGuest OS (kernel panic, fstab, disk)Console output or screenshot; rescue via another instance
System status check failsAWS hostStop then start to migrate hosts
Works one way onlyNACL missing return ephemeral portsCompare inbound and outbound flow records

Prefer access paths that remove inbound SSH entirely: SSM Session Manager (needs the SSM agent, an instance role, and SSM interface endpoints for private subnets, no inbound ports) or an EC2 Instance Connect Endpoint (SSH/RDP to instances with no public IP and no bastion; the instance SG must allow the endpoint; no extra charge beyond cross-AZ data transfer). Reachability Analyzer is a static configuration analysis: it reads SGs, NACLs and routes and names the blocking component, but it sends no packets, so it cannot see OS-level problems.

aws ec2 describe-instance-status --instance-ids i-0abc --include-all-instances \
  --query 'InstanceStatuses[].{system:SystemStatus.Status,instance:InstanceStatus.Status}'
aws ec2 get-console-output --instance-id i-0abc --latest --output text | tail -50

# static path analysis from the instance to a database ENI on 5432
PATH_ID=$(aws ec2 create-network-insights-path --source i-0abc --destination eni-0def \
  --protocol tcp --destination-port 5432 --query NetworkInsightsPath.NetworkInsightsPathId --output text)
ANALYSIS=$(aws ec2 start-network-insights-analysis --network-insights-path-id "$PATH_ID" \
  --query NetworkInsightsAnalysis.NetworkInsightsAnalysisId --output text)
aws ec2 describe-network-insights-analyses --network-insights-analysis-ids "$ANALYSIS" \
  --query 'NetworkInsightsAnalyses[].{reachable:NetworkPathFound,why:Explanations[].ExplanationCode}'

# no inbound SSH needed
aws ssm start-session --target i-0abc
aws ec2-instance-connect ssh --instance-id i-0abc --connection-type eice

Cross-Account Roles, the Confused Deputy & ABAC

Role assumption mechanics are in STS, AssumeRole & Instance Profiles and policy types in IAM Principals & Policy Types. Three follow-on patterns come up in every multi-account or SaaS design interview: the two-sided cross-account trust, the confused deputy guards, and attribute-based access control that scales permissions with tags instead of policy edits.

1. Cross-account role: both sides must agree

  1. Target account creates a role whose trust policy names the caller (an account root, a role ARN, or a service principal).
  2. Caller account grants its principal sts:AssumeRole on that role ARN in an identity policy. Trust alone is not enough when the caller is in another account.
  3. The caller assumes the role and receives credentials scoped to the role's permissions only; it gives up its own permissions for that session.

2. Confused deputy: stop a trusted party being used against you

A deputy is a third party or AWS service you trust. If it acts on behalf of many customers, an attacker who knows your role ARN can ask the deputy to use its access against your account. Two guards, depending on who the deputy is:

DeputyGuardWhere it goes
Third-party SaaS in another accountsts:ExternalId (one per customer, generated by the SaaS; 2–1,224 chars)Role trust policy Condition; the SaaS must pass it on every AssumeRole
AWS service (SNS, S3, CloudTrail, Config...)aws:SourceArn and aws:SourceAccount (optionally aws:PrincipalOrgID)Resource policy or service-role trust policy
{
  "Version": "2012-10-17",
  "Statement": [{
    "Sid": "VendorWithExternalId",
    "Effect": "Allow",
    "Principal": { "AWS": "arn:aws:iam::111122223333:root" },
    "Action": "sts:AssumeRole",
    "Condition": { "StringEquals": { "sts:ExternalId": "cust-8f3a91c2" } }
  }]
}
aws sts assume-role --role-arn arn:aws:iam::999988887777:role/VendorReadOnly \
  --role-session-name vendor-sync --external-id cust-8f3a91c2 --duration-seconds 3600

Test the role both with and without the external ID; if it can be assumed without it, the guard is not enforced and you should not hand over the ARN. The external ID is a per-customer identifier that defeats impersonation by another customer of the same vendor; it is not a password.

3. ABAC: permissions that follow tags

RBAC needs a policy change for every new project or resource. ABAC compares a tag on the principal with a tag on the resource, so one policy serves every team and new resources need only the right tag.

{
  "Version": "2012-10-17",
  "Statement": [
    { "Effect": "Allow", "Action": "ec2:Describe*", "Resource": "*" },
    { "Effect": "Allow",
      "Action": ["ec2:StartInstances", "ec2:StopInstances", "ec2:RebootInstances"],
      "Resource": "arn:aws:ec2:*:*:instance/*",
      "Condition": { "StringEquals": { "aws:ResourceTag/team": "${aws:PrincipalTag/team}" } } }
  ]
}
  • Where principal tags come from. Tags on the IAM role or user, or session tags passed at federation or sts assume-role --tags (IAM Identity Center and SAML/OIDC attributes map to them). Passing session tags needs sts:TagSession in the trust policy, which can be constrained with aws:RequestTag and aws:TagKeys.
  • Protect the tags. If a user may call ec2:CreateTags or DeleteTags freely, they can retag a resource into their own team and escalate. Restrict tag APIs with aws:TagKeys and aws:RequestTag, require tags on create, and use tag policies in Organizations.
  • Not universal. Only services marked ABAC-capable honor aws:ResourceTag; some resources and actions do not. Tag key names are case-insensitive in conditions, so team and Team collide.

GPU & Accelerator Landscape (2026) and Getting Capacity

GPU & Accelerator Instance Families covers the P4d/P5/G5/Inf2/Trn1 generation. The families below are what AWS lists as current, plus the part interviews now probe: how do you actually get 64 GPUs next week. Accelerator memory below is what EC2 reports (for example an A10G shows 22 GiB, an L40S 44 GiB), not the marketing 24/48 GB.

FamilyAccelerators per instanceNetwork / EFAReach for it when
P5 / P5e / P5en8x H100 80 GiB (640 GiB) / 8x H200 141 GiB (1,128 GiB); p5.4xlarge = 1x H1003,200 Gbps EFA (48xlarge: 3,200; 4xlarge: 100)Large-model training and big-memory inference; H200 when HBM per GPU is the constraint
P6-B200 / P6-B3008x B200 (1,432 GiB) / 8x B300 (2,144 GiB)3,200 / 6,400 GbpsFrontier training and inference on Blackwell
P6e-GB200Grace-Blackwell, arm64 host; UltraServers of up to 72 GPUs in one NVLink domainEFAv4, up to 28.8 Tbps per UltraServerTrillion-parameter models needing a rack-scale memory domain; no Spot
G6e / G7e / G7 / G6fL40S 44 GiB; RTX PRO Server 6000 96 GiB (up to 8); RTX PRO 4500 32 GiB; fractional L4 (1/8 to 1/2 GPU)EFA on larger sizes (G7e up to 1,600 Gbps)Inference, fine-tuning, graphics; fractional GPUs for small models
Trn2 / Trn2u16x Trainium2, 192 vCPU, 2 TiB host memory; UltraServer links 64 chips across 4 instances3.2 Tbps EFAv3 per instanceTraining and inference of Neuron-supported transformers at lower cost per token; see Neuron SDK
Trn3 UltraServersTrainium3 (3 nm), 144 GB HBM3e per chip; up to 144 chips per UltraServerNeuronSwitch-v1 all-to-all fabric, NeuronLink-v4Largest Neuron training/inference, MoE and long-context models; native PyTorch and JAX
Inf2Up to 12x Inferentia2, 32 GiB each (384 GiB)No EFASingle-node, cost-optimized inference
P4d/P4de, G5, G6, G4dn, Trn1A100 / A10G / L4 / T4 / Trainium1EFA on P4d, Trn1, larger G sizesOlder but widely available; cheap prototyping

Getting capacity is a ladder, from cheapest and least certain to most certain:

  1. Spot for interruptible, checkpointed training (not offered on P6e-GB200 or Trn2u). Use price-capacity-optimized allocation and several instance types.
  2. On-Demand works until the Region runs out of that GPU; there is no guarantee.
  3. On-Demand Capacity Reservations guarantee capacity while held, billed whether used or not; best for steady inference fleets.
  4. EC2 Capacity Blocks for ML: reserve GPU/Trainium capacity for a future window, colocated in an UltraCluster. Start up to 8 weeks ahead, 1–14 days in 1-day steps or 15–182 days in 7-day steps, up to 64 instances per block (256 across blocks), extendable if capacity exists. Price is fixed at purchase; instances begin terminating 30 minutes (60 for UltraServers) before the end.
  5. SageMaker training plans / HyperPod for managed jobs: Capacity Blocks cannot be used with SageMaker-managed ml.* instances.
aws ec2 describe-capacity-block-offerings --instance-type p5.48xlarge --instance-count 2 \
  --capacity-duration-hours 48 \
  --start-date-range 2026-12-01T00:00:00Z --end-date-range 2026-12-08T00:00:00Z
aws ec2 purchase-capacity-block --capacity-block-offering-id cbo-0123456789abcdef0 \
  --instance-platform Linux/UNIX

# when the block starts, launch into it
aws ec2 run-instances --instance-type p5.48xlarge --image-id ami-0abc1234 --count 2 \
  --subnet-id subnet-0abc1234 \
  --instance-market-options MarketType=capacity-block \
  --capacity-reservation-specification 'CapacityReservationTarget={CapacityReservationId=cr-0abc1234}'

Trainium & Inferentia in Practice: The Neuron SDK

Trainium and Inferentia are not drop-in CUDA replacements: models run through the AWS Neuron SDK, which compiles them ahead of time for NeuronCores. The economics (see the accelerator landscape) only pay off if your model compiles cleanly, so the interview skill is knowing the workflow and the failure modes.

  • Compiler. Takes PyTorch, JAX, or XLA HLO and emits a NEFF (Neuron Executable File Format) that the Neuron runtime loads onto the device. Compilation is ahead-of-time, so input shapes are baked in; dynamic shapes need bucketing (compile a few fixed sizes and pad).
  • Runtime and tools. Kernel driver plus libraries, neuron-ls to list devices, and profiling tools.
  • Libraries. Inference: standard vLLM APIs run on Trainium/Inferentia (expert parallelism, disaggregated inference, speculative decoding), NeuronX Distributed Inference, or Hugging Face Optimum Neuron. Training: Optimum Neuron, PyTorch Lightning, TorchTitan, NeuronX Distributed. Native PyTorch integration (TorchNeuron) and JAX are the direction for Trn3; check the current Neuron release notes for what is GA.
  • NKI (Neuron Kernel Interface) and the NKI kernel library are the escape hatch for custom kernels, the Neuron analogue of writing CUDA.
  • Platform support. Neuron DLAMIs and Deep Learning Containers; EKS (device plugin resource aws.amazon.com/neuron); ECS on the EC2 launch type; SageMaker ml.trn1, ml.trn2, ml.inf2; AWS Batch; ParallelCluster.

Migration checklist

  1. Audit operator coverage. Trace or compile the model on a small Inf2/Trn instance; unsupported ops or custom CUDA kernels are the usual blockers.
  2. Fix shapes. Choose batch sizes and sequence-length buckets that match production traffic; each bucket is a separate compiled artifact.
  3. Pick precision. BF16 or FP8 where the hardware supports it; validate accuracy against the GPU baseline before comparing cost.
  4. Cache compiled artifacts (S3 or the image) so cold starts and autoscaled replicas do not recompile.
  5. Compare on tokens per dollar and p99 latency, not on instance price.
import torch, torch_neuronx

model = MyModel().eval()
example = torch.rand(1, 3, 224, 224)

neuron_model = torch_neuronx.trace(model, example)   # ahead-of-time compile to a NEFF
torch.jit.save(neuron_model, "model_neuron.pt")

loaded = torch.jit.load("model_neuron.pt")            # later, on an Inf2/Trn instance
out = loaded(example)                                 # input shape must match the traced shape
# EKS pod spec fragment: request a Neuron device and tolerate the Neuron node taint
resources:
  limits:
    aws.amazon.com/neuron: 1
tolerations:
  - key: "aws.amazon.com/neuron"
    operator: "Exists"
    effect: "NoSchedule"
SituationChoose
Standard transformer, steady high volume, team can own a compile pipelineInf2 for inference, Trn2/Trn3 for training and large serving
Custom CUDA kernels, FlashAttention variants, bleeding-edge research codeNVIDIA P/G families
Highly dynamic shapes or frequent model changesNVIDIA (or Neuron with bucketing and a build pipeline)
Want Neuron economics without running the stackBedrock or SageMaker endpoints on Inf2/Trn2

GPU Memory & Throughput Playbook: OOM and Slow Training

Two failure modes dominate GPU work: out of memory and a job that runs but leaves the GPU idle. The page's memory rule of thumb and GPU-starvation gotcha state the symptoms; this is the ordered toolbox and the diagnosis loop.

Budget the memory first

WorkloadRule7B model70B model
Training, FP16/BF16 + AdamAbout 20 bytes per parameter before activations (AWS SageMaker model-parallel guide: 2 weights, 2 grads, 8 optimizer state, 4 + 4 FP32 copies)~140 GB~1.4 TB
Inference weights, FP162 bytes per parameter14 GB140 GB
Inference weights, FP8/INT81 byte per parameter7 GB70 GB
Inference weights, INT40.5 byte per parameter3.5 GB35 GB

Add the KV cache for inference (grows with batch size times sequence length) and activations for training (grow with batch and sequence length). A 7B model therefore trains across several GPUs, not one, while FP16 inference fits a single 24 GB-class GPU only with headroom for the cache.

Levers, roughly in the order to pull them

  1. Mixed precision. Use torch.autocast with BF16 on Ampere or newer (A100, A10G, L4, H100); T4-class GPUs lack native BF16, so use FP16 with a GradScaler. BF16 keeps the FP32 exponent range, so it needs no loss scaling.
  2. Fused attention. F.scaled_dot_product_attention picks FlashAttention-2 or memory-efficient kernels on CUDA automatically; do not hand-roll attention.
  3. Activation checkpointing. Trades recompute for memory: activations are discarded in the forward pass and recomputed in the backward pass. Pass use_reentrant=False explicitly.
  4. Gradient accumulation. Larger effective batch at the memory cost of a small micro-batch.
  5. Shard. FSDP or ZeRO-3 spreads parameters, gradients and optimizer state across GPUs (see Distributed Training); CPU offload buys capacity at the price of PCIe traffic.
  6. Quantize for inference (INT8/FP8/INT4) and use continuous batching and paged KV cache engines such as vLLM.
import torch
import torch.nn.functional as F
from torch.utils.checkpoint import checkpoint

accum_steps = 4
for step, (x, y) in enumerate(loader):
    with torch.autocast("cuda", dtype=torch.bfloat16):          # no GradScaler needed for BF16
        h = checkpoint(model.encoder, x.cuda(non_blocking=True), use_reentrant=False)
        loss = model.head(h, y.cuda(non_blocking=True)) / accum_steps
    loss.backward()
    if (step + 1) % accum_steps == 0:
        optimizer.step()
        optimizer.zero_grad(set_to_none=True)

# inside the attention block: fused FlashAttention / memory-efficient kernel
# out = F.scaled_dot_product_attention(q, k, v, is_causal=True)
# FP16 on T4-class GPUs: scaler = torch.amp.GradScaler("cuda"); scaler.scale(loss).backward()

Diagnose a slow job before buying a bigger GPU

  1. GPU utilization. nvidia-smi dmon or DCGM metrics; sustained under about 80% means the GPU is waiting.
  2. Utilization drops to 0 between steps means data loading: raise num_workers, set pin_memory=True and prefetch_factor, move data to FSx for Lustre or local NVMe, use sharded formats (WebDataset, Parquet) instead of millions of small S3 objects.
  3. Multi-node scaling is poor: run an NCCL all-reduce benchmark (nccl-tests), confirm EFA is actually used (libfabric/OFI plugin) and nodes share one AZ and placement group.
  4. Batch size too small leaves kernels short and launch-bound; grow it until memory is the limit, then accumulate.
  5. Graph compilation (torch.compile) fuses kernels for steady-state loops; measure it, do not assume a gain.

AWS Batch: Queues, Compute Environments & Array Jobs

AWS Batch is a managed scheduler for containerized batch work: you submit jobs, it queues them, provisions compute (EC2, Spot, Fargate or EKS nodes), runs them and scales back to zero. It sits between a hand-rolled SQS worker fleet and Spark: Parallel Processing for ML Data shows where it fits; this is how it works. Pick it for large independent or loosely dependent jobs (genomics, rendering, simulation, bulk transforms, GPU preprocessing) that run minutes to hours.

ObjectWhat it isKnobs that matter
Compute environment (CE)Pool of compute: managed EC2 (On-Demand or Spot), Fargate / Fargate Spot, EKS, or unmanagedMin/max vCPUs, instance types, allocation strategy, subnets, launch template
Job queueHolds RUNNABLE jobs, mapped to one or more CEs in orderQueue priority, CE order (Spot first, On-Demand fallback), optional scheduling policy
Job definitionTemplate: image, command, vCPU/memory/GPU, role, retries, timeoutresourceRequirements, retryStrategy, timeout
JobBasic, array (2–10,000 children), or multi-node parallel (gang-scheduled)Array size, dependsOn (max 20), container overrides
  • Array jobs. One submit call creates a parent and 2–10,000 children; each child reads AWS_BATCH_JOB_ARRAY_INDEX (starting at 0) to choose its shard. The timeout applies per child. Dependencies: SEQUENTIAL (child n waits for n-1) or N_TO_N (child i of B waits for child i of A), which gives per-shard pipelines.
  • Scheduling. A queue is FIFO by default. Attach a fair-share scheduling policy and set shareIdentifier per submission (with weightFactor, decay and compute reservation) so one team cannot starve the others. Use dependsOn for explicit ordering.
  • Allocation strategy. BEST_FIT_PROGRESSIVE for On-Demand. For Spot, the API reference marks SPOT_PRICE_CAPACITY_OPTIMIZED as recommended (console help text still names SPOT_CAPACITY_OPTIMIZED); give Batch many instance types. Strategies other than BEST_FIT may exceed max vCPUs by up to one instance.
  • Platforms. EC2 for GPUs (Fargate has no GPU), Fargate for zero-ops CPU jobs sized from fixed CPU/memory combinations, EKS to run jobs on an existing cluster (including multi-node parallel jobs for MPI-style gang scheduling). Capacity Blocks for ML can back a CE through a launch template (MarketType: capacity-block).
  • Retries. 1–10 attempts; evaluateOnExit (up to 6 rules) matches exit code, status reason (infrastructure, for example Host EC2* on a Spot reclaim) or reason; unmatched failures are retried unless a final EXIT rule exists. Cancelled jobs and invalid job definitions are never retried.
{
  "jobDefinitionName": "image-process",
  "type": "container",
  "platformCapabilities": ["EC2"],
  "containerProperties": {
    "image": "123456789012.dkr.ecr.us-east-1.amazonaws.com/img-proc:latest",
    "command": ["python", "process.py"],
    "jobRoleArn": "arn:aws:iam::123456789012:role/img-proc-job",
    "resourceRequirements": [
      { "type": "VCPU", "value": "4" },
      { "type": "MEMORY", "value": "8192" },
      { "type": "GPU", "value": "1" }
    ]
  },
  "retryStrategy": {
    "attempts": 5,
    "evaluateOnExit": [
      { "action": "RETRY", "onStatusReason": "Host EC2*" },
      { "action": "EXIT", "onReason": "*" }
    ]
  },
  "timeout": { "attemptDurationSeconds": 3600 }
}
aws batch register-job-definition --cli-input-json file://image-process.json
aws batch submit-job --job-name resize-2026-10-20 --job-queue gpu-spot-queue \
  --job-definition image-process --array-properties size=1000 \
  --container-overrides 'environment=[{name=TOTAL_SHARDS,value=1000}]'
# in the container: shard = int(os.environ["AWS_BATCH_JOB_ARRAY_INDEX"]) of TOTAL_SHARDS
NeedAWS BatchECS/Fargate services or Lambda + SQS
Fan out 10,000 tasks from one callNative array jobYou build the fan-out
Queueing, priorities, fair shareBuilt inExternal queue and your logic
Job dependencies / DAGdependsOn, N_TO_NStep Functions
GPUsEC2 or EKS compute environmentsECS on EC2 only; Fargate and Lambda have no GPU
Long-running service or sub-second latencyWrong toolRight tool

Fan-Out / Fan-In at Scale: Parallel, Map and Distributed Map

Step Functions: Orchestration introduced workflows and Parallel Processing for ML Data shows a Distributed Map snippet. This topic is the decision and failure model: which primitive for which fan-out, how to cap blast radius, and how to do the fan-in without it dwarfing the fan-out.

PrimitiveShapeLimits to rememberPick it when
Parallel stateFixed, different branchesBranches are known at design timeRun image, text and audio steps side by side
Map, Inline modeSame steps per array item, in the parent's history40 concurrent iterations; 256 KiB input; 25,000 history eventsSmall arrays (tens to a few hundred items)
Map, Distributed modeEach item (or batch) is a child workflow execution with its own historyUp to 10,000 parallel children; reads S3 object list, S3 inventory, CSV, JSON file, Athena manifest/Parquet directlyThousands to millions of S3 items, each under minutes, no GPU
SNS to SQS to LambdaAsync event fan-out, no coordinatorYou track completion yourselfIndependent consumers; no "wait for all"
AWS Batch array jobContainer fan-out2–10,000 children; see AWS BatchLong, GPU or heavy tasks
  • Batching. ItemBatcher groups items per child (MaxItemsPerBatch and/or a byte cap up to 256 KiB), so one Lambda call handles, say, 100 objects instead of one. This cuts state transitions and cold-start overhead.
  • Child type. ExecutionType EXPRESS children (up to 5 minutes, cheap, history only in CloudWatch Logs) for short items; STANDARD children (up to a year, console-visible history, redrivable) for long or audit-sensitive work.
  • Failure budget. ToleratedFailurePercentage or ToleratedFailureCount lets the Map Run succeed with some failed items; without it the first failure fails the run. A failed Map Run can be redriven to rerun only the failed children.
  • Downstream limits. MaxConcurrency defaults to 10,000 children; the Lambda default is 1,000 concurrent executions per Region, so cap concurrency to what Lambda, DynamoDB or a third-party API can absorb.
  • Fan-in. Write results with ResultWriter to S3 (the state output stays a small manifest), then run one aggregation step (Athena, Glue or Lambda) over the S3 prefix instead of passing megabytes through state.
{
  "StartAt": "ProcessImages",
  "States": {
    "ProcessImages": {
      "Type": "Map",
      "MaxConcurrency": 500,
      "ToleratedFailurePercentage": 2,
      "ItemReader": {
        "Resource": "arn:aws:states:::s3:listObjectsV2",
        "Parameters": { "Bucket": "src-bucket", "Prefix": "images/" }
      },
      "ItemBatcher": { "MaxItemsPerBatch": 100 },
      "ItemProcessor": {
        "ProcessorConfig": { "Mode": "DISTRIBUTED", "ExecutionType": "EXPRESS" },
        "StartAt": "ProcessBatch",
        "States": {
          "ProcessBatch": {
            "Type": "Task",
            "Resource": "arn:aws:states:::lambda:invoke",
            "Parameters": {
              "FunctionName": "arn:aws:lambda:us-east-1:123456789012:function:ProcessBatch",
              "Payload.$": "$"
            },
            "End": true
          }
        }
      },
      "ResultWriter": {
        "Resource": "arn:aws:states:::s3:putObject",
        "Parameters": { "Bucket": "results-bucket", "Prefix": "run-2026-10-20" }
      },
      "End": true
    }
  }
}

When the fan-out is event-driven rather than a coordinated batch, count completions yourself. A plain counter double-counts when a worker is retried, so collect shard ids in a set and compare its size to the expected total; the update is atomic and idempotent.

resp = table.update_item(
    Key={"job_id": job_id},
    UpdateExpression="ADD done_shards :s",      # DynamoDB string set: re-adding a shard is a no-op
    ExpressionAttributeValues={":s": {shard_id}},
    ReturnValues="UPDATED_NEW",
)
if len(resp["Attributes"]["done_shards"]) == total_shards:
    start_aggregation(job_id)                  # exactly one writer sees the full set; make this idempotent too