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.
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.
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.
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.
# 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"]
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.
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
Tool
Lang
Pros
Cons
Terraform
HCL
Multi-cloud, large ecosystem, mature
HCL limited; state mgmt headaches
Pulumi
Python/TS/Go
Real lang, tests, conditionals
Smaller community
CloudFormation
YAML/JSON
Native AWS, no state to manage
AWS-only, slow rollback
AWS CDK
TS/Python/Java/Go
Synth to CFN; constructs
AWS-only; opinionated abstractions
Crossplane
K8s CRDs
GitOps-native; multi-cloud as K8s
K8s-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
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
Class
Cost / GB-mo
Retrieval
Use
Standard
$0.023
Instant
Hot data
Intelligent-Tiering
$0.023 → $0.0036
Instant
Unknown access pattern
Standard-IA
$0.0125
Instant + retrieval $
Backup, infrequent access
One-Zone-IA
$0.01
Instant
Re-creatable, single AZ
Glacier Instant Retrieval
$0.004
Instant
Archive accessed rarely
Glacier Flexible
$0.0036
Minutes–hours
Backup
Glacier Deep Archive
$0.00099
12 hours
Compliance, 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.
Dimension
Container
Virtual Machine
Kernel
Shared host kernel
Own guest kernel per VM
Isolation boundary
Kernel syscall surface (namespaces + cgroups)
Hypervisor / hardware virtualization (VT-x)
Start time
Tens of milliseconds
Seconds to tens of seconds
Density per host
Hundreds to thousands
Tens
Overhead
Near-zero (process-level)
Full OS RAM + CPU per guest
Isolation strength
Weaker — one kernel is shared
Stronger — separate kernels
Image size
MBs to low hundreds of MBs
GBs (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.
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.
Internal scratch space overlayfs uses to stage atomic writes
merged
The 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 image
Size (approx)
Contains
Use when
scratch
0 MB
Nothing — empty
Fully static binary, no libc
distroless
~2–20 MB
Runtime libs, no shell/pkg-mgr
Prod services; minimal attack surface
alpine
~5–8 MB
musl libc + busybox shell
Need a shell; watch musl vs glibc bugs
debian-slim
~30–80 MB
glibc + apt
Broad 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:
Resolve & pull — resolve the tag to an image digest; pull any missing layers by digest (existing layers are skipped).
Create writable layer — allocate the thin copy-on-write upperdir on top of the image's read-only layers.
Set up namespaces — create fresh pid, net, mnt, uts, ipc (and optionally user) namespaces for the process.
Attach cgroups — place the process in a cgroup and apply CPU/memory/IO/pids limits.
Mount rootfs — overlay-mount the merged filesystem and pivot_root into it; wire up networking (veth into the bridge).
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.
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 type
Managed by
Lifecycle
Use for
Volume
Docker (/var/lib/docker/volumes)
Independent of container
Databases, persistent app data
Bind mount
You (any host path)
Tied to host path
Dev: mount source code live
tmpfs
Kernel (RAM)
Vanishes on stop
Secrets, 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 — 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.
Principal signs the request with credentials (access key or temporary STS token).
AWS authenticates the signature, then gathers all applicable 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.
# 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.
Service
Unit
You manage
Scaling
Best for
EC2
Virtual machine
OS, patching, capacity, autoscaling
Auto Scaling Groups (minutes)
Full control, legacy/stateful, custom kernels, GPU
Container orchestration, AWS-native, simpler than K8s
EKS
Pod
K8s workloads (AWS runs the control plane)
HPA / Cluster Autoscaler / Karpenter
Kubernetes portability, existing K8s tooling
Fargate
Container/task
Just the container (no nodes)
Per-task, serverless
Containers 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.
Service
Type
Durability / scope
Access
Best for
S3
Object store
11 nines, multi-AZ replicated
HTTPS API, flat namespace + key prefixes
Static assets, backups, data lake, logs; event notifications
EBS
Block volume
Single-AZ (replicated within the AZ)
Attached to one EC2 at a time
Boot disks, databases, low-latency block IO
EFS
File (NFS)
Multi-AZ, shared
POSIX mount from many instances
Shared filesystem across a fleet, lift-and-shift
Instance store
Ephemeral block
Local disk, lost on stop/terminate
Directly attached NVMe
Scratch, 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.
Partition-key sharded, auto-scales; on-demand or provisioned
Single-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.
Route53 (global DNS) resolves app.example.com to the CloudFront/ALB endpoint. Job: name → address, health-checked routing.
CloudFront (edge CDN) terminates TLS near the user, serves cached static assets, forwards dynamic requests to the origin. Job: latency + TLS + caching + WAF.
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.
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.
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:
Model
Commitment
Discount vs on-demand
Best for
On-demand
None, pay per second/hour
Baseline (0%)
Spiky, short-lived, unpredictable
Reserved / Savings Plans
1 or 3 years
Up to ~72%
Steady, predictable baseline capacity
Spot
None; can be reclaimed with ~2-min notice
Up 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.
Family
Class
vCPU:Mem ratio
Reach for it when
T (t3, t4g)
Burstable general
~1:2–1:4, CPU credits
Bursty low-baseline: dev boxes, small web apps, microservices idle most of the time.
M (m7g)
General purpose
1:4
Balanced steady load: app servers, mid-size databases, backends with no skew.
C (c7g)
Compute optimized
1:2
CPU-bound: batch, media transcode, game servers, HPC, ad-serving, high-RPS APIs.
Huge in-memory sets: SAP HANA, big in-memory DBs, memory-resident caches at TB scale.
P (p5)
Accelerated (GPU)
NVIDIA H100/A100
ML training, distributed deep learning, CUDA/HPC simulation.
G (g5, g6)
Accelerated (GPU)
NVIDIA L4/A10G
ML inference, graphics/rendering, video encoding — cheaper GPU than P.
I (i4i, i3en)
Storage optimized
NVMe instance store
High 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.
Model
Discount vs On-Demand
Commitment
Best for
On-Demand
0% (baseline)
None, per-second billing
Spiky/unknown load, dev, short-lived work.
Savings Plans (Compute)
up to ~66%
$/hour for 1 or 3 yr
Steady spend, flexible across EC2 + Fargate + Lambda, any region/family.
Reserved Instances (RI)
up to ~72%
1 or 3 yr, family/AZ scoped
Locked, steady-state fleets; less flexible than Savings Plans.
Licensing 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).
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 class
Sources
Retry / error model
Synchronous
API Gateway, ALB, Cognito
Caller waits; no auto-retry; client handles failure.
Asynchronous
S3, SNS, EventBridge, SES
Lambda retries twice, then DLQ / on-failure destination.
Poll-based (stream/queue)
SQS, Kinesis, DynamoDB Streams, MSK
Batch 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.
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.
Aspect
Fargate
EC2 launch type
You manage
Tasks/pods only
Instances + OS + patching + capacity
Billing
Per-task vCPU+memory, per-second
Per-instance (running or idle)
Isolation
Micro-VM per task (kernel-level)
Containers share host kernel
Startup
~30–90 s cold provision
Fast if instance already running
GPU / custom AMI
No
Yes
Spot
Fargate Spot (~70% off)
EC2 Spot (~90% off)
Wins on cost when
Variable / bursty / small
Steady, 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.
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.
Service
Unit of deploy
You manage
Scaling
Best for
Lambda
Function
Code only
Automatic, per-request (0 → thousands)
Event-driven, bursty, short (<15 min) work.
Fargate
Task / Pod
Container + task spec
App Auto Scaling on task count
Serverless long-running containers, no node ops.
ECS (EC2)
Task on your EC2
Containers + EC2 fleet
Service scaling + ASG/capacity provider
Steady containers, GPU, high utilization, AWS-native.
EKS
Pod
k8s workloads (+ nodes if not Fargate)
HPA / Cluster Autoscaler / Karpenter
Kubernetes shops, portability, complex platforms.
EC2
Virtual machine
OS, runtime, everything on it
EC2 Auto Scaling Groups
Full 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-mo
Retrieval latency
Min duration
AZs
Best for
S3 Standard
0.0230
ms
none
≥3
Hot data, active workloads
Intelligent-Tiering
tier price + monitoring
ms
none
≥3
Unknown/shifting access patterns
Standard-IA
0.0125
ms
30 days
≥3
Infrequent but latency-sensitive
One Zone-IA
0.0100
ms
30 days
1
Recreatable, non-critical copies
Glacier Instant Retrieval
0.0040
ms
90 days
≥3
Archive needing instant access
Glacier Flexible Retrieval
0.0036
1 min – 12 hr
90 days
≥3
Archive, minutes-to-hours OK
Glacier Deep Archive
0.00099
12 – 48 hr
180 days
≥3
Compliance, 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.
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).
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:
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.
IAM policy — identity-based; what a given principal may do.
ACLs — legacy per-object/bucket grants. Disabled by default on new buckets ("Bucket owner enforced"); avoid.
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).
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.
Type
Media
Max IOPS
Max throughput
Use case
gp3
SSD
80,000
2,000 MiB/s
Recommended general purpose; IOPS/throughput decoupled from size
Throughput-heavy sequential: logs, big data, streaming
sc1
HDD
250
250 MiB/s
Cold, 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:
Service
Protocol / engine
Reach
Use case
EFS
NFS v4 (Linux)
Multi-AZ, elastic
Shared Linux/container storage, home dirs, CMS
FSx for Windows File Server
SMB / NTFS
Single/Multi-AZ
Windows apps, Active Directory integration
FSx for Lustre
Lustre (HPC)
Scratch/persistent
HPC, ML training, S3-linked high-throughput
FSx for NetApp ONTAP
NFS+SMB+iSCSI
Multi-AZ
Multiprotocol, snapshots, on-prem ONTAP lift
FSx for OpenZFS
NFS (ZFS)
Single/Multi-AZ
ZFS 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.
Property
EBS
Instance Store
Persistence
Survives stop/terminate
Lost on stop/terminate
Snapshots
Yes (to S3)
No
Detach / re-attach
Yes
No (bound to host)
Performance
Good (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:
Tier
Flexible Retrieval
Deep Archive
Cost
Expedited
1–5 min
n/a
Highest
Standard
3–5 hr
~12 hr
Default
Bulk
5–12 hr
~48 hr
Lowest
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.
Dimension
RDS (Multi-AZ)
Aurora
Replication
Instance-level, 1 sync standby
Storage-level, 6-way across 3 AZs
Failover time
~60–120 s (DNS + standby promote)
< 30 s (replica already attached)
Read replicas
Up to 15 (5 for Oracle/SQL Server), each its own copy
Up to 15, shared volume
Storage
Pre-provisioned EBS (gp3), auto-scale on
Auto-scaling to 128 TiB (256 TiB on newer versions), pay per use
Serverless
No
Serverless v2, 0–256 ACU (~2 GB RAM/ACU); min 0 = auto-pause
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 mode
How you pay
Use when
On-demand
~$0.125 / M reads, ~$0.625 / M writes (us-east-1, halved Nov 2024); scales instantly
Spiky / unknown traffic, new apps, scale-to-zero
Provisioned
RCU $0.00013/hr, WCU $0.00065/hr; + Auto Scaling
Steady, 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.
Single-threaded command execution; Enhanced I/O threads offload network work
Multi-threaded
Pub/Sub, Lua, TX
Yes
No
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.
Workload
Service
Why
JOINs, ACID, ad-hoc queries
RDS / Aurora
Relational model, full transactions
Same, variable/bursty load
Aurora Serverless v2
Scales ACUs in seconds; no idle compute cost only if min capacity = 0 (auto-pause)
Same, need Oracle / SQL Server
RDS
Aurora is MySQL/PostgreSQL only
Key-value / key-range at massive scale
DynamoDB
Flat < 10 ms latency, serverless, no JOINs
Read-heavy hotspot on any DB
ElastiCache (Valkey/Redis)
Sub-ms cache-aside, offload the primary
Sessions / leaderboards / rate limit
ElastiCache (Valkey/Redis)
Hashes, Sorted Sets, TTL, atomic ops
DynamoDB reads at microseconds
DAX
API-compatible in-memory front cache
BI / dashboards / big scans
Redshift
Columnar MPP over petabytes
Redis as durable primary store
MemoryDB
Multi-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.
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.
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.
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.
CIDR
Total IPs
Usable (−5)
Typical use
/16
65,536
65,531
Whole VPC
/20
4,096
4,091
Large tier subnet
/23
512
507
App tier per AZ
/24
256
251
Public / data tier
/28
16
11
Min 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.
Destination
Target
Meaning
10.0.0.0/16
local
Stays inside the VPC
172.16.0.0/16
pcx-…
Peered VPC
192.168.0.0/16
vgw-…
On-prem via VPN gateway
0.0.0.0/0
igw-… / nat-…
Default route (public / private)
Internet Gateway
NAT Gateway
Direction
Bidirectional
Outbound only
Cost
Free
~$0.045/hr + $0.045/GB
Availability
Region-wide, redundant
Zonal: AZ-scoped (1 per AZ for HA); regional mode auto-expands across AZs
Throughput
Unmetered
5 Gbps baseline, auto-scales to 100 Gbps
Subnet
Public
Lives 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.
Feature
Security Group
NACL
Level
Instance / ENI
Subnet
State
Stateful
Stateless
Rules
Allow only
Allow and Deny
Evaluation
All rules (logical OR)
Numbered, first match wins
Default
Deny in, allow out
Default NACL allows all
Can reference
Other SG IDs
CIDR 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.
Peering
Transit Gateway
PrivateLink
Topology
Full mesh (n²)
Hub-and-spoke
Service exposure
Transitive
No
Yes
N/A (single endpoint)
Scope
Whole VPC ↔ VPC
Many VPCs + hybrid
One service only
CIDR overlap
Not allowed
Not allowed
Allowed (no routing)
Cost
Data only
Attach + GB
Hourly + 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.
Record
Maps to
Note
A / AAAA
IPv4 / IPv6
Direct address
CNAME
Another hostname
Not valid at apex
Alias
AWS resource
Apex-safe, free, health-aware
MX / TXT / NS
Mail / metadata / delegation
SPF, DKIM, subdomain NS
Policy
Behavior
Use case
Simple
One record, no health check
Single resource
Weighted
Split by weight (e.g. 80/20)
A/B, canary rollout
Latency
Lowest-latency region wins
Multi-region perf
Failover
Primary→secondary on health fail
Active-passive DR
Geolocation
By user's country/continent
Localization, compliance
Multivalue
Up to 8 healthy answers
Cheap 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 Functions
Lambda@Edge
Runtime
JS (edge)
Node / Python
Latency
Sub-millisecond
Milliseconds
Triggers
Viewer req/resp
Viewer + origin req/resp
Use
Header/URL rewrite, redirects
Auth, 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 API
HTTP API
WebSocket API
Cost/latency
Higher
~70% cheaper, lower latency
Per-message + connection-minutes
Features
Full: validation, transforms, WAF, API keys, cache
Lean: JWT, proxy, CORS
Persistent bidirectional
Authorizers
IAM, Cognito, Lambda
JWT, Lambda, IAM
Lambda ($connect)
Best for
Feature-rich public APIs
Serverless microservices
Chat, 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.
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.
Model
Customer patches OS?
Customer owns
IaaS (EC2)
Yes
Guest OS, runtime, app, data, firewall, IAM
Container (ECS/EKS on EC2)
Node OS yes
Image, task role, app, data
Serverless (Lambda, Fargate)
No
Code, IAM, data, dependencies
Managed (S3, DynamoDB)
No
Access 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 type
Attached to
Role in evaluation
Identity-based
User / group / role
Grants — what the principal can do
Resource-based
Resource (S3 bucket, KMS key, SQS)
Grants — names a Principal; enables cross-account
SCP
Org OU / account
Guardrail — caps max perms, never grants
RCP (resource control policy)
Org OU / account
Guardrail — caps max perms on resources in the org, never grants
Permission boundary
User / role
Guardrail — caps that identity's max perms
Session policy
Passed at AssumeRole
Guardrail — 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).
The role's trust policy (a resource-based policy on the role) says who may assume it via sts:AssumeRole.
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).
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.
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 type
Rotation
Policy control
Cost
AWS owned
AWS-managed, opaque
None
Free
AWS managed (aws/s3)
Automatic, annual
Cannot edit policy
No monthly fee; pay per API call
Customer managed
Optional auto (default 365 days; configurable 90–2,560) + on-demand
Full key policy + grants
~$1/key/month + $0.03/10K requests
Imported (BYOK)
On-demand only (you import new material); no automatic
Full 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 type
Catches
Action options
AWS Managed Rules
Core rule set, SQLi, XSS, known bad inputs, IP reputation, bot control
Allow / 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 match
Allow/block lists, geo-blocking by country
Allow / Block
String / regex match
Headers, URI, body, query args
Allow / 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.
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.
Service
Question it answers
Mechanism
CloudTrail
Who called which API, when, from where?
Immutable API audit log across all regions
Config
Is this resource configured compliantly over time?
Config snapshots + rules, drift + history
GuardDuty
Is something malicious happening right now?
ML threat detection on CloudTrail, VPC Flow, DNS logs
Security Hub
What 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
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.
Property
Standard
FIFO (.fifo suffix)
Throughput
Nearly unlimited
300 msg/s (3,000 with batches of 10); high-throughput mode raises this per message-group
Ordering
Best-effort
Strict order within a MessageGroupId
Delivery
At-least-once (dupes possible)
Exactly-once processing
Dedup
None
5-minute dedup window by MessageDeduplicationId or content hash
Parallelism
Unbounded consumers
One 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.
Producer SendMessage → message durably stored across AZs.
Consumer ReceiveMessage → message hidden for the visibility timeout; ReceiveCount increments.
Work succeeds → DeleteMessage removes it. Work fails/timeout → message becomes visible again.
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:
Category
Protocols
Typical use
App-to-App (A2A)
SQS, Lambda, HTTP/S, Amazon Data Firehose
Fan-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.
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.
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.
Dimension
SNS
EventBridge
Model
Topic fan-out
Bus + rules (content routing)
Filtering
Attributes / body match
Rich pattern match on any field of the event JSON
Targets
SQS, Lambda, HTTP, SMS, email, Firehose
20+ AWS targets (Lambda, SFN, SQS, Kinesis, API destinations...)
Sources
Your publishers
Your apps + AWS services + SaaS partners; scheduled events
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).
Property
Standard workflow
Express workflow
Max duration
Up to 1 year
Up to 5 minutes
Execution semantics
Exactly-once
At-least-once (async) / at-most-once (sync)
Rate
Lower start rate; long-running
Very high volume (100k+/s)
Pricing
Per state transition
Per request + duration/memory (cheaper at high volume)
History
Full, in-console
Via CloudWatch Logs only
Fit
Order fulfillment, ETL, human approval
High-rate event processing, IoT ingest, short APIs
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).
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:
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:
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.
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 type
Plane
Examples
Logged by default?
Management events
Control
RunInstances, CreateBucket, CreateUser
Yes (free, one copy)
Data events
Data
s3:GetObject, lambda:Invoke
No — 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.
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.
Question
Service
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.
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.
Model
Commitment
Flexibility
Max discount
Best for
On-Demand
None
Maximum
0%
Spiky / unpredictable, short-term
Compute Savings Plan
$/hr, 1 or 3 yr
High — any family, region, OS, tenancy
~66%
Mixed, evolving fleets (EC2 + Fargate; Lambda covered but only up to ~17%)
EC2 Instance Savings Plan
$/hr, family + region
Medium — size flexible within family
72%
Stable EC2 fleets
Reserved Instance
Instance type + AZ, 1 or 3 yr
Low (Convertible RI can swap)
72%
Redshift, and RDS/ElastiCache where Database Savings Plans do not fit
Spot
None — 2-min reclaim notice
Lowest
90%
Batch, CI, stateless, ML training w/ checkpoints
Dedicated Host
Per-host
Varies
BYOL value
Licensing 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.
Collect 2+ weeks of metrics — CPU, memory (needs CloudWatch agent), network, disk I/O.
Feed AWS Compute Optimizer (free) — it flags over/under-provisioned EC2, EBS, Lambda, ECS-on-Fargate and Auto Scaling groups with ranked recommendations.
Change one tier at a time, verify p99 latency holds, then repeat.
Prefer Graviton (m7g/c7g/r7g) and burstable T-family for low-average, spiky CPU.
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 pattern
Retrieval
Standard
$0.023
Frequent
Instant
Intelligent-Tiering
$0.023 + monitor fee
Unknown / mixed
Instant, auto-tiers, no retrieval fee
Standard-IA
$0.0125
Monthly (30-day min)
Instant
Glacier Instant
$0.004
Quarterly
Milliseconds
Glacier Flexible
$0.0036
Yearly
Minutes-hours
Glacier Deep Archive
$0.00099
Compliance / cold
12-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.
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.
Path
Cost
Note
Internet -> AWS (ingress)
Free
Uploads are free
AWS -> Internet (egress)
$0.09/GB (first 10TB)
Tiers down at scale
Same AZ
Free
Co-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/GB
Replication, DR
NAT Gateway processing
$0.045/GB + hourly
On top of egress
S3/DynamoDB Gateway Endpoint
Free
Replaces 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.
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.
Tool
Purpose
Cadence
Cost Explorer
Trends, forecast, group-by dimension/tag
Weekly
AWS Budgets
Threshold alerts (80/100/120%), actual + forecast
Always-on
Cost Anomaly Detection
ML alerts on unusual spend, per service/tag
Daily
CUR + Athena
Line-item chargeback, split shared costs
Monthly
Compute Optimizer / Trusted Advisor
Rightsizing + idle-resource findings
Quarterly
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.
# 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: [email protected] # 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.
Inform — visibility, allocation, showback/chargeback. Every team sees its own bill; shared costs (NAT, Transit Gateway) split proportionally.
Optimize — eliminate waste, rightsize, commit (Savings Plans/RIs), adopt Spot and new instance families (Graviton, Inferentia).
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.
Dimension
High Availability
Disaster Recovery
Failure handled
Instance / AZ / component
Entire region, natural disaster
Fault domain
Availability Zone
Region
Replication
Synchronous
Asynchronous
Failover
Automatic (seconds)
Manual / triggered (minutes)
Cost
~2x the tier
2%–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 mode
Synchronous (zero-lag)
Asynchronous (lag > 0)
Inter-node latency
Sub-millisecond to ~2ms
Tens to hundreds of ms
Achievable RPO
Zero (no data loss)
Seconds to minutes
Data transfer cost
Cheap / often free intra-AZ
Cross-region egress charged
Operational complexity
Low — one control plane
High — DNS, IAM, quotas, drift per region
Protects against
Datacenter loss
Region 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
Workload
RPO target
RTO target
Banking / payments
0 (no loss)
< 15 min
E-commerce
~1 hour
~1 hour
Dev / test
24 hours
24 hours
Cold archive
1 week
1 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.
Strategy
What runs in DR region
RTO
RPO
Cost (% of prod)
Complexity
Backup & Restore
Nothing — only backups in S3
Hours to days
Hours
2–7%
Low
Pilot Light
DB replica + core infra, app off
10s of minutes
Minutes
7–20%
Medium
Warm Standby
Scaled-down full stack, running
Minutes
Seconds to minutes
30–60%
Medium-High
Multi-Site Active/Active
Full stack serving live traffic
Near-zero
Near-zero
80–120%
Very High
Backup & Restore — snapshots and objects replicated to another region; you rebuild everything on disaster. Cheapest, slowest. Good for dev/test and non-critical archives.
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.
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.
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.
Mechanism
Mode
Typical lag / RPO
Failover model
RDS Multi-AZ
Synchronous, same region
0 (HA only)
Automatic, 1–2 min, same endpoint
RDS Multi-AZ Cluster
Semi-sync, 1 writer + 2 readable standbys
0
Automatic, ~35s
RDS cross-region read replica
Async, cross region
Seconds to minutes
Manual promote to standalone
Aurora (in-region)
6 copies across 3 AZs
0
Automatic, < 30s
Aurora Global Database
Storage-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 Tables
Async, active-active multi-region
< 1s
None needed — write anywhere
S3 Cross-Region Replication
Async object replication
Minutes
Repoint 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.
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.
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.
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.
Instance
Accelerator
Accel Mem
Network
On-Demand $/hr
Sweet spot
g4dn.xlarge
1x T4
16 GB
25 Gbps
~$0.53
Cheap inference/proto
g5.xlarge
1x A10G
24 GB
10 Gbps
~$1.01
Real-time inference, fine-tune
inf2.xlarge
1x Inferentia2
32 GB
15 Gbps
~$0.76
Cost-optimized inference
trn1.32xlarge
16x Trainium
512 GB
800 Gbps
~$21.50
Cost-optimized training
p4d.24xlarge
8x A100
320 GB
400 Gbps
~$32.77
Production LLM training
p5.48xlarge
8x H100
640 GB
3,200 Gbps
~$98.32
Frontier 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.
Strategy
What is split
Use when
Comm pattern
Data parallel (DDP)
The batch; each GPU holds a full model copy
Model fits in 1 GPU
AllReduce gradients (NCCL)
Tensor parallel
A single layer's matmul across GPUs
Layer too big; needs NVLink
Per-layer, very chatty
Pipeline parallel
Contiguous layer blocks per GPU
Model > 1 GPU; has bubble idle
Activations between stages
FSDP / ZeRO-3
Params + grads + optimizer sharded 1/N
Large models, avoid DP memory waste
All-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])
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.
Option
Latency
Cost model
Scale-to-zero
Best for
SageMaker Real-Time
50-200 ms
per instance-hr
No (min 1)
Steady online traffic
SageMaker Serverless
+ cold start
per invoke
Yes
Bursty / low volume
SageMaker Batch Transform
minutes
lowest (job)
Yes
Offline scoring
Bedrock
200 ms+
per token
Yes (managed)
Foundation models, no ops
Inf2 (self/SM)
10-50 ms
per instance-hr
Auto
High-throughput $/req at scale
ECS/EKS + GPU
10-100 ms
per instance-hr
Manual
Full 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.
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.
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.
Service
Model
GPU
Best for
AWS Batch (array jobs)
per instance-sec, one API launches 10k tasks
Yes (auto-selects)
Genomics, rendering, bulk transforms
EMR (Spark)
per instance-hr, transient clusters
Limited
TB/PB ETL, feature engineering
Step Functions Distributed Map
per transition, up to 10k concurrency
No (Lambda)
S3-inventory fan-out, <15 min tasks
Lambda + SQS
per invoke
No
Short, 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.
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.
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.
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.
Pattern
Key services
When to use
Primary tradeoff
3-tier web
ALB + Auto Scaling Group (EC2/Fargate) + RDS/Aurora
Familiar CRUD app, SQL data, steady traffic, team knows servers
You own capacity & patching; scales vertically at the DB tier
Serverless
API Gateway + Lambda + DynamoDB
Spiky/unknown traffic, MVP, small team, scale-to-zero economics
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.
Route 53 resolves to CloudFront, which caches static assets and terminates TLS at the edge.
An ALB (Layer 7) does path-based routing to an Auto Scaling Group of Fargate tasks or EC2 instances across multiple AZs.
Compute stays stateless; session and cache state live in ElastiCache Redis.
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.
Dimension
3-tier (ALB + ASG + Aurora)
Serverless (API GW + Lambda + DynamoDB)
Data model
Relational, JOINs, ad-hoc queries
Key-value / known access patterns
Scaling
Minutes (ASG warm-up), DB scales vertically
~100ms, per-request concurrency
Idle cost
You pay for running instances
Scales to zero — pay nothing
Latency floor
~1ms warm behind ALB
~10ms warm, 100ms–several s cold
Ops burden
Capacity 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.
Criterion
Lambda (serverless)
Fargate/EKS (containers)
EC2 (VMs)
Max duration
15 min
Unlimited
Unlimited
GPU / custom kernel
No
Fargate no; EKS on EC2 yes
Yes
Scaling speed
~100ms
~30–60s
~3–5 min
Ops overhead
Minimal
Low (Fargate) / high (EKS)
High
Cost at low volume
Cheapest (scales to zero)
Moderate flat floor
Wasteful when idle
Cost at high steady volume
Expensive
Good
Cheapest (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.
+----------------------+
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.
Ingest — Amazon Data Firehose, Glue, or DMS land data in S3.
Store in medallion tiers — raw (bronze) → processed (silver) → curated (gold) prefixes, with lifecycle rules tiering old data to Glacier.
Catalog — a Glue Crawler discovers schema into the Glue Data Catalog on a schedule.
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.
Requirement
Pattern / service
Because
Simple API, bursty traffic
API Gateway + Lambda
Scales to zero; cheapest under ~5M req/mo
Long-running service, no GPU
Fargate (ECS)
No 15-min cap; no server management
Kubernetes ecosystem / multi-cloud
EKS + Karpenter
Portability & CNCF tooling justify the overhead
Relational data, JOINs, < 64TB
RDS/Aurora PostgreSQL
ACID, ad-hoc SQL, evolving access patterns
Key-value at massive scale
DynamoDB
Single-digit ms at any scale; known patterns
Sub-ms reads, sessions, leaderboards
ElastiCache Redis
In-memory; rich data structures
Fan-out to many consumers
SNS or EventBridge
Pub/sub vs rule-based routing
Ordered real-time stream, replay
Kinesis Data Streams
Per-shard order + multi-consumer replay
Files, images, backups
S3
11 nines durability; cheapest object store
Global static/dynamic delivery
CloudFront + S3
Edge caching cuts latency & origin cost
Multi-region active-active writes
DynamoDB Global Tables
RDS/Aurora have one write region
Foundation models / RAG
Bedrock (+ 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.
"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.
Strategy
What it means
When
Rehost
"Lift & shift" VMs as-is to EC2
Speed matters; refactor later
Replatform
Minor tweaks (self-run DB → RDS)
Quick wins without a rewrite
Repurchase
Move to a SaaS product
Commodity function (email, CRM)
Refactor / Re-architect
Redesign cloud-native
Scaling or agility limits justify cost
Retire
Decommission it
Nobody uses it anymore
Retain
Leave 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.
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).
Approach
Guest modified?
Privileged-op handling
Overhead
Binary translation (old VMware)
No
Rewrite guest instructions at runtime
High
Classic paravirt (old Xen PV)
Yes (hypercalls)
Guest calls hypervisor explicitly
Medium
Hardware-assisted (VT-x/AMD-V)
No
CPU traps sensitive ops to VMM
Low (<5%)
Nitro (HVM + HW offload)
No
CPU 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.
Dimension
Xen era (pre-2018)
Nitro system
Hypervisor
Xen + fat Dom0 Linux
Thin KVM-based Nitro hypervisor
Network/storage data path
Emulated/PV in software on host CPU
Offloaded to Nitro cards (ASIC/FPGA)
Host CPU spent on virt overhead
Up to ~30%
~1% (near bare-metal)
Bare-metal instances
Not possible
*.metal — no hypervisor at all
Root of trust / operator access
Software-mediated
Nitro Security Chip; no operator shell to guests
Management plane
Runs beside guest on host
Runs 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 component
Responsibility
Guest sees
Nitro Card for VPC
VPC networking, overlay encap, security groups, encryption in transit
ENA NIC
Nitro Card for EBS
Remote block storage over NVMe, at-rest encryption
NVMe disk
Nitro Card for Instance Storage
Local NVMe SSD, transparent encryption
NVMe disk
Nitro Card Controller
Coordinates cards, exposes the system to the hypervisor
(hidden)
Nitro Security Chip
Hardware 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.
Property
Container
Firecracker microVM
Traditional VM (QEMU)
Kernel
Shared host kernel
Own guest kernel
Own guest kernel
Boundary
namespaces + cgroups + seccomp
VT-x/EPT + tiny VMM
VT-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 devices
none (n/a)
~4
100+
Density / host
1000s
1000s (thousands per node)
hundreds
Isolation strength
Weakest (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.
Invoke arrives at the Lambda frontend (auth, throttling, routing).
Placement service finds a warm Firecracker microVM or cold-starts a new one on a bare-metal Nitro worker.
Firecracker boots a minimal Linux guest (<125 ms) with your runtime + code + deps mounted.
Handler executes; the control plane talks to it over virtio-vsock (no network stack).
MicroVM is frozen/reused for the next invoke, or reaped after idle.
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.
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.
Build — compile code, resolve dependencies, produce a binary or container image. The image is tagged with the commit SHA, not latest.
Test — unit tests (fast, run first), then integration and contract tests, then security/dependency scans. Fail fast: cheap checks gate expensive ones.
Package & publish — push the image to a registry (ECR, GCR, Harbor) and other artifacts to an artifact store. This is the promotable unit.
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.
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.
Aspect
Push CD (kubectl/Helm from CI)
Pull CD (GitOps: ArgoCD/Flux)
Credentials
CI holds cluster admin keys (blast radius)
Controller lives in-cluster; no external creds
Source of truth
Whatever CI last ran
Git repo, always
Drift
Manual kubectl edit goes unnoticed
Detected and auto-reverted to Git state
Rollback
Re-run pipeline
git revert — one commit
Audit
CI logs
Git 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.
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.
Strategy
How it works
Cost / rollback
Best for
Rolling
Replace pods N at a time, old + new coexist briefly
1x capacity; rollback = roll back pods (slow)
Default, stateless, backward-compatible changes
Blue-green
Full new stack (green) beside old (blue); flip router
2x capacity; rollback = instant flip back
Fast rollback, hard schema cutovers
Canary
Route 1%→5%→25%→100% to new, watch metrics
~1.1x capacity; rollback = shift traffic back
Risky changes, gradual confidence
Feature flags
Ship code dark, toggle per-user/segment at runtime
No redeploy; rollback = flip flag
Decoupling 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.
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
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.
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.
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.
Question
Current 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).
Limit
Value
Adjustable
Tasks per service
5,000 (1,000 if ECS service discovery / Cloud Map is used)
No
Services per cluster
5,000
No
Containers per task definition
10; task definition size 64 KiB
No
Target groups per service
5
No
Tasks per RunTask call
10
No
Fargate vCPU quota
6 vCPU default on new accounts, raised automatically with usage; plus launch-rate quotas
Yes
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+).
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.
You 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 groups
You pick AMI type and size; AWS rolls updates
Stable 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 consolidates
Custom AMIs, daemons needing host access, Spot-heavy fleets, no Auto Mode fee.
Fargate profiles
AWS, per pod
Small 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 (authenticationModeAPI 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.
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.
vCPU
Memory (GB)
Notes
0.25
0.5, 1, 2
Linux only.
0.5
1–4
1 GB steps.
1
2–8
Linux or Windows.
2 / 4
4–16 / 8–30
1 GB steps.
8
16–60
4 GB steps; Linux platform 1.4.0+.
16
32–120
8 GB steps.
32
60, 120 or 244
Newest 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.
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).
Knob
Value
Notes
Memory / CPU
128–10,240 MB
CPU scales with memory; 1 vCPU at 1,769 MB.
Timeout
900 s
Hard cap for classic functions.
Payload
6 MB sync, 1 MB async, 200 MB streamed response
Async was 256 KB until Oct 2025. Streaming is for Node.js managed runtimes (or custom runtime / Lambda Web Adapter).
5 layers per function. Env vars 4 KB total. /tmp 512–10,240 MB.
Concurrency
1,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 / provisioned
Reserved: free. Provisioned: billed while allocated
Provisioned 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).
Limit
Value
Note
Object size
0 B – 50 TB
Raised 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 parts
5 MiB – 5 GiB per part (last part may be smaller)
Key length
1,024 bytes
UTF-8 encoded
Request rate
3,500 write / 5,500 read per prefix per second
Auto-partitions; transient 503 SlowDown while it scales; no cap on prefixes per bucket
General purpose buckets
10,000 per account (default)
Soft quota, raisable via Service Quotas up to 1 million; the old “100 buckets” figure is obsolete
Replication SLA
RTC: 99.99% of objects in 15 min
SLA 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.
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.
Type
Size
Max IOPS
Max MiB/s
Notes
gp3
up to 64 TiB
80,000
2,000
Baseline 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 Express
4 GiB – 64 TiB
256,000
4,000
Sub-ms latency, 1,000 IOPS per GiB, Multi-Attach, boot OK; Nitro instances only for the top range
io1
4 GiB – 16 TiB
64,000
1,000
50 IOPS per GiB; legacy, prefer io2
gp2
up to 16 TiB
16,000
250
3 IOPS per GiB with burst credits; migrate to gp3
st1 / sc1
125 GiB – 16 TiB
500 / 250
500 / 250
HDD, 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).
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 mode
Regional per-FS max (read / write)
Billing
Use when
Elastic (recommended)
20–60 GiBps / 1–5 GiBps by Region (quota-raisable)
Per GiB read/written, no credits
Spiky or unpredictable; average-to-peak under ~5%
Provisioned
3–10 GiBps / 1–3.33 GiBps
Fixed MiBps-month above the baseline your storage earns
Known steady load; average-to-peak above ~5%
Bursting
3–5 GiBps / 1–3 GiBps
Included; baseline 50 KiBps per GiB stored, burst via credits
Throughput 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
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.
Class
Access
Min duration
Gotcha
Glacier Instant Retrieval
Milliseconds, no restore step
90 days
128 KB minimum billable object size
Glacier Flexible Retrieval
Restore 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 Archive
Restore first: Standard within 12 h, Bulk within 48 h; no Expedited
180 days
Same ~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.
Item
Value
Note
Max item size
400 KB
Includes attribute names; park blobs in S3, keep the key
Read units (per 4 KB)
0.5 eventual, 1 strong, 2 transactional
Same ratios for RCU and RRU
Write units (per 1 KB)
1 standard, 2 transactional
Rounded up per item
Per-partition ceiling
3,000 RCU / 1,000 WCU
A hot key throttles even with spare table capacity
Per-table default (on-demand and provisioned)
40,000 read / 40,000 write units
Adjustable quota; account cap 80,000 applies to provisioned only
Indexes per table
20 GSI (default quota), 5 LSI
LSI must be created with the table
Tables per Region
2,500 initial
Raisable toward 10,000 via account team
TransactWriteItems
100 actions, 4 MB aggregate
Same Region and account only
PITR window
1 to 35 days (configurable)
Per-second restore granularity
Streams retention
24 hours
Longer 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.
Need
Pick
Why
Disposable cache in front of a DB
ElastiCache Valkey, durability off
Cheapest; data is reconstructable
Spiky or unknown load, no ops
ElastiCache Serverless
Scales on demand; pay for ECPU and GB-hours
Redis-compatible primary store
MemoryDB, or ElastiCache Valkey 9 sync durability
Multi-AZ log; compare features, SLA and cost for your Region
Microsecond reads in front of DynamoDB only
DAX
API-compatible, no cache-aside code
Giant, simple, multi-threaded string cache
Memcached
No replication or persistence, so node loss loses its shard
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.
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).
Topology
Failover (typical)
Readers
Note
RDS Multi-AZ instance
60–120 s (CNAME flip)
Standby is not readable
HA only; add read replicas separately
RDS Multi-AZ DB cluster
Under 35 s
2 readable standbys
MySQL and PostgreSQL
Aurora cluster
Tens of seconds with a healthy replica
Up to 15, one shared volume
AWS guidance ranges from under 30 s to under 120 s; promote by tier, retry in the client
Cross-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.
-- 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 type
Reaches
Mechanism
Cost model
Gateway
S3, DynamoDB only
Route-table prefix-list target; not PrivateLink; VPC-local only
ENI per AZ + private DNS; cross-Region supported for NLB-based services and a list of AWS services
Per AZ-hour + per GB
Gateway Load Balancer
Appliance fleet behind a GWLB
Route-table target, GENEVE
Per hour + per GB
Resource
A single DB, IP or DNS name in another VPC or on-prem (no load balancer needed)
Resource gateway + resource configuration; works over DX/VPN
See VPC pricing page
Service network
Many VPC Lattice services and resources through one endpoint
One ENI set; reachable from on-prem over DX/VPN
See 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 / feature
REST API
HTTP API
WebSocket API
Integration timeout
50 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 min
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).
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).
Origin
Lock it to CloudFront with
Notes
S3 bucket
Origin Access Control (OAC), bucket policy on cloudfront.amazonaws.com + AWS:SourceArn
OAC supports SSE-KMS, PUT/POST/DELETE and Regions launched after Dec 2022; OAI is legacy
Lambda function URL, MediaStore, MediaPackage v2
OAC
Signs origin requests with SigV4
ALB, NLB or EC2 in a private subnet
VPC origin
No public IP or IGW needed; shareable via RAM; no extra CloudFront fee
Public custom origin
Security group on the com.amazonaws.global.cloudfront.origin-facing prefix list + secret origin header
Prefix 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
}
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.
Need
Tool
Mechanism and catch
Automatic multi-Region failover
Failover/latency records + health checks
Data-plane; recovery = TTL + interval × threshold. Alias records have no TTL of their own: ELB targets use a fixed 60 s
Controlled, human-triggered Region cutover
ARC routing controls
On/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 AZ
ARC zonal shift / zonal autoshift
ALB, 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 outage
Accelerated 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 capacity
ARC readiness check
Closed 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.
Control
Limits
Grants?
Scope / catch
SCP
Principals in member accounts
No
Not applied to the management account; does not affect service-linked roles
RCP
Resources in member accounts, regardless of caller (including outside the org)
No
Subset 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 boundary
One user/role
No
Intersects with identity policy; does not cap a resource policy that names the session/user ARN directly
Session policy
One STS session
No
Passed 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.
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):
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.
On-demand only, after importing new material; you manage expiry
HMAC
Generate/verify MACs
Manual (new key)
Asymmetric RSA / ECC
Sign/verify, RSA encrypt, ECC key agreement; public key exportable
Manual (new key)
ML-DSA 44/65/87
Post-quantum sign/verify
Manual (new key)
Custom key store: CloudHSM or XKS
Keys held in your HSM cluster or external manager
Manual / 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 keys
100,000 (adjustable)
Aliases per KMS key / grants per KMS key
50 / 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 operations
1,000/s each family
Per custom key store (CloudHSM or XKS), also counts toward the symmetric quota
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.
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 Control
Common: labels and blocks self-identifying bots. Targeted: adds fingerprinting, behavioural heuristics, optional ML rules, with rate limit plus CAPTCHA/Challenge
Paid 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 accounts
You must tell the group the login/sign-up path and payload field names; use the JS/mobile SDK for full signal
Anti-DDoS rule group
L7 DDoS: builds a traffic baseline, soft mitigation (silent challenge) then hard block
Place near the top; do not add a scope-down statement (skews the baseline)
CAPTCHA vs Challenge
CAPTCHA = visible puzzle. Challenge = silent browser check. Both issue a token
Immunity 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.
# 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.
Product
What you get
Note
Event history
Last 90 days of management events per Region, console/LookupEvents
Free, no setup, not durable beyond 90 days
Trail
Durable delivery to S3, optionally CloudWatch Logs and EventBridge
First copy of management events per Region free; extra copies, data events and Insights are billed
Insights events
Anomaly 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 events
API calls made through VPC endpoints, including denied ones
Opt-in via event selectors on a trail
CloudTrail Lake
Managed event data store queried with SQL
Closed 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
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.
Audit, compliance, forensic logs queried ad hoc; ingestion about half of Standard, same storage and Insights charges
Subscription filters and S3 export, metric filters/alarming, Live Tail, GetLogEvents/FilterLogEvents, Contributor/Container/Lambda Insights; data protection policies cost extra per GB
Delivery
Lambda logs routed only to S3 or Firehose; kept in CloudWatch for 1 day
Insights 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.
Limit
Value
PutMetricData request
1 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 periods
10, 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 alarm
References at most 10 metrics (hard)
EMF
DimensionSet at most 30 keys; every distinct DimensionSet becomes a separate billable custom metric
Log event / PutLogEvents batch
1,024 KB per event; 1 MB per batch; 5,000 PutLogEvents calls/s per Region (adjustable)
Metric filters per log group; Live Tail sessions
100 (hard); 15 concurrent per account (adjustable)
Logs Insights query runtime
Times 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).
Limit
Value
Note
Max message size
1 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
Retention
60 s to 14 days, default 4 days
DLQ expiry counts from the original enqueue time on standard queues
Visibility timeout
0 s to 12 h, default 30 s
Lambda: set at least 6x the function timeout
Long poll / delay
1–20 s wait; 0–15 min delay
Always long poll (ReceiveMessageWaitTimeSeconds=20)
In flight
~120,000 standard; 120,000 FIFO
Soft; raise via support. Batch API calls max 10 messages
FIFO throughput
300 TPS per partition per API action; 3,000 msg/s batched
High-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.
Dimension
Standard topic
FIFO topic
Ordering / delivery
Best-effort, at-least-once
Strict order per message group, dedup
Subscribers
SQS, Lambda, HTTP/S, Firehose, email, SMS, push
SQS FIFO and standard queues only; Lambda via an SQS queue; no email, SMS, push or HTTP/S
Default 3,000 msg/s or 20 MB/s per topic; FifoThroughputScope=MessageGroup lifts it to the account quota, 300 msg/s per group
Limits
100,000 topics; 12.5M subscriptions per topic
1,000 topics; 100 subscriptions per topic
Archive and replay
Not available
1–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.
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).
Choice
Facts (checked 2026-10)
Serverless: Classic
1 OCU = 6 GiB memory plus vCPU; minimum 2 OCUs always on; Classic collections can still be created standalone
Serverless: NextGen
Collections 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 limits
OCU 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 families
General/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 scale
Up 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 rules
Shards 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)
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.
Phase
What you stand up
Gate (done when)
0. Landing zone & identity
Organizations + 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. Network
3-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 baseline
KMS 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 layer
Aurora/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 & package
Multi-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. Deploy
ECS, EKS or Lambda path (below).
Alarm-gated rollout with a tested rollback.
6. Edge
CloudFront 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. Observability
RED + 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 & DR
Tag 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.
# 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.
Tool
Failure it handles
How it works
Sharp edge
Route 53 health-check failover
Endpoint unhealthy
Automatic, data plane only; record answers switch when the check fails
Cannot be flipped on purpose; a bad health check endpoint flaps traffic
ARC routing controls
Region or cell failover you decide to make
On/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 off
Flip 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 / autoshift
One impaired AZ behind an ALB/NLB
Shifts 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 runs
Opt 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 switch
Multi-Region app recovery as a runbook
Plans → 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 execution
Does not guarantee compute capacity arrives; reserve capacity in the standby Region for critical tiers
AWS Elastic Disaster Recovery
Servers (on-prem, EC2, other clouds) with no native replication
Continuous block-level replication into a low-cost staging area; launch converted instances on demand
Docs: RPO of seconds, RTO typically 5–20 min; replication keeps running while you launch drill instances
AWS Backup logically air-gapped vault
Ransomware, stolen credentials, account lockout
Immutable 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:
Mechanism
You own
Notes
DynamoDB Streams + Lambda event source mapping
The sync code
Stream 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 Pipes
The pipe config
Managed 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 OpenSearch
Almost nothing
An 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.
# 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.
Model
What is shared
Isolation boundary
Cost / ops
Noisy neighbor
Pick when
Silo
Nothing; dedicated stack per tenant (stack in one account, or an account per tenant)
Infrastructure: account, VPC, IAM boundary
Highest; N deployments to patch and observe, automation mandatory
Eliminated
Regulated or large enterprise tenants, per-tenant SLAs, per-tenant cost proof
Pool
Everything: compute, tables, buckets
Logical: tenant id in key/row, enforced by IAM or database policy
Lowest; onboarding is a row, not infrastructure
Mitigated, never eliminated
Many small, similar tenants; cost-sensitive tiers
Bridge
Some layers shared, some per tenant (shared web/app tier, database per tenant) or silo for premium tiers and pool for basic
Mixed, chosen per service
Middle; most real systems end here
Isolated where it hurts
One 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:
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.
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.
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.
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.
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.
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.
Is there a managed AWS service for it? If yes, it is the default. Self-managing is the exception you must justify.
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.
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.
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.
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. Growth
ECS 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. Scale
ECS 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.
Bedrock 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.
Across instance families and Regions inside SageMaker
See plan-types page
Database Savings Plan
Aurora, RDS, DynamoDB, ElastiCache, DocumentDB, Neptune, Keyspaces, Timestream, DMS, OpenSearch Service — serverless and latest-generation provisioned
Any engine, family, size, deployment option, Region; 1-year term, no upfront
Up to 35%
Reserved Instances / reserved capacity
Specific instance or service capacity
Low; Convertible RIs can be exchanged
Up 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:
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.
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.
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.
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.
Keep a floor. A small On-Demand base so the service stays up when a pool dries up; Spot for everything above it.
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.
Draw the line. Everything new is IaC from today. No exceptions, no “just this one bucket”.
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.
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).
Make the pipeline the only writer. Org-level guardrails deny mutating calls from everyone except the pipeline and a break-glass role.
Detect residual drift on a schedule and decide per finding: revert the resource, or adopt the change into code.
Need
CloudFormation / CDK
Terraform
Adopt existing resources
IaC 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 change
Change set
terraform plan (saved plan file for the apply step)
Detect drift
Drift 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 locking
Managed by the service; none to operate
Remote state in S3; prefer native use_lockfile — DynamoDB-based locking is deprecated and scheduled for removal in a future minor version
Multi-account rollout
StackSets or a pipeline per account
One pipeline and state per account/environment; modules for reuse
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.
Option
How it works
You get
Watch for
Internal ALB / NLB
Service 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 Connect
ECS 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 Lattice
ECS 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")
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.
Path
Who retries
How it scales
Where 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.
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.
Control
Effect
Use 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 concurrency
Hard 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.
"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.
Option
Model and concurrency
Billing
Pick 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 Instances
Event 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 Functions
Your 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.
MicroVMs
Stateful 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
Tool
What it does
Constraint
SnapStart
Restores 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 concurrency
Keeps N environments initialized.
Billed while allocated; version or alias only.
Response streaming
Cuts 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.
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:
Header
Meaning
Permissions
Typical use
If-None-Match: *
Write only if no current object has this key (create-if-absent)
s3:PutObject
Claim 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:GetObject
Optimistic 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.
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.
Dimension
General purpose bucket (Standard)
Directory bucket (Express One Zone)
Placement
Regional, ≥3 AZs
One AZ you pick; name base--use1-az4--x-s3
Latency
Milliseconds, higher and more variable than Express
Consistent single-digit ms; docs cite up to 10x faster than Standard
Request rate
3,500 write / 5,500 read per prefix, auto-partitioned
Up to 2,000,000 GET and 200,000 PUT per second per bucket; no prefix tuning, keys not lexicographically ordered in LIST
Namespace
Flat keys, prefixes
Hierarchical directories (/ only delimiter), created and removed automatically
AuthN/Z
SigV4 per request
s3express:CreateSession, 5-minute bucket-scoped session credentials handled by the SDK
Access boundary
Bucket, prefix, tag, object
Bucket 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 task
What it does
Defaults and knobs
Compaction
Merges small files into larger ones and applies row-level deletes
Target 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 management
Expires old Iceberg snapshots
Keeps at least 1 snapshot; default max age 120 hours (5 days); both configurable per table
Unreferenced file removal
Deletes data files no snapshot references
Marked 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).
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.
Limit
Value
Vector buckets per Region per account / indexes per bucket
10,000 / 10,000
Vectors per index
Up to 2 billion (20 trillion per bucket)
Dimensions
1–4,096; float32 only; cosine or euclidean
Metadata per vector
40 KB total, 50 keys, filterable part 2 KB; up to 10 non-filterable keys per index
Write path
500 vectors per PutVectors; up to 1,000 put/delete requests per second per index (2,500 vectors per second)
Query
Top-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"]])
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.
Control
Who can remove or shorten it
Typical use
Governance retention
Principals 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 retention
Nobody, including root: mode cannot change and the period cannot shorten (it can be extended). Only closing the AWS account deletes the data early
Regulatory WORM
Legal hold
Anyone with s3:PutObjectLegalHold; no expiry, independent of retention
Litigation freeze of specific versions
Event hold (variable retention)
Released by authorized principals; retain-until-date is set to release time plus a preset duration
Retention 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.
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.
Need
Feature
Detail
Existing objects, failed objects, replicas of replicas
Batch Replication
On-demand S3 Batch Operations job; live rules only cover new objects, and a replica is not re-replicated by a chained rule
Predictable lag
Replication 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-active
Two-way rules + replica modification sync
One rule each direction; sync carries tag, ACL and Object Lock metadata changes made on replicas back to the source
Encrypted objects
SSE-KMS replication settings
KMS-encrypted objects are skipped unless SseKmsEncryptedObjects and a destination key are configured
Deletes
DeleteMarkerReplication
V2 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.
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.
Option
Semantics
Data lives in
Pick when
Mountpoint for S3
Object-native: read large files, create new ones; no in-place edits, no locking, no symlinks
S3
Read-heavy ML/analytics streaming from one writer, lowest cost
S3 Files
Full NFS semantics, shared by thousands of clients, synced to S3
S3 (hot working set cached on file storage)
File-based tools and agents that must operate on existing S3 data without copying
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
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)
Capability
Purpose
Key facts
Snapshots Archive
Cheaper long-term retention
Archived 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 Bin
Undo accidental deletes
Tag-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 Lock
WORM / ransomware protection
Governance (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 volumes
Enabled per snapshot per AZ; volumes are fully initialized at creation; default quota 5 FSR snapshots per Region
Volume initialization rate
Predictable lazy-load speed
Provisioned 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 Manager
Automate all of the above
Tag-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.
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.
Class
First-byte latency
Per-file billing floor
Minimum duration
Availability
Standard (SSD)
Sub-millisecond reads, ~2.7 ms writes
none
none
99.99% Regional / 99.9% One Zone
Infrequent Access
Tens of ms
128 KiB; 2 KiB of metadata stays in Standard
none
99.99% Regional / 99.9% One Zone
Archive
Tens of ms
128 KiB; 2 KiB metadata in Standard
90 days (pro-rated charge if deleted or truncated earlier)
99.9%, Regional only
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.
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.
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.
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.
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 pattern
Best fit
Why
Unknown or shifting
S3 Intelligent-Tiering
No 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
Bulk retrieval is free; Expedited for urgent needs; 90-day minimum
Less than once per year, compliance, tape replacement
Glacier Deep Archive
Lowest 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.
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.
Dimension
Valkey
Redis OSS
Memcached
Newest on ElastiCache
9.1 (also 7.2.6, 8.0, 8.1, 8.2, 9.0)
7.1
1.6.x
Price vs Redis OSS
Node-based 20% lower; Serverless 33% lower
Baseline
Separate price list
Serverless minimum metered storage
100 MB
1 GB
1 GB
Support lifecycle
Current
v4 and v5 left standard support 2026-01-31 (Extended Support, rising annual premium); v6 standard support ends 2027-01-31
Per version schedule
Replication, persistence
Multi-AZ, snapshots; optional durability on 9.0+
Multi-AZ, snapshots
None
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:
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.
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.
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.
Verify CacheHits, CacheMisses and EngineCPUUtilization; Redis OSS Reserved Nodes keep applying and cover more Valkey capacity because Valkey units are cheaper.
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.
Strategy
Write path
Failure mode
Use when
Cache-aside
App writes DB, then deletes the key
Stale until TTL after the race below
Default for read-heavy data
Read-through
Cache layer loads on miss
Same as cache-aside; couples cache to the loader
Shared library or DAX-style front cache
Write-through
App writes DB and cache together
Unread keys waste memory; partial failure leaves them diverged
Read-after-write must be fresh
Write-behind
Write cache, flush to DB later
Acknowledged writes lost if the cache node dies first
Counters, analytics, only with durable queueing or Valkey 9 sync durability
Refresh-ahead
Background reload before expiry
Needs hot-key telemetry; wasted loads
Few 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.
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.
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.
Service
Model
Pick when
Facts to know
DocumentDB
JSON documents, MongoDB API
Migrating MongoDB apps; rich queries and aggregations on nested data
Compatible 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.
Neptune
Property graph (Gremlin, openCypher) and RDF (SPARQL)
One 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 Analytics
In-memory graph analytics plus vector search
GraphRAG: vector similarity combined with traversals and graph algorithms in one query
HNSW vector index, up to 65,000 dimensions, callable from openCypher.
Keyspaces
Wide-column, Cassandra (CQL)
Moving Cassandra without running nodes
Serverless; no compaction, tombstone or GC tuning; writes replicated three times across AZs; multi-Region replication available.
Timestream
Time series
Metrics and IoT history
Timestream 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.
MemoryDB
Durable Valkey/Redis-compatible store
Redis APIs as the primary database; microsecond key reads, single-digit-millisecond vector search
Multi-AZ transaction log; HNSW vector search; compare against ElastiCache Valkey 9 durability (see ElastiCache).
QLDB
Ledger (retired)
Do not choose
End 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
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.
Option
What scales
Writers
Trade-offs
Bigger writer plus up to 15 Aurora readers
Reads, then vertical writes
1
Simplest; hits the single-writer ceiling
Aurora Global Database
Cross-Region reads and DR
1 (primary Region)
Cross-Region lag typically under a second; switchover or failover to move the writer
Aurora PostgreSQL Limitless
Write throughput and storage by sharding
Many shards behind routers
PostgreSQL only; sharded, reference and standard tables; shard keys cannot be updated; serializable isolation unsupported; shard-group capacity 16–6,144 ACUs
Key-value scale and multi-Region strong consistency
Any replica
No 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.
Flow hash, 5-tuple stickiness by default (3- or 2-tuple optional)
Target types
Instance, IP, Lambda
Instance, IP, ALB
Instance, IP
Addresses
DNS name only; IPs change
One static IP per AZ; Elastic IPs for internet-facing, chosen private IPs for internal
Reached through GWLB endpoints (PrivateLink), not by clients
Client IP
In X-Forwarded-For
Client IP preservation is a target-group setting (always on for UDP and QUIC groups)
Original packet preserved end to end
Auth / TLS
Terminates TLS; Cognito, OIDC and JWT-validation actions; mTLS (verify or passthrough); WAF
TLS listener or passthrough to targets that terminate
None; the appliance inspects
Cross-zone default
Always on at LB level (can turn off per target group); no inter-AZ charge
Off; enabling it incurs inter-AZ data transfer charges
Off; set at LB level
Idle timeout
60 s default
TCP 350 s (60–6000 configurable), UDP 120 s
Flow-based; tune keep-alives on appliances
Pick it for
Web apps, microservices, Lambda front ends, blue/green by weight
Non-HTTP protocols, static IP allow-listing, PrivateLink services, extreme connection counts
Inline 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.
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 VPN
Direct Connect (DX)
DX + encryption
Path
IPsec over the internet; two tunnels per connection
Private fibre via a DX location; no internet hop
Same circuit; MACsec (L2) or IPsec over it
Throughput
1.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 routing
Dedicated 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
Latency
Internet variability
Consistent, predictable
Consistent
Provisioning
Minutes
Cross-connect plus often a carrier circuit; plan for long lead time
Add after DX is up
Best for
Start-up path, DR backup for DX, low or moderate bandwidth
Sustained high bandwidth, steady latency, large data transfers
Compliance 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.
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.
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.
Gateway endpoints for S3 and DynamoDB in every route table: no hourly or processing charge, and the traffic never meets the NAT.
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.
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.
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.
Mode
Where it lives
IPs
Choose when
Zonal, public
One public subnet in one AZ
Elastic IPs, 2 default, up to 8
You want fixed per-AZ source IPs or per-subnet isolation
Zonal, private
One private subnet
Private IPs only
Overlapping-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 AZ
Default for new internet egress; fewer moving parts. Does not support private NAT
Regional (manual)
Same
You associate IPs per AZ
Allow-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
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).
Symptom
Usually means
First suspects
Hangs, then timeout
Packets 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 reset
Nothing listening, wrong port, listening on 127.0.0.1, OS firewall
Intermittent drops under load
A per-instance or per-gateway allowance is exhausted
Conntrack, bandwidth or packet-rate allowance; NAT port exhaustion; DNS packet limit
5xx from a load balancer
Target unhealthy, or idle timeout shorter than backend keep-alive
Health check path and port, SG from LB to targets, ALB 60 s idle vs backend keep-alive
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.
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.
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).
NACL: both directions and the ephemeral range, rule order (lowest number wins).
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).
Service
Question it answers
What it reads
Catch
GuardDuty
Is 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
Inspector
Which 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 IaC
Rescans when a new CVE is published. Lambda scanned only if invoked or updated in the last 90 days
Macie
Where 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 lists
Not for RDS, DynamoDB or EBS. Sampling is not a full scan
Security Hub
What 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 ASFF
Two generations coexist; do not confuse "Security Hub" with "Security Hub CSPM" in docs or pricing
Detective
How 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 findings
Investigation, not detection; needs GuardDuty history to be most useful
Security Lake
Can I query all security telemetry in one place?
Normalizes AWS, SaaS and on-prem sources to OCSF into S3 in your account
A 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.
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".
Control
Layer / scope
Stateful?
Use it for
Shield Standard / Advanced
L3/L4 (Advanced also L7 with WAF); edge resources
Managed
Volumetric 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)
WAF
L7 HTTP(S); CloudFront, ALB, API GW REST, AppSync, Cognito
Deploys 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.
Framework
AWS provides
You must implement and evidence
SOC 1/2/3, ISO 27001, PCI DSS (AWS is a Level 1 service provider), FedRAMP
Independent audit reports and certificates, downloadable from AWS Artifact
Your own scope: access control, encryption, logging, change management. AWS reports cover only AWS's layer
HIPAA
Business Associate Addendum accepted in Artifact (per account or organization-wide); list of HIPAA-eligible services
Use only eligible services for PHI, encrypt, audit access, train staff. Having a BAA does not make every service in scope for PHI
PCI DSS
Attestation of compliance for AWS infrastructure
Cardholder-data scope, segmentation, key management, tokenization to shrink scope
GDPR
Data Processing Addendum incorporated in the AWS Service Terms and applied automatically; Standard Contractual Clauses for transfers
Lawful 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.
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.
setSecret — the function changes the credential in the real system (database user, API provider) to the pending value.
testSecret — the function connects with the pending credential to prove it works.
finishSecret — the function moves AWSCURRENT to the new version; Secrets Manager automatically puts AWSPREVIOUS on the old one, keeping a last-known-good copy.
Strategy
How it works
Trade-off
Single user
Rotates the one user's password in place
Simple, but there is a short window where connections holding the old password fail until they refetch
Alternating users
First rotation clones the user (suffix _clone), then each rotation updates the other user; one credential is always valid while the other is tested
Higher 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.
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.
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.
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.
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.
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.
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.
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).
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.
Symptom
Most likely layer
Fast check
Connection times out
SG, NACL, route or no public IP
Flow Logs REJECT; Reachability Analyzer
Connection refused
Network is fine; nothing listening
OS service and port; SG is not the cause
Permission denied (publickey)
Key pair, user name or authorized_keys
Correct default user for the AMI; EC2 Instance Connect
Instance status check fails
Guest OS (kernel panic, fstab, disk)
Console output or screenshot; rescue via another instance
System status check fails
AWS host
Stop then start to migrate hosts
Works one way only
NACL missing return ephemeral ports
Compare 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.
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
Target account creates a role whose trust policy names the caller (an account root, a role ARN, or a service principal).
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.
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:
Deputy
Guard
Where it goes
Third-party SaaS in another account
sts: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)
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.
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.
Training and inference of Neuron-supported transformers at lower cost per token; see Neuron SDK
Trn3 UltraServers
Trainium3 (3 nm), 144 GB HBM3e per chip; up to 144 chips per UltraServer
NeuronSwitch-v1 all-to-all fabric, NeuronLink-v4
Largest Neuron training/inference, MoE and long-context models; native PyTorch and JAX
Inf2
Up to 12x Inferentia2, 32 GiB each (384 GiB)
No EFA
Single-node, cost-optimized inference
P4d/P4de, G5, G6, G4dn, Trn1
A100 / A10G / L4 / T4 / Trainium1
EFA on P4d, Trn1, larger G sizes
Older but widely available; cheap prototyping
Getting capacity is a ladder, from cheapest and least certain to most certain:
Spot for interruptible, checkpointed training (not offered on P6e-GB200 or Trn2u). Use price-capacity-optimized allocation and several instance types.
On-Demand works until the Region runs out of that GPU; there is no guarantee.
On-Demand Capacity Reservations guarantee capacity while held, billed whether used or not; best for steady inference fleets.
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.
SageMaker training plans / HyperPod for managed jobs: Capacity Blocks cannot be used with SageMaker-managed ml.* instances.
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
Audit operator coverage. Trace or compile the model on a small Inf2/Trn instance; unsupported ops or custom CUDA kernels are the usual blockers.
Fix shapes. Choose batch sizes and sequence-length buckets that match production traffic; each bucket is a separate compiled artifact.
Pick precision. BF16 or FP8 where the hardware supports it; validate accuracy against the GPU baseline before comparing cost.
Cache compiled artifacts (S3 or the image) so cold starts and autoscaled replicas do not recompile.
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"
Situation
Choose
Standard transformer, steady high volume, team can own a compile pipeline
Inf2 for inference, Trn2/Trn3 for training and large serving
Custom CUDA kernels, FlashAttention variants, bleeding-edge research code
NVIDIA P/G families
Highly dynamic shapes or frequent model changes
NVIDIA (or Neuron with bucketing and a build pipeline)
Want Neuron economics without running the stack
Bedrock 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
Workload
Rule
7B model
70B model
Training, FP16/BF16 + Adam
About 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, FP16
2 bytes per parameter
14 GB
140 GB
Inference weights, FP8/INT8
1 byte per parameter
7 GB
70 GB
Inference weights, INT4
0.5 byte per parameter
3.5 GB
35 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
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.
Fused attention.F.scaled_dot_product_attention picks FlashAttention-2 or memory-efficient kernels on CUDA automatically; do not hand-roll attention.
Activation checkpointing. Trades recompute for memory: activations are discarded in the forward pass and recomputed in the backward pass. Pass use_reentrant=False explicitly.
Gradient accumulation. Larger effective batch at the memory cost of a small micro-batch.
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.
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
GPU utilization.nvidia-smi dmon or DCGM metrics; sustained under about 80% means the GPU is waiting.
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.
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.
Batch size too small leaves kernels short and launch-bound; grow it until memory is the limit, then accumulate.
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.
Object
What it is
Knobs that matter
Compute environment (CE)
Pool of compute: managed EC2 (On-Demand or Spot), Fargate / Fargate Spot, EKS, or unmanaged
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.
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
Need
AWS Batch
ECS/Fargate services or Lambda + SQS
Fan out 10,000 tasks from one call
Native array job
You build the fan-out
Queueing, priorities, fair share
Built in
External queue and your logic
Job dependencies / DAG
dependsOn, N_TO_N
Step Functions
GPUs
EC2 or EKS compute environments
ECS on EC2 only; Fargate and Lambda have no GPU
Long-running service or sub-second latency
Wrong tool
Right 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.
Primitive
Shape
Limits to remember
Pick it when
Parallel state
Fixed, different branches
Branches are known at design time
Run image, text and audio steps side by side
Map, Inline mode
Same steps per array item, in the parent's history
40 concurrent iterations; 256 KiB input; 25,000 history events
Small arrays (tens to a few hundred items)
Map, Distributed mode
Each item (or batch) is a child workflow execution with its own history
Up to 10,000 parallel children; reads S3 object list, S3 inventory, CSV, JSON file, Athena manifest/Parquet directly
Thousands to millions of S3 items, each under minutes, no GPU
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.ExecutionTypeEXPRESS 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.
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